public synchronized CryptoKey getOrCreateCryptoKey(String keyRingId, String keyName) {

    // Get the keyring, creating it if it does not already exist
    if (keyRing == null) {
      maybeCreateKeyRing(keyRingId);
    }

    try (KeyManagementServiceClient client = clientFactory.getKMSClient()) {

      // Build the symmetric key to create.
      CryptoKey keyToCreate =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(
                          CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
              .build();

      LOG.info("Checking if symmetric key {} already exists in KMS.", keyName);

      // Loop through the existing keys in the given keyring to see if the
      // key already exists.
      String newKeyName = CryptoKeyName.of(projectId, region, keyRingId, keyName).toString();
      Optional<CryptoKey> existingKey =
          StreamSupport.stream(
                  client.listCryptoKeys(keyRing.getName()).iterateAll().spliterator(), false)
              .filter(kRing -> kRing.getName().equals(newKeyName))
              .findFirst();

      // Create the symmetric key if it does not exist, otherwise, return the found key.
      CryptoKey cryptoKey;
      if (!existingKey.isPresent()) {
        LOG.info("Symmetric key {} does not exist. Creating the key in KMS.", keyName);
        cryptoKey = client.createCryptoKey(keyRing.getName(), keyName, keyToCreate);
        LOG.info("Created symmetric key {}.", cryptoKey.getName());
      } else {
        LOG.info("Symmetric key {} already exists. Retrieving the key from KMS.", keyName);
        cryptoKey = existingKey.get();
        LOG.info("Retrieved symmetric key {}.", cryptoKey.getName());
      }

      return cryptoKey;
    }
  }
@Test
  public void testGetOrCreateCryptoKeyShouldNotCreateKeyRingWhenItAlreadyExists() {
    KeyRing keyRing =
        KeyRing.newBuilder()
            .setName(KeyRingName.of(PROJECT_ID, REGION, KEYRING_ID).toString())
            .build();
    when(kmsClientFactory.getKMSClient()).thenReturn(serviceClient);
    when(serviceClient.listKeyRings(any(LocationName.class)).iterateAll())
        .thenReturn(ImmutableList.of(keyRing));

    testManager.getOrCreateCryptoKey(KEYRING_ID, KEY_ID);
    verify(serviceClient, never())
        .createKeyRing(any(LocationName.class), anyString(), any(KeyRing.class));
  }