comment
stringlengths
1
45k
method_body
stringlengths
23
281k
target_code
stringlengths
0
5.16k
method_body_after
stringlengths
12
281k
context_before
stringlengths
8
543k
context_after
stringlengths
8
543k
why this `jaas.getOptions().get(jaas.getOptions())`?
private boolean meetJaasConditions(String jaasConfig) { if (jaasConfig == null) { return true; } AtomicBoolean flag = new AtomicBoolean(false); JaasResolver resolver = new JaasResolver(); resolver.resolve(jaasConfig).ifPresent(jaas -> { if (AZURE_CONFIGURED_JAAS_OPTIONS_VALUE.equals(jaas.getOptions().get(jaas.getOptions()))) { flag.set(true); } }); return flag.get(); }
}
private boolean meetJaasConditions(String jaasConfig) { if (jaasConfig == null) { return true; } JaasResolver resolver = new JaasResolver(); return resolver.resolve(jaasConfig) .map(jaas -> AZURE_CONFIGURED_JAAS_OPTIONS_VALUE.equals( jaas.getOptions().get(AZURE_CONFIGURED_JAAS_OPTIONS_KEY))) .orElse(false); }
class AbstractKafkaPropertiesBeanPostProcessor<T> implements BeanPostProcessor { static final String SECURITY_PROTOCOL_CONFIG_SASL = SASL_SSL.name(); static final String SASL_MECHANISM_OAUTH = OAUTHBEARER_MECHANISM; static final String AZURE_CONFIGURED_JAAS_OPTIONS_KEY = "azure.configured"; static final String AZURE_CONFIGURED_JAAS_OPTIONS_VALUE = "true"; static final String AZURE_CONFIGURED_JAAS_OPTIONS = AZURE_CONFIGURED_JAAS_OPTIONS_KEY + "=\"" + AZURE_CONFIGURED_JAAS_OPTIONS_VALUE + "\""; static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH = KafkaOAuth2AuthenticateCallbackHandler.class.getName(); protected static final PropertyMapper PROPERTY_MAPPER = new PropertyMapper(); private static final Map<String, String> KAFKA_OAUTH_CONFIGS; private static final String LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE = "OAUTHBEARER authentication property {} will be configured as {} to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE = "Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication will be loaded to configure your Kafka security and sasl properties to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION = "Currently {} authentication mechanism is used, recommend to use Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication" + " which supports various Azure Identity credentials. To leverage the auto-configuration for OAuth2, you can just remove all your security, sasl and credential configurations of Kafka and Event Hubs." + " And configure Kafka bootstrap servers instead, which can be set as spring.kafka.boostrap-servers=EventHubsNamespacesFQDN:9093."; static { Map<String, String> configs = new HashMap<>(); configs.put(SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); configs.put(SASL_MECHANISM, SASL_MECHANISM_OAUTH); configs.put(SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); KAFKA_OAUTH_CONFIGS = Collections.unmodifiableMap(configs); } private final AzureGlobalProperties azureGlobalProperties; AbstractKafkaPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { this.azureGlobalProperties = azureGlobalProperties; } @SuppressWarnings("unchecked") @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (needsPostProcess(bean)) { T properties = (T) bean; replaceAzurePropertiesWithJaas(getMergedProducerProperties(properties), getRawProducerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedConsumerProperties(properties), getRawConsumerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedAdminProperties(properties), getRawAdminProperties(properties)); customizeProcess(properties); } return bean; } /** * Create a map of the merged Kafka producer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka producer properties */ protected abstract Map<String, Object> getMergedProducerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores producer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing producer-specific properties */ protected abstract Map<String, String> getRawProducerProperties(T properties); /** * Create a map of the merged Kafka consumer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka consumer properties */ protected abstract Map<String, Object> getMergedConsumerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores consumer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing consumer-specific properties */ protected abstract Map<String, String> getRawConsumerProperties(T properties); /** * Create a map of the merged Kafka admin properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka admin properties */ protected abstract Map<String, Object> getMergedAdminProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores admin-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing admin-specific properties */ protected abstract Map<String, String> getRawAdminProperties(T properties); protected abstract boolean needsPostProcess(Object bean); protected abstract Logger getLogger(); /** * Process Kafka Spring properties for any customized operations. * @param properties the Kafka Spring properties */ protected void customizeProcess(T properties) { } protected void clearAzureProperties(Map<String, String> properties) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(properties::remove); } /** * This method executes two operations: * <p> * 1. When this configuration meets Azure Kafka passwordless startup requirements, convert all Azure properties * in Kafka to {@link Jaas}, and configure the JAAS configuration back to Kafka. * </p> * <p> * 2. Clear any Azure properties in Kafka properties. * </p> * @param mergedProperties the merged Kafka properties which can contain Azure properties to resolve JAAS from * @param rawPropertiesMap the raw Kafka properties Map to configure JAAS to and remove Azure Properties from */ private void replaceAzurePropertiesWithJaas(Map<String, Object> mergedProperties, Map<String, String> rawPropertiesMap) { resolveJaasForAzure(mergedProperties) .ifPresent(jaas -> { configJaasToKafkaRawProperties(jaas, rawPropertiesMap); logConfigureOAuthProperties(); configureKafkaUserAgent(); }); clearAzureProperties(rawPropertiesMap); } private Optional<Jaas> resolveJaasForAzure(Map<String, Object> mergedProperties) { if (needConfigureSaslOAuth(mergedProperties)) { JaasResolver resolver = new JaasResolver(); Jaas jaas = resolver.resolve((String) mergedProperties.get(SASL_JAAS_CONFIG)) .orElse(new Jaas(OAuthBearerLoginModule.class.getName())); setAzurePropertiesToJaasOptionsIfAbsent(azureGlobalProperties, jaas); setKafkaPropertiesToJaasOptions(mergedProperties, jaas); jaas.getOptions().put(AZURE_CONFIGURED_JAAS_OPTIONS_KEY, AZURE_CONFIGURED_JAAS_OPTIONS_VALUE); return Optional.of(jaas); } else { return Optional.empty(); } } private void configJaasToKafkaRawProperties(Jaas jaas, Map<String, String> rawPropertiesMap) { rawPropertiesMap.putAll(KAFKA_OAUTH_CONFIGS); rawPropertiesMap.put(SASL_JAAS_CONFIG, jaas.toString()); } /** * Configure necessary OAuth properties for kafka properties and log for the changes. */ private void logConfigureOAuthProperties() { getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_MECHANISM, SASL_MECHANISM_OAUTH); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_JAAS_CONFIG, "***the value involves credentials and will not be logged***"); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); } private void setKafkaPropertiesToJaasOptions(Map<String, ?> properties, Jaas jaas) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(k -> PROPERTY_MAPPER.from(properties.get(k)).to(p -> jaas.getOptions().put(k, (String) p))); } private void setAzurePropertiesToJaasOptionsIfAbsent(AzureProperties azureProperties, Jaas jaas) { convertAzurePropertiesToMap(azureProperties) .forEach((k, v) -> jaas.getOptions().putIfAbsent(k, v)); } private Map<String, String> convertAzurePropertiesToMap(AzureProperties properties) { Map<String, String> configs = new HashMap<>(); for (AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping m : AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.values()) { PROPERTY_MAPPER.from(m.getter().apply(properties)).to(p -> configs.put(m.propertyKey(), p)); } return configs; } /** * Configure Spring Cloud Azure user-agent for Kafka client. This method is idempotent to avoid configuring UA repeatedly. */ synchronized void configureKafkaUserAgent() { Method dataMethod = ReflectionUtils.findMethod(ApiVersionsRequest.class, "data"); if (dataMethod != null) { ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest.Builder().build(); ApiVersionsRequestData apiVersionsRequestData = (ApiVersionsRequestData) ReflectionUtils.invokeMethod(dataMethod, apiVersionsRequest); if (apiVersionsRequestData != null) { String clientSoftwareName = apiVersionsRequestData.clientSoftwareName(); if (clientSoftwareName != null && !clientSoftwareName.contains(AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH)) { apiVersionsRequestData.setClientSoftwareName(apiVersionsRequestData.clientSoftwareName() + AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH); apiVersionsRequestData.setClientSoftwareVersion(VERSION); } } } } /** * Detect whether we need to configure SASL/OAUTHBEARER properties for {@link KafkaProperties}. Will configure when * the security protocol is not configured, or it's set as SASL_SSL with sasl mechanism as null or OAUTHBEAR. * * @param sourceProperties the source kafka properties for admin/consumer/producer to detect * @return whether we need to configure with Spring Cloud Azure MSI support or not. */ boolean needConfigureSaslOAuth(Map<String, Object> sourceProperties) { return meetAzureBootstrapServerConditions(sourceProperties) && meetSaslOAuthConditions(sourceProperties); } private boolean meetSaslOAuthConditions(Map<String, Object> sourceProperties) { String securityProtocol = (String) sourceProperties.get(SECURITY_PROTOCOL_CONFIG); String saslMechanism = (String) sourceProperties.get(SASL_MECHANISM); String jaasConfig = (String) sourceProperties.get(SASL_JAAS_CONFIG); if (meetSaslProtocolConditions(securityProtocol) && meetSaslOAuth2MechanismConditions(saslMechanism) && meetJaasConditions(jaasConfig)) { return true; } getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION, saslMechanism); return false; } private boolean meetSaslProtocolConditions(String securityProtocol) { return securityProtocol == null || SECURITY_PROTOCOL_CONFIG_SASL.equalsIgnoreCase(securityProtocol); } private boolean meetSaslOAuth2MechanismConditions(String saslMechanism) { return saslMechanism == null || SASL_MECHANISM_OAUTH.equalsIgnoreCase(saslMechanism); } private boolean meetAzureBootstrapServerConditions(Map<String, Object> sourceProperties) { Object bootstrapServers = sourceProperties.get(BOOTSTRAP_SERVERS_CONFIG); List<String> serverList; if (bootstrapServers instanceof String) { serverList = Arrays.asList(delimitedListToStringArray((String) bootstrapServers, ",")); } else if (bootstrapServers instanceof Iterable<?>) { serverList = new ArrayList<>(); for (Object obj : (Iterable) bootstrapServers) { if (obj instanceof String) { serverList.add((String) obj); } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } } } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } return serverList.size() == 1 && serverList.get(0).endsWith(":9093"); } }
class AbstractKafkaPropertiesBeanPostProcessor<T> implements BeanPostProcessor { static final String SECURITY_PROTOCOL_CONFIG_SASL = SASL_SSL.name(); static final String SASL_MECHANISM_OAUTH = OAUTHBEARER_MECHANISM; static final String AZURE_CONFIGURED_JAAS_OPTIONS_KEY = "azure.configured"; static final String AZURE_CONFIGURED_JAAS_OPTIONS_VALUE = "true"; static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH = KafkaOAuth2AuthenticateCallbackHandler.class.getName(); protected static final PropertyMapper PROPERTY_MAPPER = new PropertyMapper(); private static final Map<String, String> KAFKA_OAUTH_CONFIGS; private static final String LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE = "OAUTHBEARER authentication property {} will be configured as {} to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE = "Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication will be loaded to configure your Kafka security and sasl properties to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION = "Currently {} authentication mechanism is used, recommend to use Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication" + " which supports various Azure Identity credentials. To leverage the auto-configuration for OAuth2, you can just remove all your security, sasl and credential configurations of Kafka and Event Hubs." + " And configure Kafka bootstrap servers instead, which can be set as spring.kafka.boostrap-servers=EventHubsNamespacesFQDN:9093."; static { Map<String, String> configs = new HashMap<>(); configs.put(SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); configs.put(SASL_MECHANISM, SASL_MECHANISM_OAUTH); configs.put(SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); KAFKA_OAUTH_CONFIGS = Collections.unmodifiableMap(configs); } private final AzureGlobalProperties azureGlobalProperties; AbstractKafkaPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { this.azureGlobalProperties = azureGlobalProperties; } @SuppressWarnings("unchecked") @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (needsPostProcess(bean)) { T properties = (T) bean; replaceAzurePropertiesWithJaas(getMergedProducerProperties(properties), getRawProducerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedConsumerProperties(properties), getRawConsumerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedAdminProperties(properties), getRawAdminProperties(properties)); customizeProcess(properties); } return bean; } /** * Create a map of the merged Kafka producer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka producer properties */ protected abstract Map<String, Object> getMergedProducerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores producer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing producer-specific properties */ protected abstract Map<String, String> getRawProducerProperties(T properties); /** * Create a map of the merged Kafka consumer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka consumer properties */ protected abstract Map<String, Object> getMergedConsumerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores consumer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing consumer-specific properties */ protected abstract Map<String, String> getRawConsumerProperties(T properties); /** * Create a map of the merged Kafka admin properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka admin properties */ protected abstract Map<String, Object> getMergedAdminProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores admin-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing admin-specific properties */ protected abstract Map<String, String> getRawAdminProperties(T properties); protected abstract boolean needsPostProcess(Object bean); protected abstract Logger getLogger(); /** * Process Kafka Spring properties for any customized operations. * @param properties the Kafka Spring properties */ protected void customizeProcess(T properties) { } protected void clearAzureProperties(Map<String, String> properties) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(properties::remove); } /** * This method executes two operations: * <p> * 1. When this configuration meets Azure Kafka passwordless startup requirements, convert all Azure properties * in Kafka to {@link Jaas}, and configure the JAAS configuration back to Kafka. * </p> * <p> * 2. Clear any Azure properties in Kafka properties. * </p> * @param mergedProperties the merged Kafka properties which can contain Azure properties to resolve JAAS from * @param rawPropertiesMap the raw Kafka properties Map to configure JAAS to and remove Azure Properties from */ private void replaceAzurePropertiesWithJaas(Map<String, Object> mergedProperties, Map<String, String> rawPropertiesMap) { resolveJaasForAzure(mergedProperties) .ifPresent(jaas -> { configJaasToKafkaRawProperties(jaas, rawPropertiesMap); logConfigureOAuthProperties(); configureKafkaUserAgent(); }); clearAzureProperties(rawPropertiesMap); } private Optional<Jaas> resolveJaasForAzure(Map<String, Object> mergedProperties) { if (needConfigureSaslOAuth(mergedProperties)) { JaasResolver resolver = new JaasResolver(); Jaas jaas = resolver.resolve((String) mergedProperties.get(SASL_JAAS_CONFIG)) .orElse(new Jaas(OAuthBearerLoginModule.class.getName())); setAzurePropertiesToJaasOptionsIfAbsent(azureGlobalProperties, jaas); setKafkaPropertiesToJaasOptions(mergedProperties, jaas); jaas.getOptions().put(AZURE_CONFIGURED_JAAS_OPTIONS_KEY, AZURE_CONFIGURED_JAAS_OPTIONS_VALUE); return Optional.of(jaas); } else { return Optional.empty(); } } private void configJaasToKafkaRawProperties(Jaas jaas, Map<String, String> rawPropertiesMap) { rawPropertiesMap.putAll(KAFKA_OAUTH_CONFIGS); rawPropertiesMap.put(SASL_JAAS_CONFIG, jaas.toString()); } /** * Configure necessary OAuth properties for kafka properties and log for the changes. */ private void logConfigureOAuthProperties() { getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_MECHANISM, SASL_MECHANISM_OAUTH); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_JAAS_CONFIG, "***the value involves credentials and will not be logged***"); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); } private void setKafkaPropertiesToJaasOptions(Map<String, ?> properties, Jaas jaas) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(k -> PROPERTY_MAPPER.from(properties.get(k)).to(p -> jaas.getOptions().put(k, (String) p))); } private void setAzurePropertiesToJaasOptionsIfAbsent(AzureProperties azureProperties, Jaas jaas) { convertAzurePropertiesToMap(azureProperties) .forEach((k, v) -> jaas.getOptions().putIfAbsent(k, v)); } private Map<String, String> convertAzurePropertiesToMap(AzureProperties properties) { Map<String, String> configs = new HashMap<>(); for (AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping m : AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.values()) { PROPERTY_MAPPER.from(m.getter().apply(properties)).to(p -> configs.put(m.propertyKey(), p)); } return configs; } /** * Configure Spring Cloud Azure user-agent for Kafka client. This method is idempotent to avoid configuring UA repeatedly. */ synchronized void configureKafkaUserAgent() { Method dataMethod = ReflectionUtils.findMethod(ApiVersionsRequest.class, "data"); if (dataMethod != null) { ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest.Builder().build(); ApiVersionsRequestData apiVersionsRequestData = (ApiVersionsRequestData) ReflectionUtils.invokeMethod(dataMethod, apiVersionsRequest); if (apiVersionsRequestData != null) { String clientSoftwareName = apiVersionsRequestData.clientSoftwareName(); if (clientSoftwareName != null && !clientSoftwareName.contains(AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH)) { apiVersionsRequestData.setClientSoftwareName(apiVersionsRequestData.clientSoftwareName() + AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH); apiVersionsRequestData.setClientSoftwareVersion(VERSION); } } } } /** * Detect whether we need to configure SASL/OAUTHBEARER properties for {@link KafkaProperties}. Will configure when * the security protocol is not configured, or it's set as SASL_SSL with sasl mechanism as null or OAUTHBEAR. * * @param sourceProperties the source kafka properties for admin/consumer/producer to detect * @return whether we need to configure with Spring Cloud Azure MSI support or not. */ boolean needConfigureSaslOAuth(Map<String, Object> sourceProperties) { return meetAzureBootstrapServerConditions(sourceProperties) && meetSaslOAuthConditions(sourceProperties); } private boolean meetSaslOAuthConditions(Map<String, Object> sourceProperties) { String securityProtocol = (String) sourceProperties.get(SECURITY_PROTOCOL_CONFIG); String saslMechanism = (String) sourceProperties.get(SASL_MECHANISM); String jaasConfig = (String) sourceProperties.get(SASL_JAAS_CONFIG); if (meetSaslProtocolConditions(securityProtocol) && meetSaslOAuth2MechanismConditions(saslMechanism) && meetJaasConditions(jaasConfig)) { return true; } getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION, saslMechanism); return false; } private boolean meetSaslProtocolConditions(String securityProtocol) { return securityProtocol == null || SECURITY_PROTOCOL_CONFIG_SASL.equalsIgnoreCase(securityProtocol); } private boolean meetSaslOAuth2MechanismConditions(String saslMechanism) { return saslMechanism == null || SASL_MECHANISM_OAUTH.equalsIgnoreCase(saslMechanism); } private boolean meetAzureBootstrapServerConditions(Map<String, Object> sourceProperties) { Object bootstrapServers = sourceProperties.get(BOOTSTRAP_SERVERS_CONFIG); List<String> serverList; if (bootstrapServers instanceof String) { serverList = Arrays.asList(delimitedListToStringArray((String) bootstrapServers, ",")); } else if (bootstrapServers instanceof Iterable<?>) { serverList = new ArrayList<>(); for (Object obj : (Iterable) bootstrapServers) { if (obj instanceof String) { serverList.add((String) obj); } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } } } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } return serverList.size() == 1 && serverList.get(0).endsWith(":9093"); } }
We should explicitly use this default constructor in the subclasses https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/aad/implementation/webapp/AadOAuth2AuthorizationCodeGrantRequestEntityConverter.java#L34-L36
protected AbstractOAuth2AuthorizationCodeGrantRequestEntityConverter() { addHeadersConverter(this::getHttpHeaders); addParametersConverter(this::getHttpBody); }
}
protected AbstractOAuth2AuthorizationCodeGrantRequestEntityConverter() { addHeadersConverter(this::getHttpHeaders); addParametersConverter(this::getHttpBody); }
class AbstractOAuth2AuthorizationCodeGrantRequestEntityConverter extends OAuth2AuthorizationCodeGrantRequestEntityConverter { private static final MultiValueMap<String, String> EMPTY_MULTI_VALUE_MAP = new MultiValueMapAdapter<>(Collections.emptyMap()); /** * Gets the application ID. * * @return the application ID */ protected abstract String getApplicationId(); /** * Additional default headers information. * @return HttpHeaders */ protected HttpHeaders getHttpHeaders(OAuth2AuthorizationCodeGrantRequest request) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.put("x-client-SKU", Collections.singletonList(getApplicationId())); httpHeaders.put("x-client-VER", Collections.singletonList(AzureSpringIdentifier.VERSION)); httpHeaders.put("client-request-id", Collections.singletonList(UUID.randomUUID().toString())); return httpHeaders; } /** * Default body of OAuth2AuthorizationCodeGrantRequest. * @param request OAuth2AuthorizationCodeGrantRequest * @return MultiValueMap */ protected MultiValueMap<String, String> getHttpBody(OAuth2AuthorizationCodeGrantRequest request) { return EMPTY_MULTI_VALUE_MAP; } }
class AbstractOAuth2AuthorizationCodeGrantRequestEntityConverter extends OAuth2AuthorizationCodeGrantRequestEntityConverter { private static final MultiValueMap<String, String> EMPTY_MULTI_VALUE_MAP = new MultiValueMapAdapter<>(Collections.emptyMap()); /** * Gets the application ID. * * @return the application ID */ protected abstract String getApplicationId(); /** * Additional default headers information. * @return HttpHeaders */ protected HttpHeaders getHttpHeaders(OAuth2AuthorizationCodeGrantRequest request) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.put("x-client-SKU", Collections.singletonList(getApplicationId())); httpHeaders.put("x-client-VER", Collections.singletonList(AzureSpringIdentifier.VERSION)); httpHeaders.put("client-request-id", Collections.singletonList(UUID.randomUUID().toString())); return httpHeaders; } /** * Default body of OAuth2AuthorizationCodeGrantRequest. * @param request OAuth2AuthorizationCodeGrantRequest * @return MultiValueMap */ protected MultiValueMap<String, String> getHttpBody(OAuth2AuthorizationCodeGrantRequest request) { return EMPTY_MULTI_VALUE_MAP; } }
changed, thanks
public Mono<VirtualMachineExtensionInstanceView> getInstanceViewAsync() { return this .client .getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), "instanceView") .flatMap(inner -> { VirtualMachineExtensionInstanceView instanceView = inner.instanceView(); if (instanceView == null) { return Mono.empty(); } else { return Mono.just(instanceView); } }); }
}
public Mono<VirtualMachineExtensionInstanceView> getInstanceViewAsync() { return this .client .getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), "instanceView") .flatMap(inner -> Mono.justOrEmpty(inner.instanceView())); }
class VirtualMachineExtensionImpl extends ExternalChildResourceImpl< VirtualMachineExtension, VirtualMachineExtensionInner, VirtualMachineImpl, VirtualMachine> implements VirtualMachineExtension, VirtualMachineExtension.Definition<VirtualMachine.DefinitionStages.WithCreate>, VirtualMachineExtension.UpdateDefinition<VirtualMachine.Update>, VirtualMachineExtension.Update { private final VirtualMachineExtensionsClient client; private HashMap<String, Object> publicSettings; private HashMap<String, Object> protectedSettings; VirtualMachineExtensionImpl( String name, VirtualMachineImpl parent, VirtualMachineExtensionInner inner, VirtualMachineExtensionsClient client) { super(name, parent, inner); this.client = client; initializeSettings(); } protected static VirtualMachineExtensionImpl newVirtualMachineExtension( String name, VirtualMachineImpl parent, VirtualMachineExtensionsClient client) { VirtualMachineExtensionInner inner = new VirtualMachineExtensionInner(); inner.withLocation(parent.regionName()); VirtualMachineExtensionImpl extension = new VirtualMachineExtensionImpl(name, parent, inner, client); return extension; } @Override public String id() { return this.innerModel().id(); } @Override public String publisherName() { return this.innerModel().publisher(); } @Override public String typeName() { return this.innerModel().typePropertiesType(); } @Override public String versionName() { return this.innerModel().typeHandlerVersion(); } @Override public boolean autoUpgradeMinorVersionEnabled() { return this.innerModel().autoUpgradeMinorVersion(); } @Override public Map<String, Object> publicSettings() { return Collections.unmodifiableMap(this.publicSettings); } @Override public String publicSettingsAsJsonString() { return null; } @Override public VirtualMachineExtensionInstanceView getInstanceView() { return getInstanceViewAsync().block(); } @Override @Override public Map<String, String> tags() { Map<String, String> tags = this.innerModel().tags(); if (tags == null) { tags = new TreeMap<>(); } return Collections.unmodifiableMap(tags); } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public VirtualMachineExtensionImpl withMinorVersionAutoUpgrade() { this.innerModel().withAutoUpgradeMinorVersion(true); return this; } @Override public VirtualMachineExtensionImpl withoutMinorVersionAutoUpgrade() { this.innerModel().withAutoUpgradeMinorVersion(false); return this; } @Override public VirtualMachineExtensionImpl withImage(VirtualMachineExtensionImage image) { this .innerModel() .withPublisher(image.publisherName()) .withTypePropertiesType(image.typeName()) .withTypeHandlerVersion(image.versionName()); return this; } @Override public VirtualMachineExtensionImpl withPublisher(String extensionImagePublisherName) { this.innerModel().withPublisher(extensionImagePublisherName); return this; } @Override public VirtualMachineExtensionImpl withPublicSetting(String key, Object value) { this.publicSettings.put(key, value); return this; } @Override public VirtualMachineExtensionImpl withProtectedSetting(String key, Object value) { this.protectedSettings.put(key, value); return this; } @Override public VirtualMachineExtensionImpl withPublicSettings(HashMap<String, Object> settings) { this.publicSettings.clear(); this.publicSettings.putAll(settings); return this; } @Override public VirtualMachineExtensionImpl withProtectedSettings(HashMap<String, Object> settings) { this.protectedSettings.clear(); this.protectedSettings.putAll(settings); return this; } @Override public VirtualMachineExtensionImpl withType(String extensionImageTypeName) { this.innerModel().withTypePropertiesType(extensionImageTypeName); return this; } @Override public VirtualMachineExtensionImpl withVersion(String extensionImageVersionName) { this.innerModel().withTypeHandlerVersion(extensionImageVersionName); return this; } @Override public final VirtualMachineExtensionImpl withTags(Map<String, String> tags) { this.innerModel().withTags(new HashMap<>(tags)); return this; } @Override public final VirtualMachineExtensionImpl withTag(String key, String value) { if (this.innerModel().tags() == null) { this.innerModel().withTags(new HashMap<>()); } this.innerModel().tags().put(key, value); return this; } @Override public final VirtualMachineExtensionImpl withoutTag(String key) { if (this.innerModel().tags() != null) { this.innerModel().tags().remove(key); } return this; } @Override public VirtualMachineImpl attach() { this.nullifySettingsIfEmpty(); return this.parent().withExtension(this); } @Override protected Mono<VirtualMachineExtensionInner> getInnerAsync() { String name; if (this.isReference()) { name = ResourceUtils.nameFromResourceId(this.innerModel().id()); } else { name = this.innerModel().name(); } return this.client.getAsync(this.parent().resourceGroupName(), this.parent().name(), name); } @Override public Mono<VirtualMachineExtension> createResourceAsync() { final VirtualMachineExtensionImpl self = this; return this .client .createOrUpdateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .map( inner -> { self.setInner(inner); self.initializeSettings(); return self; }); } @Override @SuppressWarnings("unchecked") public Mono<VirtualMachineExtension> updateResourceAsync() { this.nullifySettingsIfEmpty(); if (this.isReference()) { String extensionName = ResourceUtils.nameFromResourceId(this.innerModel().id()); return this .client .getAsync(this.parent().resourceGroupName(), this.parent().name(), extensionName) .flatMap( resource -> { innerModel() .withPublisher(resource.publisher()) .withTypePropertiesType(resource.typePropertiesType()) .withTypeHandlerVersion(resource.typeHandlerVersion()); if (innerModel().autoUpgradeMinorVersion() == null) { innerModel().withAutoUpgradeMinorVersion(resource.autoUpgradeMinorVersion()); } LinkedHashMap<String, Object> publicSettings = (LinkedHashMap<String, Object>) resource.settings(); if (publicSettings != null && publicSettings.size() > 0) { LinkedHashMap<String, Object> innerPublicSettings = (LinkedHashMap<String, Object>) innerModel().settings(); if (innerPublicSettings == null) { innerModel().withSettings(new LinkedHashMap<String, Object>()); innerPublicSettings = (LinkedHashMap<String, Object>) innerModel().settings(); } for (Map.Entry<String, Object> entry : publicSettings.entrySet()) { if (!innerPublicSettings.containsKey(entry.getKey())) { innerPublicSettings.put(entry.getKey(), entry.getValue()); } } } return createResourceAsync(); }); } else { return this.createResourceAsync(); } } @Override public Mono<Void> deleteResourceAsync() { return this.client.deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } /** * @return true if this is just a reference to the extension. * <p>An extension will present as a reference when the parent virtual machine was fetched using VM list, a GET * on a specific VM will return fully expanded extension details. */ public boolean isReference() { return this.innerModel().name() == null; } private void nullifySettingsIfEmpty() { if (this.publicSettings.size() == 0) { this.innerModel().withSettings(null); } if (this.protectedSettings.size() == 0) { this.innerModel().withProtectedSettings(null); } } @SuppressWarnings("unchecked") private void initializeSettings() { if (this.innerModel().settings() == null) { this.publicSettings = new LinkedHashMap<>(); this.innerModel().withSettings(this.publicSettings); } else { this.publicSettings = (LinkedHashMap<String, Object>) this.innerModel().settings(); } if (this.innerModel().protectedSettings() == null) { this.protectedSettings = new LinkedHashMap<>(); this.innerModel().withProtectedSettings(this.protectedSettings); } else { this.protectedSettings = (LinkedHashMap<String, Object>) this.innerModel().protectedSettings(); } } }
class VirtualMachineExtensionImpl extends ExternalChildResourceImpl< VirtualMachineExtension, VirtualMachineExtensionInner, VirtualMachineImpl, VirtualMachine> implements VirtualMachineExtension, VirtualMachineExtension.Definition<VirtualMachine.DefinitionStages.WithCreate>, VirtualMachineExtension.UpdateDefinition<VirtualMachine.Update>, VirtualMachineExtension.Update { private final VirtualMachineExtensionsClient client; private HashMap<String, Object> publicSettings; private HashMap<String, Object> protectedSettings; VirtualMachineExtensionImpl( String name, VirtualMachineImpl parent, VirtualMachineExtensionInner inner, VirtualMachineExtensionsClient client) { super(name, parent, inner); this.client = client; initializeSettings(); } protected static VirtualMachineExtensionImpl newVirtualMachineExtension( String name, VirtualMachineImpl parent, VirtualMachineExtensionsClient client) { VirtualMachineExtensionInner inner = new VirtualMachineExtensionInner(); inner.withLocation(parent.regionName()); VirtualMachineExtensionImpl extension = new VirtualMachineExtensionImpl(name, parent, inner, client); return extension; } @Override public String id() { return this.innerModel().id(); } @Override public String publisherName() { return this.innerModel().publisher(); } @Override public String typeName() { return this.innerModel().typePropertiesType(); } @Override public String versionName() { return this.innerModel().typeHandlerVersion(); } @Override public boolean autoUpgradeMinorVersionEnabled() { return this.innerModel().autoUpgradeMinorVersion(); } @Override public Map<String, Object> publicSettings() { return Collections.unmodifiableMap(this.publicSettings); } @Override public String publicSettingsAsJsonString() { return null; } @Override public VirtualMachineExtensionInstanceView getInstanceView() { return getInstanceViewAsync().block(); } @Override @Override public Map<String, String> tags() { Map<String, String> tags = this.innerModel().tags(); if (tags == null) { tags = new TreeMap<>(); } return Collections.unmodifiableMap(tags); } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public VirtualMachineExtensionImpl withMinorVersionAutoUpgrade() { this.innerModel().withAutoUpgradeMinorVersion(true); return this; } @Override public VirtualMachineExtensionImpl withoutMinorVersionAutoUpgrade() { this.innerModel().withAutoUpgradeMinorVersion(false); return this; } @Override public VirtualMachineExtensionImpl withImage(VirtualMachineExtensionImage image) { this .innerModel() .withPublisher(image.publisherName()) .withTypePropertiesType(image.typeName()) .withTypeHandlerVersion(image.versionName()); return this; } @Override public VirtualMachineExtensionImpl withPublisher(String extensionImagePublisherName) { this.innerModel().withPublisher(extensionImagePublisherName); return this; } @Override public VirtualMachineExtensionImpl withPublicSetting(String key, Object value) { this.publicSettings.put(key, value); return this; } @Override public VirtualMachineExtensionImpl withProtectedSetting(String key, Object value) { this.protectedSettings.put(key, value); return this; } @Override public VirtualMachineExtensionImpl withPublicSettings(HashMap<String, Object> settings) { this.publicSettings.clear(); this.publicSettings.putAll(settings); return this; } @Override public VirtualMachineExtensionImpl withProtectedSettings(HashMap<String, Object> settings) { this.protectedSettings.clear(); this.protectedSettings.putAll(settings); return this; } @Override public VirtualMachineExtensionImpl withType(String extensionImageTypeName) { this.innerModel().withTypePropertiesType(extensionImageTypeName); return this; } @Override public VirtualMachineExtensionImpl withVersion(String extensionImageVersionName) { this.innerModel().withTypeHandlerVersion(extensionImageVersionName); return this; } @Override public final VirtualMachineExtensionImpl withTags(Map<String, String> tags) { this.innerModel().withTags(new HashMap<>(tags)); return this; } @Override public final VirtualMachineExtensionImpl withTag(String key, String value) { if (this.innerModel().tags() == null) { this.innerModel().withTags(new HashMap<>()); } this.innerModel().tags().put(key, value); return this; } @Override public final VirtualMachineExtensionImpl withoutTag(String key) { if (this.innerModel().tags() != null) { this.innerModel().tags().remove(key); } return this; } @Override public VirtualMachineImpl attach() { this.nullifySettingsIfEmpty(); return this.parent().withExtension(this); } @Override protected Mono<VirtualMachineExtensionInner> getInnerAsync() { String name; if (this.isReference()) { name = ResourceUtils.nameFromResourceId(this.innerModel().id()); } else { name = this.innerModel().name(); } return this.client.getAsync(this.parent().resourceGroupName(), this.parent().name(), name); } @Override public Mono<VirtualMachineExtension> createResourceAsync() { final VirtualMachineExtensionImpl self = this; return this .client .createOrUpdateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .map( inner -> { self.setInner(inner); self.initializeSettings(); return self; }); } @Override @SuppressWarnings("unchecked") public Mono<VirtualMachineExtension> updateResourceAsync() { this.nullifySettingsIfEmpty(); if (this.isReference()) { String extensionName = ResourceUtils.nameFromResourceId(this.innerModel().id()); return this .client .getAsync(this.parent().resourceGroupName(), this.parent().name(), extensionName) .flatMap( resource -> { innerModel() .withPublisher(resource.publisher()) .withTypePropertiesType(resource.typePropertiesType()) .withTypeHandlerVersion(resource.typeHandlerVersion()); if (innerModel().autoUpgradeMinorVersion() == null) { innerModel().withAutoUpgradeMinorVersion(resource.autoUpgradeMinorVersion()); } LinkedHashMap<String, Object> publicSettings = (LinkedHashMap<String, Object>) resource.settings(); if (publicSettings != null && publicSettings.size() > 0) { LinkedHashMap<String, Object> innerPublicSettings = (LinkedHashMap<String, Object>) innerModel().settings(); if (innerPublicSettings == null) { innerModel().withSettings(new LinkedHashMap<String, Object>()); innerPublicSettings = (LinkedHashMap<String, Object>) innerModel().settings(); } for (Map.Entry<String, Object> entry : publicSettings.entrySet()) { if (!innerPublicSettings.containsKey(entry.getKey())) { innerPublicSettings.put(entry.getKey(), entry.getValue()); } } } return createResourceAsync(); }); } else { return this.createResourceAsync(); } } @Override public Mono<Void> deleteResourceAsync() { return this.client.deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } /** * @return true if this is just a reference to the extension. * <p>An extension will present as a reference when the parent virtual machine was fetched using VM list, a GET * on a specific VM will return fully expanded extension details. */ public boolean isReference() { return this.innerModel().name() == null; } private void nullifySettingsIfEmpty() { if (this.publicSettings.size() == 0) { this.innerModel().withSettings(null); } if (this.protectedSettings.size() == 0) { this.innerModel().withProtectedSettings(null); } } @SuppressWarnings("unchecked") private void initializeSettings() { if (this.innerModel().settings() == null) { this.publicSettings = new LinkedHashMap<>(); this.innerModel().withSettings(this.publicSettings); } else { this.publicSettings = (LinkedHashMap<String, Object>) this.innerModel().settings(); } if (this.innerModel().protectedSettings() == null) { this.protectedSettings = new LinkedHashMap<>(); this.innerModel().withProtectedSettings(this.protectedSettings); } else { this.protectedSettings = (LinkedHashMap<String, Object>) this.innerModel().protectedSettings(); } } }
Not necessary. Refs: https://stackoverflow.com/questions/2054022/is-it-unnecessary-to-put-super-in-constructor Test: ![image](https://user-images.githubusercontent.com/13167207/196083442-404689d8-3df4-4921-b524-7fccf96a70e6.png)
protected AbstractOAuth2AuthorizationCodeGrantRequestEntityConverter() { addHeadersConverter(this::getHttpHeaders); addParametersConverter(this::getHttpBody); }
}
protected AbstractOAuth2AuthorizationCodeGrantRequestEntityConverter() { addHeadersConverter(this::getHttpHeaders); addParametersConverter(this::getHttpBody); }
class AbstractOAuth2AuthorizationCodeGrantRequestEntityConverter extends OAuth2AuthorizationCodeGrantRequestEntityConverter { private static final MultiValueMap<String, String> EMPTY_MULTI_VALUE_MAP = new MultiValueMapAdapter<>(Collections.emptyMap()); /** * Gets the application ID. * * @return the application ID */ protected abstract String getApplicationId(); /** * Additional default headers information. * @return HttpHeaders */ protected HttpHeaders getHttpHeaders(OAuth2AuthorizationCodeGrantRequest request) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.put("x-client-SKU", Collections.singletonList(getApplicationId())); httpHeaders.put("x-client-VER", Collections.singletonList(AzureSpringIdentifier.VERSION)); httpHeaders.put("client-request-id", Collections.singletonList(UUID.randomUUID().toString())); return httpHeaders; } /** * Default body of OAuth2AuthorizationCodeGrantRequest. * @param request OAuth2AuthorizationCodeGrantRequest * @return MultiValueMap */ protected MultiValueMap<String, String> getHttpBody(OAuth2AuthorizationCodeGrantRequest request) { return EMPTY_MULTI_VALUE_MAP; } }
class AbstractOAuth2AuthorizationCodeGrantRequestEntityConverter extends OAuth2AuthorizationCodeGrantRequestEntityConverter { private static final MultiValueMap<String, String> EMPTY_MULTI_VALUE_MAP = new MultiValueMapAdapter<>(Collections.emptyMap()); /** * Gets the application ID. * * @return the application ID */ protected abstract String getApplicationId(); /** * Additional default headers information. * @return HttpHeaders */ protected HttpHeaders getHttpHeaders(OAuth2AuthorizationCodeGrantRequest request) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.put("x-client-SKU", Collections.singletonList(getApplicationId())); httpHeaders.put("x-client-VER", Collections.singletonList(AzureSpringIdentifier.VERSION)); httpHeaders.put("client-request-id", Collections.singletonList(UUID.randomUUID().toString())); return httpHeaders; } /** * Default body of OAuth2AuthorizationCodeGrantRequest. * @param request OAuth2AuthorizationCodeGrantRequest * @return MultiValueMap */ protected MultiValueMap<String, String> getHttpBody(OAuth2AuthorizationCodeGrantRequest request) { return EMPTY_MULTI_VALUE_MAP; } }
nit, justOrEmpty
public Mono<VirtualMachineExtensionInstanceView> getInstanceViewAsync() { return this .client .getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), "instanceView") .flatMap(inner -> { VirtualMachineExtensionInstanceView instanceView = inner.instanceView(); if (instanceView == null) { return Mono.empty(); } else { return Mono.just(instanceView); } }); }
}
public Mono<VirtualMachineExtensionInstanceView> getInstanceViewAsync() { return this .client .getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), "instanceView") .flatMap(inner -> Mono.justOrEmpty(inner.instanceView())); }
class VirtualMachineExtensionImpl extends ExternalChildResourceImpl< VirtualMachineExtension, VirtualMachineExtensionInner, VirtualMachineImpl, VirtualMachine> implements VirtualMachineExtension, VirtualMachineExtension.Definition<VirtualMachine.DefinitionStages.WithCreate>, VirtualMachineExtension.UpdateDefinition<VirtualMachine.Update>, VirtualMachineExtension.Update { private final VirtualMachineExtensionsClient client; private HashMap<String, Object> publicSettings; private HashMap<String, Object> protectedSettings; VirtualMachineExtensionImpl( String name, VirtualMachineImpl parent, VirtualMachineExtensionInner inner, VirtualMachineExtensionsClient client) { super(name, parent, inner); this.client = client; initializeSettings(); } protected static VirtualMachineExtensionImpl newVirtualMachineExtension( String name, VirtualMachineImpl parent, VirtualMachineExtensionsClient client) { VirtualMachineExtensionInner inner = new VirtualMachineExtensionInner(); inner.withLocation(parent.regionName()); VirtualMachineExtensionImpl extension = new VirtualMachineExtensionImpl(name, parent, inner, client); return extension; } @Override public String id() { return this.innerModel().id(); } @Override public String publisherName() { return this.innerModel().publisher(); } @Override public String typeName() { return this.innerModel().typePropertiesType(); } @Override public String versionName() { return this.innerModel().typeHandlerVersion(); } @Override public boolean autoUpgradeMinorVersionEnabled() { return this.innerModel().autoUpgradeMinorVersion(); } @Override public Map<String, Object> publicSettings() { return Collections.unmodifiableMap(this.publicSettings); } @Override public String publicSettingsAsJsonString() { return null; } @Override public VirtualMachineExtensionInstanceView getInstanceView() { return getInstanceViewAsync().block(); } @Override @Override public Map<String, String> tags() { Map<String, String> tags = this.innerModel().tags(); if (tags == null) { tags = new TreeMap<>(); } return Collections.unmodifiableMap(tags); } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public VirtualMachineExtensionImpl withMinorVersionAutoUpgrade() { this.innerModel().withAutoUpgradeMinorVersion(true); return this; } @Override public VirtualMachineExtensionImpl withoutMinorVersionAutoUpgrade() { this.innerModel().withAutoUpgradeMinorVersion(false); return this; } @Override public VirtualMachineExtensionImpl withImage(VirtualMachineExtensionImage image) { this .innerModel() .withPublisher(image.publisherName()) .withTypePropertiesType(image.typeName()) .withTypeHandlerVersion(image.versionName()); return this; } @Override public VirtualMachineExtensionImpl withPublisher(String extensionImagePublisherName) { this.innerModel().withPublisher(extensionImagePublisherName); return this; } @Override public VirtualMachineExtensionImpl withPublicSetting(String key, Object value) { this.publicSettings.put(key, value); return this; } @Override public VirtualMachineExtensionImpl withProtectedSetting(String key, Object value) { this.protectedSettings.put(key, value); return this; } @Override public VirtualMachineExtensionImpl withPublicSettings(HashMap<String, Object> settings) { this.publicSettings.clear(); this.publicSettings.putAll(settings); return this; } @Override public VirtualMachineExtensionImpl withProtectedSettings(HashMap<String, Object> settings) { this.protectedSettings.clear(); this.protectedSettings.putAll(settings); return this; } @Override public VirtualMachineExtensionImpl withType(String extensionImageTypeName) { this.innerModel().withTypePropertiesType(extensionImageTypeName); return this; } @Override public VirtualMachineExtensionImpl withVersion(String extensionImageVersionName) { this.innerModel().withTypeHandlerVersion(extensionImageVersionName); return this; } @Override public final VirtualMachineExtensionImpl withTags(Map<String, String> tags) { this.innerModel().withTags(new HashMap<>(tags)); return this; } @Override public final VirtualMachineExtensionImpl withTag(String key, String value) { if (this.innerModel().tags() == null) { this.innerModel().withTags(new HashMap<>()); } this.innerModel().tags().put(key, value); return this; } @Override public final VirtualMachineExtensionImpl withoutTag(String key) { if (this.innerModel().tags() != null) { this.innerModel().tags().remove(key); } return this; } @Override public VirtualMachineImpl attach() { this.nullifySettingsIfEmpty(); return this.parent().withExtension(this); } @Override protected Mono<VirtualMachineExtensionInner> getInnerAsync() { String name; if (this.isReference()) { name = ResourceUtils.nameFromResourceId(this.innerModel().id()); } else { name = this.innerModel().name(); } return this.client.getAsync(this.parent().resourceGroupName(), this.parent().name(), name); } @Override public Mono<VirtualMachineExtension> createResourceAsync() { final VirtualMachineExtensionImpl self = this; return this .client .createOrUpdateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .map( inner -> { self.setInner(inner); self.initializeSettings(); return self; }); } @Override @SuppressWarnings("unchecked") public Mono<VirtualMachineExtension> updateResourceAsync() { this.nullifySettingsIfEmpty(); if (this.isReference()) { String extensionName = ResourceUtils.nameFromResourceId(this.innerModel().id()); return this .client .getAsync(this.parent().resourceGroupName(), this.parent().name(), extensionName) .flatMap( resource -> { innerModel() .withPublisher(resource.publisher()) .withTypePropertiesType(resource.typePropertiesType()) .withTypeHandlerVersion(resource.typeHandlerVersion()); if (innerModel().autoUpgradeMinorVersion() == null) { innerModel().withAutoUpgradeMinorVersion(resource.autoUpgradeMinorVersion()); } LinkedHashMap<String, Object> publicSettings = (LinkedHashMap<String, Object>) resource.settings(); if (publicSettings != null && publicSettings.size() > 0) { LinkedHashMap<String, Object> innerPublicSettings = (LinkedHashMap<String, Object>) innerModel().settings(); if (innerPublicSettings == null) { innerModel().withSettings(new LinkedHashMap<String, Object>()); innerPublicSettings = (LinkedHashMap<String, Object>) innerModel().settings(); } for (Map.Entry<String, Object> entry : publicSettings.entrySet()) { if (!innerPublicSettings.containsKey(entry.getKey())) { innerPublicSettings.put(entry.getKey(), entry.getValue()); } } } return createResourceAsync(); }); } else { return this.createResourceAsync(); } } @Override public Mono<Void> deleteResourceAsync() { return this.client.deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } /** * @return true if this is just a reference to the extension. * <p>An extension will present as a reference when the parent virtual machine was fetched using VM list, a GET * on a specific VM will return fully expanded extension details. */ public boolean isReference() { return this.innerModel().name() == null; } private void nullifySettingsIfEmpty() { if (this.publicSettings.size() == 0) { this.innerModel().withSettings(null); } if (this.protectedSettings.size() == 0) { this.innerModel().withProtectedSettings(null); } } @SuppressWarnings("unchecked") private void initializeSettings() { if (this.innerModel().settings() == null) { this.publicSettings = new LinkedHashMap<>(); this.innerModel().withSettings(this.publicSettings); } else { this.publicSettings = (LinkedHashMap<String, Object>) this.innerModel().settings(); } if (this.innerModel().protectedSettings() == null) { this.protectedSettings = new LinkedHashMap<>(); this.innerModel().withProtectedSettings(this.protectedSettings); } else { this.protectedSettings = (LinkedHashMap<String, Object>) this.innerModel().protectedSettings(); } } }
class VirtualMachineExtensionImpl extends ExternalChildResourceImpl< VirtualMachineExtension, VirtualMachineExtensionInner, VirtualMachineImpl, VirtualMachine> implements VirtualMachineExtension, VirtualMachineExtension.Definition<VirtualMachine.DefinitionStages.WithCreate>, VirtualMachineExtension.UpdateDefinition<VirtualMachine.Update>, VirtualMachineExtension.Update { private final VirtualMachineExtensionsClient client; private HashMap<String, Object> publicSettings; private HashMap<String, Object> protectedSettings; VirtualMachineExtensionImpl( String name, VirtualMachineImpl parent, VirtualMachineExtensionInner inner, VirtualMachineExtensionsClient client) { super(name, parent, inner); this.client = client; initializeSettings(); } protected static VirtualMachineExtensionImpl newVirtualMachineExtension( String name, VirtualMachineImpl parent, VirtualMachineExtensionsClient client) { VirtualMachineExtensionInner inner = new VirtualMachineExtensionInner(); inner.withLocation(parent.regionName()); VirtualMachineExtensionImpl extension = new VirtualMachineExtensionImpl(name, parent, inner, client); return extension; } @Override public String id() { return this.innerModel().id(); } @Override public String publisherName() { return this.innerModel().publisher(); } @Override public String typeName() { return this.innerModel().typePropertiesType(); } @Override public String versionName() { return this.innerModel().typeHandlerVersion(); } @Override public boolean autoUpgradeMinorVersionEnabled() { return this.innerModel().autoUpgradeMinorVersion(); } @Override public Map<String, Object> publicSettings() { return Collections.unmodifiableMap(this.publicSettings); } @Override public String publicSettingsAsJsonString() { return null; } @Override public VirtualMachineExtensionInstanceView getInstanceView() { return getInstanceViewAsync().block(); } @Override @Override public Map<String, String> tags() { Map<String, String> tags = this.innerModel().tags(); if (tags == null) { tags = new TreeMap<>(); } return Collections.unmodifiableMap(tags); } @Override public String provisioningState() { return this.innerModel().provisioningState(); } @Override public VirtualMachineExtensionImpl withMinorVersionAutoUpgrade() { this.innerModel().withAutoUpgradeMinorVersion(true); return this; } @Override public VirtualMachineExtensionImpl withoutMinorVersionAutoUpgrade() { this.innerModel().withAutoUpgradeMinorVersion(false); return this; } @Override public VirtualMachineExtensionImpl withImage(VirtualMachineExtensionImage image) { this .innerModel() .withPublisher(image.publisherName()) .withTypePropertiesType(image.typeName()) .withTypeHandlerVersion(image.versionName()); return this; } @Override public VirtualMachineExtensionImpl withPublisher(String extensionImagePublisherName) { this.innerModel().withPublisher(extensionImagePublisherName); return this; } @Override public VirtualMachineExtensionImpl withPublicSetting(String key, Object value) { this.publicSettings.put(key, value); return this; } @Override public VirtualMachineExtensionImpl withProtectedSetting(String key, Object value) { this.protectedSettings.put(key, value); return this; } @Override public VirtualMachineExtensionImpl withPublicSettings(HashMap<String, Object> settings) { this.publicSettings.clear(); this.publicSettings.putAll(settings); return this; } @Override public VirtualMachineExtensionImpl withProtectedSettings(HashMap<String, Object> settings) { this.protectedSettings.clear(); this.protectedSettings.putAll(settings); return this; } @Override public VirtualMachineExtensionImpl withType(String extensionImageTypeName) { this.innerModel().withTypePropertiesType(extensionImageTypeName); return this; } @Override public VirtualMachineExtensionImpl withVersion(String extensionImageVersionName) { this.innerModel().withTypeHandlerVersion(extensionImageVersionName); return this; } @Override public final VirtualMachineExtensionImpl withTags(Map<String, String> tags) { this.innerModel().withTags(new HashMap<>(tags)); return this; } @Override public final VirtualMachineExtensionImpl withTag(String key, String value) { if (this.innerModel().tags() == null) { this.innerModel().withTags(new HashMap<>()); } this.innerModel().tags().put(key, value); return this; } @Override public final VirtualMachineExtensionImpl withoutTag(String key) { if (this.innerModel().tags() != null) { this.innerModel().tags().remove(key); } return this; } @Override public VirtualMachineImpl attach() { this.nullifySettingsIfEmpty(); return this.parent().withExtension(this); } @Override protected Mono<VirtualMachineExtensionInner> getInnerAsync() { String name; if (this.isReference()) { name = ResourceUtils.nameFromResourceId(this.innerModel().id()); } else { name = this.innerModel().name(); } return this.client.getAsync(this.parent().resourceGroupName(), this.parent().name(), name); } @Override public Mono<VirtualMachineExtension> createResourceAsync() { final VirtualMachineExtensionImpl self = this; return this .client .createOrUpdateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .map( inner -> { self.setInner(inner); self.initializeSettings(); return self; }); } @Override @SuppressWarnings("unchecked") public Mono<VirtualMachineExtension> updateResourceAsync() { this.nullifySettingsIfEmpty(); if (this.isReference()) { String extensionName = ResourceUtils.nameFromResourceId(this.innerModel().id()); return this .client .getAsync(this.parent().resourceGroupName(), this.parent().name(), extensionName) .flatMap( resource -> { innerModel() .withPublisher(resource.publisher()) .withTypePropertiesType(resource.typePropertiesType()) .withTypeHandlerVersion(resource.typeHandlerVersion()); if (innerModel().autoUpgradeMinorVersion() == null) { innerModel().withAutoUpgradeMinorVersion(resource.autoUpgradeMinorVersion()); } LinkedHashMap<String, Object> publicSettings = (LinkedHashMap<String, Object>) resource.settings(); if (publicSettings != null && publicSettings.size() > 0) { LinkedHashMap<String, Object> innerPublicSettings = (LinkedHashMap<String, Object>) innerModel().settings(); if (innerPublicSettings == null) { innerModel().withSettings(new LinkedHashMap<String, Object>()); innerPublicSettings = (LinkedHashMap<String, Object>) innerModel().settings(); } for (Map.Entry<String, Object> entry : publicSettings.entrySet()) { if (!innerPublicSettings.containsKey(entry.getKey())) { innerPublicSettings.put(entry.getKey(), entry.getValue()); } } } return createResourceAsync(); }); } else { return this.createResourceAsync(); } } @Override public Mono<Void> deleteResourceAsync() { return this.client.deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } /** * @return true if this is just a reference to the extension. * <p>An extension will present as a reference when the parent virtual machine was fetched using VM list, a GET * on a specific VM will return fully expanded extension details. */ public boolean isReference() { return this.innerModel().name() == null; } private void nullifySettingsIfEmpty() { if (this.publicSettings.size() == 0) { this.innerModel().withSettings(null); } if (this.protectedSettings.size() == 0) { this.innerModel().withProtectedSettings(null); } } @SuppressWarnings("unchecked") private void initializeSettings() { if (this.innerModel().settings() == null) { this.publicSettings = new LinkedHashMap<>(); this.innerModel().withSettings(this.publicSettings); } else { this.publicSettings = (LinkedHashMap<String, Object>) this.innerModel().settings(); } if (this.innerModel().protectedSettings() == null) { this.protectedSettings = new LinkedHashMap<>(); this.innerModel().withProtectedSettings(this.protectedSettings); } else { this.protectedSettings = (LinkedHashMap<String, Object>) this.innerModel().protectedSettings(); } } }
Policy name seems not taking effect. Policies will always have name "Default".
public void canCRUDSqlDatabase() throws Exception { SqlServer sqlServer = createSqlServer(); Mono<SqlDatabase> resourceStream = sqlServer.databases().define(SQL_DATABASE_NAME).withStandardEdition(SqlDatabaseStandardServiceObjective.S0).createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); validateSqlDatabase(sqlDatabase, SQL_DATABASE_NAME); Assertions.assertTrue(sqlServer.databases().list().size() > 0); final String storageAccountName = generateRandomResourceName("sqlsa", 20); StorageAccount storageAccount = storageManager.storageAccounts().define(storageAccountName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); String accountKey = storageAccount.getKeys().get(0).value(); String blobEntrypoint = storageAccount.endPoints().primary().blob(); List<String> disabledAlerts = Collections.singletonList("Sql_Injection"); sqlDatabase.defineThreatDetectionPolicy(SecurityAlertPolicyName.fromString("myPolicy")) .withPolicyEnabled() .withStorageEndpoint(blobEntrypoint) .withStorageAccountAccessKey(accountKey) .withAlertsFilter(disabledAlerts) .create(); sqlDatabase.refresh(); SqlDatabaseThreatDetectionPolicy alertPolicy = sqlDatabase.getThreatDetectionPolicy(); Assertions.assertNotNull(alertPolicy); Assertions.assertEquals(SecurityAlertPolicyState.ENABLED, alertPolicy.currentState()); Assertions.assertEquals(alertPolicy.disabledAlertList(), disabledAlerts); Assertions.assertTrue(alertPolicy.isDefaultSecurityAlertPolicy()); TransparentDataEncryption transparentDataEncryption = sqlDatabase.getTransparentDataEncryption(); Assertions.assertNotNull(transparentDataEncryption.status()); transparentDataEncryption = transparentDataEncryption.updateStatus(TransparentDataEncryptionState.ENABLED); Assertions.assertNotNull(transparentDataEncryption); Assertions.assertEquals(TransparentDataEncryptionState.ENABLED, transparentDataEncryption.status()); transparentDataEncryption = sqlDatabase.getTransparentDataEncryption().updateStatus(TransparentDataEncryptionState.DISABLED); Assertions.assertNotNull(transparentDataEncryption); Assertions.assertEquals(TransparentDataEncryptionState.DISABLED, transparentDataEncryption.status()); Assertions.assertEquals(transparentDataEncryption.sqlServerName(), sqlServerName); Assertions.assertEquals(transparentDataEncryption.databaseName(), SQL_DATABASE_NAME); Assertions.assertNotNull(transparentDataEncryption.name()); Assertions.assertNotNull(transparentDataEncryption.id()); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); Creatable<SqlElasticPool> sqlElasticPoolCreatable = sqlServer.elasticPools().define(SQL_ELASTIC_POOL_NAME).withStandardPool(); String anotherDatabaseName = "anotherDatabase"; SqlDatabase anotherDatabase = sqlServer .databases() .define(anotherDatabaseName) .withNewElasticPool(sqlElasticPoolCreatable) .withSourceDatabase(sqlDatabase.id()) .withMode(CreateMode.COPY) .create(); validateSqlDatabaseWithElasticPool(anotherDatabase, anotherDatabaseName); sqlServer.databases().delete(anotherDatabase.name()); validateSqlDatabase(sqlServer.databases().get(SQL_DATABASE_NAME), SQL_DATABASE_NAME); validateListSqlDatabase(sqlServer.databases().list()); sqlServer.databases().delete(SQL_DATABASE_NAME); validateSqlDatabaseNotFound(SQL_DATABASE_NAME); resourceStream = sqlServer .databases() .define("newDatabase") .withCollation(COLLATION) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .createAsync(); sqlDatabase = resourceStream.block(); sqlDatabase = sqlDatabase.rename("renamedDatabase"); validateSqlDatabase(sqlDatabase, "renamedDatabase"); sqlServer.databases().delete(sqlDatabase.name()); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); }
sqlDatabase.defineThreatDetectionPolicy(SecurityAlertPolicyName.fromString("myPolicy"))
public void canCRUDSqlDatabase() throws Exception { SqlServer sqlServer = createSqlServer(); Mono<SqlDatabase> resourceStream = sqlServer.databases().define(SQL_DATABASE_NAME).withStandardEdition(SqlDatabaseStandardServiceObjective.S0).createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); validateSqlDatabase(sqlDatabase, SQL_DATABASE_NAME); Assertions.assertTrue(sqlServer.databases().list().size() > 0); final String storageAccountName = generateRandomResourceName("sqlsa", 20); StorageAccount storageAccount = storageManager.storageAccounts().define(storageAccountName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .create(); String accountKey = storageAccount.getKeys().get(0).value(); String blobEntrypoint = storageAccount.endPoints().primary().blob(); List<String> disabledAlerts = Collections.singletonList("Sql_Injection"); sqlDatabase.defineThreatDetectionPolicy(SecurityAlertPolicyName.fromString("myPolicy")) .withPolicyEnabled() .withStorageEndpoint(blobEntrypoint) .withStorageAccountAccessKey(accountKey) .withAlertsFilter(disabledAlerts) .create(); sqlDatabase.refresh(); SqlDatabaseThreatDetectionPolicy alertPolicy = sqlDatabase.getThreatDetectionPolicy(); Assertions.assertNotNull(alertPolicy); Assertions.assertEquals(SecurityAlertPolicyState.ENABLED, alertPolicy.currentState()); Assertions.assertEquals(alertPolicy.disabledAlertList(), disabledAlerts); Assertions.assertTrue(alertPolicy.isDefaultSecurityAlertPolicy()); TransparentDataEncryption transparentDataEncryption = sqlDatabase.getTransparentDataEncryption(); Assertions.assertNotNull(transparentDataEncryption.status()); transparentDataEncryption = transparentDataEncryption.updateStatus(TransparentDataEncryptionState.ENABLED); Assertions.assertNotNull(transparentDataEncryption); Assertions.assertEquals(TransparentDataEncryptionState.ENABLED, transparentDataEncryption.status()); transparentDataEncryption = sqlDatabase.getTransparentDataEncryption().updateStatus(TransparentDataEncryptionState.DISABLED); Assertions.assertNotNull(transparentDataEncryption); Assertions.assertEquals(TransparentDataEncryptionState.DISABLED, transparentDataEncryption.status()); Assertions.assertEquals(transparentDataEncryption.sqlServerName(), sqlServerName); Assertions.assertEquals(transparentDataEncryption.databaseName(), SQL_DATABASE_NAME); Assertions.assertNotNull(transparentDataEncryption.name()); Assertions.assertNotNull(transparentDataEncryption.id()); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); Creatable<SqlElasticPool> sqlElasticPoolCreatable = sqlServer.elasticPools().define(SQL_ELASTIC_POOL_NAME).withStandardPool(); String anotherDatabaseName = "anotherDatabase"; SqlDatabase anotherDatabase = sqlServer .databases() .define(anotherDatabaseName) .withNewElasticPool(sqlElasticPoolCreatable) .withSourceDatabase(sqlDatabase.id()) .withMode(CreateMode.COPY) .create(); validateSqlDatabaseWithElasticPool(anotherDatabase, anotherDatabaseName); sqlServer.databases().delete(anotherDatabase.name()); validateSqlDatabase(sqlServer.databases().get(SQL_DATABASE_NAME), SQL_DATABASE_NAME); validateListSqlDatabase(sqlServer.databases().list()); sqlServer.databases().delete(SQL_DATABASE_NAME); validateSqlDatabaseNotFound(SQL_DATABASE_NAME); resourceStream = sqlServer .databases() .define("newDatabase") .withCollation(COLLATION) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .createAsync(); sqlDatabase = resourceStream.block(); sqlDatabase = sqlDatabase.rename("renamedDatabase"); validateSqlDatabase(sqlDatabase, "renamedDatabase"); sqlServer.databases().delete(sqlDatabase.name()); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); }
class SqlServerOperationsTests extends SqlServerTest { private static final String SQL_DATABASE_NAME = "myTestDatabase2"; private static final String COLLATION = "SQL_Latin1_General_CP1_CI_AS"; private static final String SQL_ELASTIC_POOL_NAME = "testElasticPool"; private static final String SQL_FIREWALLRULE_NAME = "firewallrule1"; private static final String START_IPADDRESS = "10.102.1.10"; private static final String END_IPADDRESS = "10.102.1.12"; @Test public void canCRUDSqlSyncMember() throws Exception { final String dbName = "dbSample"; final String dbSyncName = "dbSync"; final String dbMemberName = "dbMember"; final String syncGroupName = "groupName"; final String syncMemberName = "memberName"; final String administratorLogin = "sqladmin"; final String administratorPassword = password(); SqlServer sqlPrimaryServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .defineDatabase(dbSyncName) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .defineDatabase(dbMemberName) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .create(); SqlDatabase dbSource = sqlPrimaryServer.databases().get(dbName); SqlDatabase dbSync = sqlPrimaryServer.databases().get(dbSyncName); SqlDatabase dbMember = sqlPrimaryServer.databases().get(dbMemberName); SqlSyncGroup sqlSyncGroup = dbSync .syncGroups() .define(syncGroupName) .withSyncDatabaseId(dbSource.id()) .withDatabaseUserName(administratorLogin) .withDatabasePassword(administratorPassword) .withConflictResolutionPolicyHubWins() .withInterval(-1) .create(); Assertions.assertNotNull(sqlSyncGroup); SqlSyncMember sqlSyncMember = sqlSyncGroup .syncMembers() .define(syncMemberName) .withMemberSqlDatabase(dbMember) .withMemberUserName(administratorLogin) .withMemberPassword(administratorPassword) .withMemberDatabaseType(SyncMemberDbType.AZURE_SQL_DATABASE) .withDatabaseType(SyncDirection.ONE_WAY_MEMBER_TO_HUB) .create(); Assertions.assertNotNull(sqlSyncMember); sqlSyncMember .update() .withDatabaseType(SyncDirection.BIDIRECTIONAL) .withMemberUserName(administratorLogin) .withMemberPassword(administratorPassword) .withMemberDatabaseType(SyncMemberDbType.AZURE_SQL_DATABASE) .apply(); Assertions.assertFalse(sqlSyncGroup.syncMembers().list().isEmpty()); sqlSyncMember = sqlServerManager .sqlServers() .syncMembers() .getBySqlServer(rgName, sqlServerName, dbSyncName, syncGroupName, syncMemberName); Assertions.assertNotNull(sqlSyncMember); sqlSyncMember.delete(); sqlSyncGroup.delete(); } @Test public void canCRUDSqlSyncGroup() throws Exception { final String dbName = "dbSample"; final String dbSyncName = "dbSync"; final String syncGroupName = "groupName"; final String administratorLogin = "sqladmin"; final String administratorPassword = password(); SqlServer sqlPrimaryServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .defineDatabase(dbSyncName) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .create(); SqlDatabase dbSource = sqlPrimaryServer.databases().get(dbName); SqlDatabase dbSync = sqlPrimaryServer.databases().get(dbSyncName); SqlSyncGroup sqlSyncGroup = dbSync .syncGroups() .define(syncGroupName) .withSyncDatabaseId(dbSource.id()) .withDatabaseUserName(administratorLogin) .withDatabasePassword(administratorPassword) .withConflictResolutionPolicyHubWins() .withInterval(-1) .create(); Assertions.assertNotNull(sqlSyncGroup); Assertions .assertTrue( sqlServerManager .sqlServers() .syncGroups() .listSyncDatabaseIds(Region.US_EAST) .stream() .findAny() .isPresent()); Assertions.assertFalse(dbSync.syncGroups().list().isEmpty()); sqlSyncGroup = sqlServerManager.sqlServers().syncGroups().getBySqlServer(rgName, sqlServerName, dbSyncName, syncGroupName); Assertions.assertNotNull(sqlSyncGroup); sqlSyncGroup.delete(); } @Test public void canCopySqlDatabase() throws Exception { final String sqlPrimaryServerName = generateRandomResourceName("sqlpri", 22); final String sqlSecondaryServerName = generateRandomResourceName("sqlsec", 22); final String epName = "epSample"; final String dbName = "dbSample"; final String administratorLogin = "sqladmin"; final String administratorPassword = password(); SqlServer sqlPrimaryServer = sqlServerManager .sqlServers() .define(sqlPrimaryServerName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineElasticPool(epName) .withPremiumPool() .attach() .defineDatabase(dbName) .withExistingElasticPool(epName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .attach() .create(); SqlServer sqlSecondaryServer = sqlServerManager .sqlServers() .define(sqlSecondaryServerName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .create(); SqlDatabase dbSample = sqlPrimaryServer.databases().get(dbName); SqlDatabase dbCopy = sqlSecondaryServer .databases() .define("dbCopy") .withSourceDatabase(dbSample) .withMode(CreateMode.COPY) .withPremiumEdition(SqlDatabasePremiumServiceObjective.P1) .create(); Assertions.assertNotNull(dbCopy); } @Test public void canCRUDSqlFailoverGroup() throws Exception { final String sqlPrimaryServerName = generateRandomResourceName("sqlpri", 22); final String sqlSecondaryServerName = generateRandomResourceName("sqlsec", 22); final String sqlOtherServerName = generateRandomResourceName("sql000", 22); final String failoverGroupName = generateRandomResourceName("fg", 22); final String failoverGroupName2 = generateRandomResourceName("fg2", 22); final String dbName = "dbSample"; final String administratorLogin = "sqladmin"; final String administratorPassword = password(); SqlServer sqlPrimaryServer = sqlServerManager .sqlServers() .define(sqlPrimaryServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .create(); SqlServer sqlSecondaryServer = sqlServerManager .sqlServers() .define(sqlSecondaryServerName) .withRegion(Region.US_EAST2) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .create(); SqlServer sqlOtherServer = sqlServerManager .sqlServers() .define(sqlOtherServerName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .create(); SqlFailoverGroup failoverGroup = sqlPrimaryServer .failoverGroups() .define(failoverGroupName) .withManualReadWriteEndpointPolicy() .withPartnerServerId(sqlSecondaryServer.id()) .withReadOnlyEndpointPolicyDisabled() .create(); Assertions.assertNotNull(failoverGroup); Assertions.assertEquals(failoverGroupName, failoverGroup.name()); Assertions.assertEquals(rgName, failoverGroup.resourceGroupName()); Assertions.assertEquals(sqlPrimaryServerName, failoverGroup.sqlServerName()); Assertions.assertEquals(FailoverGroupReplicationRole.PRIMARY, failoverGroup.replicationRole()); Assertions.assertEquals(1, failoverGroup.partnerServers().size()); Assertions.assertEquals(sqlSecondaryServer.id(), failoverGroup.partnerServers().get(0).id()); Assertions .assertEquals( FailoverGroupReplicationRole.SECONDARY, failoverGroup.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroup.databases().size()); Assertions.assertEquals(0, failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, failoverGroup.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.DISABLED, failoverGroup.readOnlyEndpointPolicy()); SqlFailoverGroup failoverGroupOnPartner = sqlSecondaryServer.failoverGroups().get(failoverGroup.name()); Assertions.assertEquals(failoverGroupName, failoverGroupOnPartner.name()); Assertions.assertEquals(rgName, failoverGroupOnPartner.resourceGroupName()); Assertions.assertEquals(sqlSecondaryServerName, failoverGroupOnPartner.sqlServerName()); Assertions.assertEquals(FailoverGroupReplicationRole.SECONDARY, failoverGroupOnPartner.replicationRole()); Assertions.assertEquals(1, failoverGroupOnPartner.partnerServers().size()); Assertions.assertEquals(sqlPrimaryServer.id(), failoverGroupOnPartner.partnerServers().get(0).id()); Assertions .assertEquals( FailoverGroupReplicationRole.PRIMARY, failoverGroupOnPartner.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroupOnPartner.databases().size()); Assertions.assertEquals(0, failoverGroupOnPartner.readWriteEndpointDataLossGracePeriodMinutes()); Assertions .assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, failoverGroupOnPartner.readWriteEndpointPolicy()); Assertions .assertEquals(ReadOnlyEndpointFailoverPolicy.DISABLED, failoverGroupOnPartner.readOnlyEndpointPolicy()); SqlFailoverGroup failoverGroup2 = sqlPrimaryServer .failoverGroups() .define(failoverGroupName2) .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) .withPartnerServerId(sqlOtherServer.id()) .withReadOnlyEndpointPolicyEnabled() .create(); Assertions.assertNotNull(failoverGroup2); Assertions.assertEquals(failoverGroupName2, failoverGroup2.name()); Assertions.assertEquals(rgName, failoverGroup2.resourceGroupName()); Assertions.assertEquals(sqlPrimaryServerName, failoverGroup2.sqlServerName()); Assertions.assertEquals(FailoverGroupReplicationRole.PRIMARY, failoverGroup2.replicationRole()); Assertions.assertEquals(1, failoverGroup2.partnerServers().size()); Assertions.assertEquals(sqlOtherServer.id(), failoverGroup2.partnerServers().get(0).id()); Assertions .assertEquals( FailoverGroupReplicationRole.SECONDARY, failoverGroup2.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroup2.databases().size()); Assertions.assertEquals(120, failoverGroup2.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.AUTOMATIC, failoverGroup2.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.ENABLED, failoverGroup2.readOnlyEndpointPolicy()); failoverGroup .update() .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) .withReadOnlyEndpointPolicyEnabled() .withTag("tag1", "value1") .apply(); Assertions.assertEquals(120, failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.AUTOMATIC, failoverGroup.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.ENABLED, failoverGroup.readOnlyEndpointPolicy()); SqlDatabase db = sqlPrimaryServer.databases().get(dbName); failoverGroup .update() .withManualReadWriteEndpointPolicy() .withReadOnlyEndpointPolicyDisabled() .withNewDatabaseId(db.id()) .apply(); Assertions.assertEquals(1, failoverGroup.databases().size()); Assertions.assertEquals(db.id(), failoverGroup.databases().get(0)); Assertions.assertEquals(0, failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, failoverGroup.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.DISABLED, failoverGroup.readOnlyEndpointPolicy()); List<SqlFailoverGroup> failoverGroupsList = sqlPrimaryServer.failoverGroups().list(); Assertions.assertEquals(2, failoverGroupsList.size()); failoverGroupsList = sqlSecondaryServer.failoverGroups().list(); Assertions.assertEquals(1, failoverGroupsList.size()); sqlPrimaryServer.failoverGroups().delete(failoverGroup2.name()); } @Test public void canChangeSqlServerAndDatabaseAutomaticTuning() throws Exception { String sqlServerAdminName = "sqladmin"; String sqlServerAdminPassword = password(); String databaseName = "db-from-sample"; String id = generateRandomUuid(); String storageName = generateRandomResourceName(sqlServerName, 22); SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .defineDatabase(databaseName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withBasicEdition() .attach() .create(); SqlDatabase dbFromSample = sqlServer.databases().get(databaseName); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); SqlServerAutomaticTuning serverAutomaticTuning = sqlServer.getServerAutomaticTuning(); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.desiredState()); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.actualState()); Assertions.assertEquals(4, serverAutomaticTuning.tuningOptions().size()); serverAutomaticTuning .update() .withAutomaticTuningMode(AutomaticTuningServerMode.AUTO) .withAutomaticTuningOption("createIndex", AutomaticTuningOptionModeDesired.OFF) .withAutomaticTuningOption("dropIndex", AutomaticTuningOptionModeDesired.ON) .withAutomaticTuningOption("forceLastGoodPlan", AutomaticTuningOptionModeDesired.DEFAULT) .apply(); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.desiredState()); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.OFF, serverAutomaticTuning.tuningOptions().get("createIndex").desiredState()); Assertions .assertEquals( AutomaticTuningOptionModeActual.OFF, serverAutomaticTuning.tuningOptions().get("createIndex").actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.ON, serverAutomaticTuning.tuningOptions().get("dropIndex").desiredState()); Assertions .assertEquals( AutomaticTuningOptionModeActual.ON, serverAutomaticTuning.tuningOptions().get("dropIndex").actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.DEFAULT, serverAutomaticTuning.tuningOptions().get("forceLastGoodPlan").desiredState()); SqlDatabaseAutomaticTuning databaseAutomaticTuning = dbFromSample.getDatabaseAutomaticTuning(); Assertions.assertEquals(4, databaseAutomaticTuning.tuningOptions().size()); databaseAutomaticTuning .update() .withAutomaticTuningMode(AutomaticTuningMode.AUTO) .withAutomaticTuningOption("createIndex", AutomaticTuningOptionModeDesired.OFF) .withAutomaticTuningOption("dropIndex", AutomaticTuningOptionModeDesired.ON) .withAutomaticTuningOption("forceLastGoodPlan", AutomaticTuningOptionModeDesired.DEFAULT) .apply(); Assertions.assertEquals(AutomaticTuningMode.AUTO, databaseAutomaticTuning.desiredState()); Assertions.assertEquals(AutomaticTuningMode.AUTO, databaseAutomaticTuning.actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.OFF, databaseAutomaticTuning.tuningOptions().get("createIndex").desiredState()); Assertions .assertEquals( AutomaticTuningOptionModeActual.OFF, databaseAutomaticTuning.tuningOptions().get("createIndex").actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.ON, databaseAutomaticTuning.tuningOptions().get("dropIndex").desiredState()); Assertions .assertEquals( AutomaticTuningOptionModeActual.ON, databaseAutomaticTuning.tuningOptions().get("dropIndex").actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.DEFAULT, databaseAutomaticTuning.tuningOptions().get("forceLastGoodPlan").desiredState()); dbFromSample.delete(); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName); } @Test public void canCreateAndAquireServerDnsAlias() throws Exception { String sqlServerName1 = sqlServerName + "1"; String sqlServerName2 = sqlServerName + "2"; String sqlServerAdminName = "sqladmin"; String sqlServerAdminPassword = password(); SqlServer sqlServer1 = sqlServerManager .sqlServers() .define(sqlServerName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .create(); Assertions.assertNotNull(sqlServer1); SqlServerDnsAlias dnsAlias = sqlServer1.dnsAliases().define(sqlServerName).create(); Assertions.assertNotNull(dnsAlias); Assertions.assertEquals(rgName, dnsAlias.resourceGroupName()); Assertions.assertEquals(sqlServerName1, dnsAlias.sqlServerName()); dnsAlias = sqlServerManager.sqlServers().dnsAliases().getBySqlServer(rgName, sqlServerName1, sqlServerName); Assertions.assertNotNull(dnsAlias); Assertions.assertEquals(rgName, dnsAlias.resourceGroupName()); Assertions.assertEquals(sqlServerName1, dnsAlias.sqlServerName()); Assertions.assertEquals(1, sqlServer1.databases().list().size()); SqlServer sqlServer2 = sqlServerManager .sqlServers() .define(sqlServerName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .create(); Assertions.assertNotNull(sqlServer2); sqlServer2.dnsAliases().acquire(sqlServerName, sqlServer1.id()); ResourceManagerUtils.sleep(Duration.ofMinutes(3)); dnsAlias = sqlServer2.dnsAliases().get(sqlServerName); Assertions.assertNotNull(dnsAlias); Assertions.assertEquals(rgName, dnsAlias.resourceGroupName()); Assertions.assertEquals(sqlServerName2, dnsAlias.sqlServerName()); dnsAlias.delete(); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName1); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName2); } @Test public void canGetSqlServerCapabilitiesAndCreateIdentity() throws Exception { String sqlServerAdminName = "sqladmin"; String sqlServerAdminPassword = password(); String databaseName = "db-from-sample"; RegionCapabilities regionCapabilities = sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST); Assertions.assertNotNull(regionCapabilities); Assertions.assertNotNull(regionCapabilities.supportedCapabilitiesByServerVersion().get("12.0")); Assertions .assertTrue( regionCapabilities.supportedCapabilitiesByServerVersion().get("12.0").supportedEditions().size() > 0); Assertions .assertTrue( regionCapabilities .supportedCapabilitiesByServerVersion() .get("12.0") .supportedElasticPoolEditions() .size() > 0); SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .withSystemAssignedManagedServiceIdentity() .defineDatabase(databaseName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withBasicEdition() .attach() .create(); SqlDatabase dbFromSample = sqlServer.databases().get(databaseName); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); Assertions.assertTrue(sqlServer.isManagedServiceIdentityEnabled()); Assertions.assertEquals(sqlServerManager.tenantId(), sqlServer.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertNotNull(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()); sqlServer.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(sqlServer.isManagedServiceIdentityEnabled()); Assertions.assertEquals(sqlServerManager.tenantId(), sqlServer.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertNotNull(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()); dbFromSample.delete(); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName); } @Test @DoNotRecord(skipInPlayback = true) public void canCRUDSqlServerWithImportDatabase() throws Exception { String sqlServerAdminName = "sqladmin"; String sqlServerAdminPassword = password(); String id = generateRandomUuid(); String storageName = generateRandomResourceName(sqlServerName, 22); SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .withActiveDirectoryAdministrator("DSEng", id) .create(); SqlDatabase dbFromSample = sqlServer .databases() .define("db-from-sample") .fromSample(SampleName.ADVENTURE_WORKS_LT) .withBasicEdition() .withTag("tag1", "value1") .create(); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); SqlDatabaseImportExportResponse exportedDB; StorageAccount storageAccount = null; try { storageAccount = storageManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); } catch (ManagementException e) { Assertions.assertEquals(404, e.getResponse().getStatusCode()); } if (storageAccount == null) { Creatable<StorageAccount> storageAccountCreatable = storageManager .storageAccounts() .define(storageName) .withRegion(sqlServer.regionName()) .withExistingResourceGroup(sqlServer.resourceGroupName()); exportedDB = dbFromSample .exportTo(storageAccountCreatable, "from-sample", "dbfromsample.bacpac") .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) .execute(); storageAccount = storageManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); } else { exportedDB = dbFromSample .exportTo(storageAccount, "from-sample", "dbfromsample.bacpac") .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) .execute(); } SqlDatabase dbFromImport = sqlServer .databases() .define("db-from-import") .defineElasticPool("ep1") .withBasicPool() .attach() .importFrom(storageAccount, "from-sample", "dbfromsample.bacpac") .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) .withTag("tag2", "value2") .create(); Assertions.assertNotNull(dbFromImport); Assertions.assertEquals("ep1", dbFromImport.elasticPoolName()); dbFromImport.delete(); dbFromSample.delete(); sqlServer.elasticPools().delete("ep1"); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName); } @Test public void canCRUDSqlServerWithFirewallRule() throws Exception { String sqlServerAdminName = "sqladmin"; String id = generateRandomUuid(); if (!isPlaybackMode()) { id = clientIdFromFile(); } SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(password()) .withActiveDirectoryAdministrator("DSEng", id) .withoutAccessFromAzureServices() .defineFirewallRule("somefirewallrule1") .withIpAddress("0.0.0.1") .attach() .withTag("tag1", "value1") .create(); Assertions.assertEquals(sqlServerAdminName, sqlServer.administratorLogin()); Assertions.assertEquals("v12.0", sqlServer.kind()); Assertions.assertEquals("12.0", sqlServer.version()); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); Assertions.assertEquals(sqlServerAdminName, sqlServer.administratorLogin()); Assertions.assertEquals("v12.0", sqlServer.kind()); Assertions.assertEquals("12.0", sqlServer.version()); SqlActiveDirectoryAdministrator sqlADAdmin = sqlServer.getActiveDirectoryAdministrator(); Assertions.assertNotNull(sqlADAdmin); Assertions.assertEquals("DSEng", sqlADAdmin.signInName()); Assertions.assertNotNull(sqlADAdmin.id()); Assertions.assertEquals(AdministratorType.ACTIVE_DIRECTORY, sqlADAdmin.administratorType()); sqlADAdmin = sqlServer.setActiveDirectoryAdministrator("DSEngAll", id); Assertions.assertNotNull(sqlADAdmin); Assertions.assertEquals("DSEngAll", sqlADAdmin.signInName()); Assertions.assertNotNull(sqlADAdmin.id()); Assertions.assertEquals(AdministratorType.ACTIVE_DIRECTORY, sqlADAdmin.administratorType()); sqlServer.removeActiveDirectoryAdministrator(); final SqlServer finalSqlServer = sqlServer; validateResourceNotFound(() -> finalSqlServer.getActiveDirectoryAdministrator()); SqlFirewallRule firewallRule = sqlServerManager.sqlServers().firewallRules().getBySqlServer(rgName, sqlServerName, "somefirewallrule1"); Assertions.assertEquals("0.0.0.1", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.1", firewallRule.endIpAddress()); validateResourceNotFound( () -> sqlServerManager .sqlServers() .firewallRules() .getBySqlServer(rgName, sqlServerName, "AllowAllWindowsAzureIps")); sqlServer.enableAccessFromAzureServices(); firewallRule = sqlServerManager .sqlServers() .firewallRules() .getBySqlServer(rgName, sqlServerName, "AllowAllWindowsAzureIps"); Assertions.assertEquals("0.0.0.0", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.0", firewallRule.endIpAddress()); sqlServer.update().defineFirewallRule("newFirewallRule1") .withIpAddress("0.0.0.2") .attach() .apply(); sqlServer.firewallRules().delete("newFirewallRule2"); final SqlServer finalSqlServer1 = sqlServer; validateResourceNotFound(() -> finalSqlServer1.firewallRules().get("newFirewallRule2")); firewallRule = sqlServerManager .sqlServers() .firewallRules() .define("newFirewallRule2") .withExistingSqlServer(rgName, sqlServerName) .withIpAddress("0.0.0.3") .create(); Assertions.assertEquals("0.0.0.3", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.3", firewallRule.endIpAddress()); firewallRule = firewallRule.update().withStartIpAddress("0.0.0.1").apply(); Assertions.assertEquals("0.0.0.1", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.3", firewallRule.endIpAddress()); sqlServer.firewallRules().delete("somefirewallrule1"); validateResourceNotFound( () -> sqlServerManager .sqlServers() .firewallRules() .getBySqlServer(rgName, sqlServerName, "somefirewallrule1")); firewallRule = sqlServer.firewallRules().define("somefirewallrule2").withIpAddress("0.0.0.4").create(); Assertions.assertEquals("0.0.0.4", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.4", firewallRule.endIpAddress()); firewallRule.delete(); } @Test public void canCRUDSqlServer() throws Exception { CheckNameAvailabilityResult checkNameResult = sqlServerManager.sqlServers().checkNameAvailability(sqlServerName); Assertions.assertTrue(checkNameResult.isAvailable()); SqlServer sqlServer = createSqlServer(); validateSqlServer(sqlServer); checkNameResult = sqlServerManager.sqlServers().checkNameAvailability(sqlServerName); Assertions.assertFalse(checkNameResult.isAvailable()); Assertions .assertEquals( CheckNameAvailabilityReason.ALREADY_EXISTS.toString(), checkNameResult.unavailabilityReason()); sqlServer.update().withAdministratorPassword("P@ssword~2").apply(); PagedIterable<SqlServer> sqlServers = sqlServerManager.sqlServers().listByResourceGroup(rgName); boolean found = false; for (SqlServer server : sqlServers) { if (server.name().equals(sqlServerName)) { found = true; } } Assertions.assertTrue(found); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); Assertions.assertNotNull(sqlServer); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test public void canUseCoolShortcutsForResourceCreation() throws Exception { String database2Name = "database2"; String database1InEPName = "database1InEP"; String database2InEPName = "database2InEP"; String elasticPool2Name = "elasticPool2"; String elasticPool3Name = "elasticPool3"; String elasticPool1Name = SQL_ELASTIC_POOL_NAME; SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin("userName") .withAdministratorPassword("Password~1") .withoutAccessFromAzureServices() .defineDatabase(SQL_DATABASE_NAME).attach() .defineDatabase(database2Name).attach() .defineElasticPool(elasticPool1Name).withStandardPool().attach() .defineElasticPool(elasticPool2Name).withPremiumPool().attach() .defineElasticPool(elasticPool3Name).withStandardPool().attach() .defineDatabase(database1InEPName).withExistingElasticPool(elasticPool2Name).attach() .defineDatabase(database2InEPName).withExistingElasticPool(elasticPool2Name).attach() .defineFirewallRule(SQL_FIREWALLRULE_NAME).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddress(START_IPADDRESS).attach() .create(); validateMultiCreation( database2Name, database1InEPName, database2InEPName, elasticPool1Name, elasticPool2Name, elasticPool3Name, sqlServer, false); elasticPool1Name = SQL_ELASTIC_POOL_NAME + " U"; database2Name = "database2U"; database1InEPName = "database1InEPU"; database2InEPName = "database2InEPU"; elasticPool2Name = "elasticPool2U"; elasticPool3Name = "elasticPool3U"; sqlServer = sqlServer .update() .defineDatabase(SQL_DATABASE_NAME).attach() .defineDatabase(database2Name).attach() .defineElasticPool(elasticPool1Name).withStandardPool().attach() .defineElasticPool(elasticPool2Name).withPremiumPool().attach() .defineElasticPool(elasticPool3Name).withStandardPool().attach() .defineDatabase(database1InEPName).withExistingElasticPool(elasticPool2Name).attach() .defineDatabase(database2InEPName).withExistingElasticPool(elasticPool2Name).attach() .defineFirewallRule(SQL_FIREWALLRULE_NAME).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddress(START_IPADDRESS).attach() .withTag("tag2", "value2") .apply(); validateMultiCreation( database2Name, database1InEPName, database2InEPName, elasticPool1Name, elasticPool2Name, elasticPool3Name, sqlServer, true); sqlServer.refresh(); Assertions.assertEquals(sqlServer.elasticPools().list().size(), 0); PagedIterable<SqlServer> sqlServers = sqlServerManager.sqlServers().listByResourceGroup(rgName); boolean found = false; for (SqlServer server : sqlServers) { if (server.name().equals(sqlServerName)) { found = true; } } Assertions.assertTrue(found); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); Assertions.assertNotNull(sqlServer); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test @Test public void canManageReplicationLinks() throws Exception { String anotherSqlServerName = sqlServerName + "another"; SqlServer sqlServer1 = createSqlServer(); SqlServer sqlServer2 = createSqlServer(anotherSqlServerName); Mono<SqlDatabase> resourceStream = sqlServer1 .databases() .define(SQL_DATABASE_NAME) .withCollation(COLLATION) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .createAsync(); SqlDatabase databaseInServer1 = resourceStream.block(); validateSqlDatabase(databaseInServer1, SQL_DATABASE_NAME); SqlDatabase databaseInServer2 = sqlServer2 .databases() .define(SQL_DATABASE_NAME) .withSourceDatabase(databaseInServer1.id()) .withMode(CreateMode.ONLINE_SECONDARY) .create(); ResourceManagerUtils.sleep(Duration.ofSeconds(2)); List<ReplicationLink> replicationLinksInDb1 = new ArrayList<>(databaseInServer1.listReplicationLinks().values()); Assertions.assertEquals(replicationLinksInDb1.size(), 1); Assertions.assertEquals(replicationLinksInDb1.get(0).partnerDatabase(), databaseInServer2.name()); Assertions.assertEquals(replicationLinksInDb1.get(0).partnerServer(), databaseInServer2.sqlServerName()); List<ReplicationLink> replicationLinksInDb2 = new ArrayList<>(databaseInServer2.listReplicationLinks().values()); Assertions.assertEquals(replicationLinksInDb2.size(), 1); Assertions.assertEquals(replicationLinksInDb2.get(0).partnerDatabase(), databaseInServer1.name()); Assertions.assertEquals(replicationLinksInDb2.get(0).partnerServer(), databaseInServer1.sqlServerName()); Assertions.assertNotNull(replicationLinksInDb1.get(0).refresh()); replicationLinksInDb2.get(0).failover(); replicationLinksInDb2.get(0).refresh(); ResourceManagerUtils.sleep(Duration.ofSeconds(30)); replicationLinksInDb1.get(0).forceFailoverAllowDataLoss(); replicationLinksInDb1.get(0).refresh(); ResourceManagerUtils.sleep(Duration.ofSeconds(30)); replicationLinksInDb2.get(0).delete(); Assertions.assertEquals(databaseInServer2.listReplicationLinks().size(), 0); sqlServer1.databases().delete(databaseInServer1.name()); sqlServer2.databases().delete(databaseInServer2.name()); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer2.resourceGroupName(), sqlServer2.name()); validateSqlServerNotFound(sqlServer2); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer1.resourceGroupName(), sqlServer1.name()); validateSqlServerNotFound(sqlServer1); } @Test public void canDoOperationsOnDataWarehouse() throws Exception { SqlServer sqlServer = createSqlServer(); validateSqlServer(sqlServer); Mono<SqlDatabase> resourceStream = sqlServer .databases() .define(SQL_DATABASE_NAME) .withCollation(COLLATION) .withSku(DatabaseSku.DATAWAREHOUSE_DW1000C) .createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); Assertions.assertNotNull(sqlDatabase); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertNotNull(sqlDatabase); Assertions.assertTrue(sqlDatabase.isDataWarehouse()); SqlWarehouse dataWarehouse = sqlServer.databases().get(SQL_DATABASE_NAME).asWarehouse(); Assertions.assertNotNull(dataWarehouse); Assertions.assertEquals(dataWarehouse.name(), SQL_DATABASE_NAME); Assertions.assertEquals(DatabaseEdition.DATA_WAREHOUSE, dataWarehouse.edition()); Assertions.assertNotNull(dataWarehouse.listRestorePoints()); dataWarehouse.pauseDataWarehouse(); dataWarehouse.resumeDataWarehouse(); sqlServer.databases().delete(SQL_DATABASE_NAME); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test public void canCRUDSqlDatabaseWithElasticPool() throws Exception { SqlServer sqlServer = createSqlServer(); Creatable<SqlElasticPool> sqlElasticPoolCreatable = sqlServer .elasticPools() .define(SQL_ELASTIC_POOL_NAME) .withStandardPool() .withTag("tag1", "value1"); Mono<SqlDatabase> resourceStream = sqlServer .databases() .define(SQL_DATABASE_NAME) .withNewElasticPool(sqlElasticPoolCreatable) .withCollation(COLLATION) .createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); validateSqlDatabase(sqlDatabase, SQL_DATABASE_NAME); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); SqlElasticPool elasticPool = sqlServer.elasticPools().get(SQL_ELASTIC_POOL_NAME); validateSqlElasticPool(elasticPool); validateSqlDatabaseWithElasticPool(sqlServer.databases().get(SQL_DATABASE_NAME), SQL_DATABASE_NAME); validateListSqlDatabase(sqlServer.databases().list()); sqlDatabase .update() .withoutElasticPool() .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) .apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertNull(sqlDatabase.elasticPoolName()); sqlDatabase.update().withPremiumEdition(SqlDatabasePremiumServiceObjective.P1).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertEquals(sqlDatabase.edition(), DatabaseEdition.PREMIUM); Assertions.assertEquals(sqlDatabase.currentServiceObjectiveName(), ServiceObjectiveName.P1.toString()); sqlDatabase.update().withPremiumEdition(SqlDatabasePremiumServiceObjective.P2).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertEquals(sqlDatabase.currentServiceObjectiveName(), ServiceObjectiveName.P2.toString()); Assertions.assertEquals(sqlDatabase.requestedServiceObjectiveName(), ServiceObjectiveName.P2.toString()); sqlDatabase.update().withMaxSizeBytes(268435456000L).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertEquals(sqlDatabase.maxSizeBytes(), 268435456000L); sqlDatabase.update().withExistingElasticPool(SQL_ELASTIC_POOL_NAME).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertEquals(sqlDatabase.elasticPoolName(), SQL_ELASTIC_POOL_NAME); Assertions.assertNotNull(elasticPool.listActivities()); List<SqlDatabase> databasesInElasticPool = elasticPool.listDatabases(); Assertions.assertNotNull(databasesInElasticPool); Assertions.assertEquals(databasesInElasticPool.size(), 1); SqlDatabase databaseInElasticPool = elasticPool.getDatabase(SQL_DATABASE_NAME); validateSqlDatabase(databaseInElasticPool, SQL_DATABASE_NAME); databaseInElasticPool.refresh(); validateResourceNotFound(() -> elasticPool.getDatabase("does_not_exist")); sqlServer.databases().delete(SQL_DATABASE_NAME); validateSqlDatabaseNotFound(SQL_DATABASE_NAME); SqlElasticPool sqlElasticPool = sqlServer.elasticPools().get(SQL_ELASTIC_POOL_NAME); resourceStream = sqlServer .databases() .define("newDatabase") .withExistingElasticPool(sqlElasticPool) .withCollation(COLLATION) .createAsync(); sqlDatabase = resourceStream.block(); sqlServer.databases().delete(sqlDatabase.name()); validateSqlDatabaseNotFound("newDatabase"); sqlServer.elasticPools().delete(SQL_ELASTIC_POOL_NAME); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test public void canCRUDSqlElasticPool() throws Exception { SqlServer sqlServer = createSqlServer(); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); Mono<SqlElasticPool> resourceStream = sqlServer .elasticPools() .define(SQL_ELASTIC_POOL_NAME) .withStandardPool() .withTag("tag1", "value1") .createAsync(); SqlElasticPool sqlElasticPool = resourceStream.block(); validateSqlElasticPool(sqlElasticPool); Assertions.assertEquals(sqlElasticPool.listDatabases().size(), 0); sqlElasticPool = sqlElasticPool .update() .withReservedDtu(SqlElasticPoolBasicEDTUs.eDTU_100) .withDatabaseMaxCapacity(20) .withDatabaseMinCapacity(10) .withStorageCapacity(102400 * 1024 * 1024L) .withNewDatabase(SQL_DATABASE_NAME) .withTag("tag2", "value2") .apply(); validateSqlElasticPool(sqlElasticPool); Assertions.assertEquals(sqlElasticPool.listDatabases().size(), 1); Assertions.assertNotNull(sqlElasticPool.getDatabase(SQL_DATABASE_NAME)); validateSqlElasticPool(sqlServer.elasticPools().get(SQL_ELASTIC_POOL_NAME)); validateListSqlElasticPool(sqlServer.elasticPools().list()); sqlServer.databases().delete(SQL_DATABASE_NAME); sqlServer.elasticPools().delete(SQL_ELASTIC_POOL_NAME); validateSqlElasticPoolNotFound(sqlServer, SQL_ELASTIC_POOL_NAME); resourceStream = sqlServer.elasticPools().define("newElasticPool").withStandardPool().createAsync(); sqlElasticPool = resourceStream.block(); sqlServer.elasticPools().delete(sqlElasticPool.name()); validateSqlElasticPoolNotFound(sqlServer, "newElasticPool"); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test public void canCRUDSqlFirewallRule() throws Exception { SqlServer sqlServer = createSqlServer(); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); Mono<SqlFirewallRule> resourceStream = sqlServer .firewallRules() .define(SQL_FIREWALLRULE_NAME) .withIpAddressRange(START_IPADDRESS, END_IPADDRESS) .createAsync(); SqlFirewallRule sqlFirewallRule = resourceStream.block(); validateSqlFirewallRule(sqlFirewallRule, SQL_FIREWALLRULE_NAME); validateSqlFirewallRule(sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME), SQL_FIREWALLRULE_NAME); String secondFirewallRuleName = "secondFireWallRule"; SqlFirewallRule secondFirewallRule = sqlServer.firewallRules().define(secondFirewallRuleName).withIpAddress(START_IPADDRESS).create(); Assertions.assertNotNull(secondFirewallRule); secondFirewallRule = sqlServer.firewallRules().get(secondFirewallRuleName); Assertions.assertNotNull(secondFirewallRule); Assertions.assertEquals(START_IPADDRESS, secondFirewallRule.endIpAddress()); secondFirewallRule = secondFirewallRule.update().withEndIpAddress(END_IPADDRESS).apply(); validateSqlFirewallRule(secondFirewallRule, secondFirewallRuleName); sqlServer.firewallRules().delete(secondFirewallRuleName); final SqlServer finalSqlServer = sqlServer; validateResourceNotFound(() -> finalSqlServer.firewallRules().get(secondFirewallRuleName)); sqlFirewallRule = sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME); validateSqlFirewallRule(sqlFirewallRule, SQL_FIREWALLRULE_NAME); sqlFirewallRule.update().withEndIpAddress(START_IPADDRESS).apply(); sqlFirewallRule = sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME); Assertions.assertEquals(sqlFirewallRule.endIpAddress(), START_IPADDRESS); validateListSqlFirewallRule(sqlServer.firewallRules().list()); sqlServer.firewallRules().delete(sqlFirewallRule.name()); validateSqlFirewallRuleNotFound(); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } private void validateMultiCreation( String database2Name, String database1InEPName, String database2InEPName, String elasticPool1Name, String elasticPool2Name, String elasticPool3Name, SqlServer sqlServer, boolean deleteUsingUpdate) { validateSqlServer(sqlServer); validateSqlServer(sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName)); validateSqlDatabase(sqlServer.databases().get(SQL_DATABASE_NAME), SQL_DATABASE_NAME); validateSqlFirewallRule(sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME), SQL_FIREWALLRULE_NAME); List<SqlFirewallRule> firewalls = sqlServer.firewallRules().list(); Assertions.assertEquals(3, firewalls.size()); int startIPAddress = 0; int endIPAddress = 0; for (SqlFirewallRule firewall : firewalls) { if (!firewall.name().equalsIgnoreCase(SQL_FIREWALLRULE_NAME)) { Assertions.assertEquals(firewall.startIpAddress(), START_IPADDRESS); if (firewall.endIpAddress().equalsIgnoreCase(START_IPADDRESS)) { startIPAddress++; } else if (firewall.endIpAddress().equalsIgnoreCase(END_IPADDRESS)) { endIPAddress++; } } } Assertions.assertEquals(startIPAddress, 1); Assertions.assertEquals(endIPAddress, 1); Assertions.assertNotNull(sqlServer.databases().get(database2Name)); Assertions.assertNotNull(sqlServer.databases().get(database1InEPName)); Assertions.assertNotNull(sqlServer.databases().get(database2InEPName)); SqlElasticPool ep1 = sqlServer.elasticPools().get(elasticPool1Name); validateSqlElasticPool(ep1, elasticPool1Name); SqlElasticPool ep2 = sqlServer.elasticPools().get(elasticPool2Name); Assertions.assertNotNull(ep2); Assertions.assertEquals(ElasticPoolEdition.PREMIUM, ep2.edition()); Assertions.assertEquals(ep2.listDatabases().size(), 2); Assertions.assertNotNull(ep2.getDatabase(database1InEPName)); Assertions.assertNotNull(ep2.getDatabase(database2InEPName)); SqlElasticPool ep3 = sqlServer.elasticPools().get(elasticPool3Name); Assertions.assertNotNull(ep3); Assertions.assertEquals(ElasticPoolEdition.STANDARD, ep3.edition()); if (!deleteUsingUpdate) { sqlServer.databases().delete(database2Name); sqlServer.databases().delete(database1InEPName); sqlServer.databases().delete(database2InEPName); sqlServer.databases().delete(SQL_DATABASE_NAME); Assertions.assertEquals(ep1.listDatabases().size(), 0); Assertions.assertEquals(ep2.listDatabases().size(), 0); Assertions.assertEquals(ep3.listDatabases().size(), 0); sqlServer.elasticPools().delete(elasticPool1Name); sqlServer.elasticPools().delete(elasticPool2Name); sqlServer.elasticPools().delete(elasticPool3Name); firewalls = sqlServer.firewallRules().list(); for (SqlFirewallRule firewallRule : firewalls) { firewallRule.delete(); } } else { sqlServer .update() .withoutDatabase(database2Name) .withoutElasticPool(elasticPool1Name) .withoutElasticPool(elasticPool2Name) .withoutElasticPool(elasticPool3Name) .withoutDatabase(database1InEPName) .withoutDatabase(SQL_DATABASE_NAME) .withoutDatabase(database2InEPName) .withoutFirewallRule(SQL_FIREWALLRULE_NAME) .apply(); Assertions.assertEquals(sqlServer.elasticPools().list().size(), 0); firewalls = sqlServer.firewallRules().list(); Assertions.assertEquals(firewalls.size(), 2); for (SqlFirewallRule firewallRule : firewalls) { firewallRule.delete(); } } Assertions.assertEquals(sqlServer.elasticPools().list().size(), 0); Assertions.assertEquals(sqlServer.databases().list().size(), 1); } private void validateSqlFirewallRuleNotFound() { validateResourceNotFound( () -> sqlServerManager .sqlServers() .getByResourceGroup(rgName, sqlServerName) .firewallRules() .get(SQL_FIREWALLRULE_NAME)); } private void validateSqlElasticPoolNotFound(SqlServer sqlServer, String elasticPoolName) { validateResourceNotFound(() -> sqlServer.elasticPools().get(elasticPoolName)); } private void validateSqlDatabaseNotFound(String newDatabase) { validateResourceNotFound( () -> sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName).databases().get(newDatabase)); } private void validateSqlServerNotFound(SqlServer sqlServer) { validateResourceNotFound(() -> sqlServerManager.sqlServers().getById(sqlServer.id())); } private void validateResourceNotFound(Supplier<Object> fetchResource) { try { Object result = fetchResource.get(); Assertions.assertNull(result); } catch (ManagementException e) { Assertions.assertEquals(404, e.getResponse().getStatusCode()); } } private SqlServer createSqlServer() { return createSqlServer(sqlServerName); } private SqlServer createSqlServer(String sqlServerName) { return sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin("userName") .withAdministratorPassword("P@ssword~1") .create(); } private static void validateListSqlFirewallRule(List<SqlFirewallRule> sqlFirewallRules) { boolean found = false; for (SqlFirewallRule firewallRule : sqlFirewallRules) { if (firewallRule.name().equals(SQL_FIREWALLRULE_NAME)) { found = true; } } Assertions.assertTrue(found); } private void validateSqlFirewallRule(SqlFirewallRule sqlFirewallRule, String firewallName) { Assertions.assertNotNull(sqlFirewallRule); Assertions.assertEquals(firewallName, sqlFirewallRule.name()); Assertions.assertEquals(sqlServerName, sqlFirewallRule.sqlServerName()); Assertions.assertEquals(START_IPADDRESS, sqlFirewallRule.startIpAddress()); Assertions.assertEquals(END_IPADDRESS, sqlFirewallRule.endIpAddress()); Assertions.assertEquals(rgName, sqlFirewallRule.resourceGroupName()); Assertions.assertEquals(sqlServerName, sqlFirewallRule.sqlServerName()); Assertions.assertEquals(Region.US_EAST, sqlFirewallRule.region()); } private static void validateListSqlElasticPool(List<SqlElasticPool> sqlElasticPools) { boolean found = false; for (SqlElasticPool elasticPool : sqlElasticPools) { if (elasticPool.name().equals(SQL_ELASTIC_POOL_NAME)) { found = true; } } Assertions.assertTrue(found); } private void validateSqlElasticPool(SqlElasticPool sqlElasticPool) { validateSqlElasticPool(sqlElasticPool, SQL_ELASTIC_POOL_NAME); } private void validateSqlElasticPool(SqlElasticPool sqlElasticPool, String elasticPoolName) { Assertions.assertNotNull(sqlElasticPool); Assertions.assertEquals(rgName, sqlElasticPool.resourceGroupName()); Assertions.assertEquals(elasticPoolName, sqlElasticPool.name()); Assertions.assertEquals(sqlServerName, sqlElasticPool.sqlServerName()); Assertions.assertEquals(ElasticPoolEdition.STANDARD, sqlElasticPool.edition()); Assertions.assertNotNull(sqlElasticPool.creationDate()); Assertions.assertNotEquals(0, sqlElasticPool.databaseDtuMax()); Assertions.assertNotEquals(0, sqlElasticPool.dtu()); } private static void validateListSqlDatabase(List<SqlDatabase> sqlDatabases) { boolean found = false; for (SqlDatabase database : sqlDatabases) { if (database.name().equals(SQL_DATABASE_NAME)) { found = true; } } Assertions.assertTrue(found); } private void validateSqlServer(SqlServer sqlServer) { Assertions.assertNotNull(sqlServer); Assertions.assertEquals(rgName, sqlServer.resourceGroupName()); Assertions.assertNotNull(sqlServer.fullyQualifiedDomainName()); Assertions.assertEquals("userName", sqlServer.administratorLogin()); } private void validateSqlDatabase(SqlDatabase sqlDatabase, String databaseName) { Assertions.assertNotNull(sqlDatabase); Assertions.assertEquals(sqlDatabase.name(), databaseName); Assertions.assertEquals(sqlServerName, sqlDatabase.sqlServerName()); Assertions.assertEquals(sqlDatabase.collation(), COLLATION); Assertions.assertEquals(DatabaseEdition.STANDARD, sqlDatabase.edition()); } private void validateSqlDatabaseWithElasticPool(SqlDatabase sqlDatabase, String databaseName) { validateSqlDatabase(sqlDatabase, databaseName); Assertions.assertEquals(SQL_ELASTIC_POOL_NAME, sqlDatabase.elasticPoolName()); } @Test public void testRandomSku() { List<DatabaseSku> databaseSkus = DatabaseSku.getAll().stream().filter(sku -> !"M".equals(sku.toSku().family())).collect(Collectors.toCollection(LinkedList::new)); Collections.shuffle(databaseSkus); List<ElasticPoolSku> elasticPoolSkus = ElasticPoolSku.getAll().stream().filter(sku -> !"M".equals(sku.toSku().family())).collect(Collectors.toCollection(LinkedList::new)); Collections.shuffle(elasticPoolSkus); sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST).supportedCapabilitiesByServerVersion() .forEach((x, serverVersionCapability) -> { serverVersionCapability.supportedEditions().forEach(edition -> { edition.supportedServiceLevelObjectives().forEach(serviceObjective -> { if (serviceObjective.status() != CapabilityStatus.AVAILABLE && serviceObjective.status() != CapabilityStatus.DEFAULT || "M".equals(serviceObjective.sku().family())) { databaseSkus.remove(DatabaseSku.fromSku(serviceObjective.sku())); } }); }); serverVersionCapability.supportedElasticPoolEditions().forEach(edition -> { edition.supportedElasticPoolPerformanceLevels().forEach(performance -> { if (performance.status() != CapabilityStatus.AVAILABLE && performance.status() != CapabilityStatus.DEFAULT || "M".equals(performance.sku().family())) { elasticPoolSkus.remove(ElasticPoolSku.fromSku(performance.sku())); } }); }); }); SqlServer sqlServer = sqlServerManager.sqlServers().define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin("userName") .withAdministratorPassword(password()) .create(); Flux.merge( Flux.range(0, 3) .flatMap(i -> sqlServer.databases().define("database" + i).withSku(databaseSkus.get(i)).createAsync().cast(Indexable.class)), Flux.range(0, 3) .flatMap(i -> sqlServer.elasticPools().define("elasticPool" + i).withSku(elasticPoolSkus.get(i)).createAsync().cast(Indexable.class)) ) .blockLast(); } @Test @Disabled("Only run for updating sku") public void generateSku() throws IOException { StringBuilder databaseSkuBuilder = new StringBuilder(); StringBuilder elasticPoolSkuBuilder = new StringBuilder(); sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST).supportedCapabilitiesByServerVersion() .forEach((x, serverVersionCapability) -> { serverVersionCapability.supportedEditions().forEach(edition -> { if (edition.name().equalsIgnoreCase("System")) { return; } edition.supportedServiceLevelObjectives().forEach(serviceObjective -> { addStaticSkuDefinition(databaseSkuBuilder, edition.name(), serviceObjective.name(), serviceObjective.sku(), "DatabaseSku"); }); }); serverVersionCapability.supportedElasticPoolEditions().forEach(edition -> { if (edition.name().equalsIgnoreCase("System")) { return; } edition.supportedElasticPoolPerformanceLevels().forEach(performance -> { String detailName = String.format("%s_%d", performance.sku().name(), performance.sku().capacity()); addStaticSkuDefinition(elasticPoolSkuBuilder, edition.name(), detailName, performance.sku(), "ElasticPoolSku"); }); }); }); String databaseSku = new String(readAllBytes(getClass().getResourceAsStream("/DatabaseSku.java")), StandardCharsets.UTF_8); databaseSku = databaseSku.replace("<Generated>", databaseSkuBuilder.toString()); Files.write(new File("src/main/java/com/azure/resourcemanager/sql/models/DatabaseSku.java").toPath(), databaseSku.getBytes(StandardCharsets.UTF_8)); String elasticPoolSku = new String(readAllBytes(getClass().getResourceAsStream("/ElasticPoolSku.java")), StandardCharsets.UTF_8); elasticPoolSku = elasticPoolSku.replace("<Generated>", elasticPoolSkuBuilder.toString()); Files.write(new File("src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolSku.java").toPath(), elasticPoolSku.getBytes(StandardCharsets.UTF_8)); sqlServerManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); } private byte[] readAllBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] data = new byte[4096]; while (true) { int size = inputStream.read(data); if (size > 0) { outputStream.write(data, 0, size); } else { return outputStream.toByteArray(); } } } } private void addStaticSkuDefinition(StringBuilder builder, String edition, String detailName, Sku sku, String className) { builder .append("\n ").append("/** ").append(edition).append(" Edition with ").append(detailName).append(" sku. */") .append("\n ").append("public static final ").append(className).append(" ").append(String.format("%s_%s", edition.toUpperCase(Locale.ROOT), detailName.toUpperCase(Locale.ROOT))).append(" =") .append("\n new ").append(className).append("(") .append(sku.name() == null ? null : "\"" + sku.name() + "\"") .append(", ") .append(sku.tier() == null ? null : "\"" + sku.tier() + "\"") .append(", ") .append(sku.family() == null ? null : "\"" + sku.family() + "\"") .append(", ") .append(sku.capacity()) .append(", ") .append(sku.size() == null ? null : "\"" + sku.size() + "\"") .append(");"); } }
class SqlServerOperationsTests extends SqlServerTest { private static final String SQL_DATABASE_NAME = "myTestDatabase2"; private static final String COLLATION = "SQL_Latin1_General_CP1_CI_AS"; private static final String SQL_ELASTIC_POOL_NAME = "testElasticPool"; private static final String SQL_FIREWALLRULE_NAME = "firewallrule1"; private static final String START_IPADDRESS = "10.102.1.10"; private static final String END_IPADDRESS = "10.102.1.12"; @Test public void canCRUDSqlSyncMember() throws Exception { final String dbName = "dbSample"; final String dbSyncName = "dbSync"; final String dbMemberName = "dbMember"; final String syncGroupName = "groupName"; final String syncMemberName = "memberName"; final String administratorLogin = "sqladmin"; final String administratorPassword = password(); SqlServer sqlPrimaryServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .defineDatabase(dbSyncName) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .defineDatabase(dbMemberName) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .create(); SqlDatabase dbSource = sqlPrimaryServer.databases().get(dbName); SqlDatabase dbSync = sqlPrimaryServer.databases().get(dbSyncName); SqlDatabase dbMember = sqlPrimaryServer.databases().get(dbMemberName); SqlSyncGroup sqlSyncGroup = dbSync .syncGroups() .define(syncGroupName) .withSyncDatabaseId(dbSource.id()) .withDatabaseUserName(administratorLogin) .withDatabasePassword(administratorPassword) .withConflictResolutionPolicyHubWins() .withInterval(-1) .create(); Assertions.assertNotNull(sqlSyncGroup); SqlSyncMember sqlSyncMember = sqlSyncGroup .syncMembers() .define(syncMemberName) .withMemberSqlDatabase(dbMember) .withMemberUserName(administratorLogin) .withMemberPassword(administratorPassword) .withMemberDatabaseType(SyncMemberDbType.AZURE_SQL_DATABASE) .withDatabaseType(SyncDirection.ONE_WAY_MEMBER_TO_HUB) .create(); Assertions.assertNotNull(sqlSyncMember); sqlSyncMember .update() .withDatabaseType(SyncDirection.BIDIRECTIONAL) .withMemberUserName(administratorLogin) .withMemberPassword(administratorPassword) .withMemberDatabaseType(SyncMemberDbType.AZURE_SQL_DATABASE) .apply(); Assertions.assertFalse(sqlSyncGroup.syncMembers().list().isEmpty()); sqlSyncMember = sqlServerManager .sqlServers() .syncMembers() .getBySqlServer(rgName, sqlServerName, dbSyncName, syncGroupName, syncMemberName); Assertions.assertNotNull(sqlSyncMember); sqlSyncMember.delete(); sqlSyncGroup.delete(); } @Test public void canCRUDSqlSyncGroup() throws Exception { final String dbName = "dbSample"; final String dbSyncName = "dbSync"; final String syncGroupName = "groupName"; final String administratorLogin = "sqladmin"; final String administratorPassword = password(); SqlServer sqlPrimaryServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .defineDatabase(dbSyncName) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .create(); SqlDatabase dbSource = sqlPrimaryServer.databases().get(dbName); SqlDatabase dbSync = sqlPrimaryServer.databases().get(dbSyncName); SqlSyncGroup sqlSyncGroup = dbSync .syncGroups() .define(syncGroupName) .withSyncDatabaseId(dbSource.id()) .withDatabaseUserName(administratorLogin) .withDatabasePassword(administratorPassword) .withConflictResolutionPolicyHubWins() .withInterval(-1) .create(); Assertions.assertNotNull(sqlSyncGroup); Assertions .assertTrue( sqlServerManager .sqlServers() .syncGroups() .listSyncDatabaseIds(Region.US_EAST) .stream() .findAny() .isPresent()); Assertions.assertFalse(dbSync.syncGroups().list().isEmpty()); sqlSyncGroup = sqlServerManager.sqlServers().syncGroups().getBySqlServer(rgName, sqlServerName, dbSyncName, syncGroupName); Assertions.assertNotNull(sqlSyncGroup); sqlSyncGroup.delete(); } @Test public void canCopySqlDatabase() throws Exception { final String sqlPrimaryServerName = generateRandomResourceName("sqlpri", 22); final String sqlSecondaryServerName = generateRandomResourceName("sqlsec", 22); final String epName = "epSample"; final String dbName = "dbSample"; final String administratorLogin = "sqladmin"; final String administratorPassword = password(); SqlServer sqlPrimaryServer = sqlServerManager .sqlServers() .define(sqlPrimaryServerName) .withRegion(Region.US_EAST2) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineElasticPool(epName) .withPremiumPool() .attach() .defineDatabase(dbName) .withExistingElasticPool(epName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .attach() .create(); SqlServer sqlSecondaryServer = sqlServerManager .sqlServers() .define(sqlSecondaryServerName) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .create(); SqlDatabase dbSample = sqlPrimaryServer.databases().get(dbName); SqlDatabase dbCopy = sqlSecondaryServer .databases() .define("dbCopy") .withSourceDatabase(dbSample) .withMode(CreateMode.COPY) .withPremiumEdition(SqlDatabasePremiumServiceObjective.P1) .create(); Assertions.assertNotNull(dbCopy); } @Test public void canCRUDSqlFailoverGroup() throws Exception { final String sqlPrimaryServerName = generateRandomResourceName("sqlpri", 22); final String sqlSecondaryServerName = generateRandomResourceName("sqlsec", 22); final String sqlOtherServerName = generateRandomResourceName("sql000", 22); final String failoverGroupName = generateRandomResourceName("fg", 22); final String failoverGroupName2 = generateRandomResourceName("fg2", 22); final String dbName = "dbSample"; final String administratorLogin = "sqladmin"; final String administratorPassword = password(); SqlServer sqlPrimaryServer = sqlServerManager .sqlServers() .define(sqlPrimaryServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .defineDatabase(dbName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .attach() .create(); SqlServer sqlSecondaryServer = sqlServerManager .sqlServers() .define(sqlSecondaryServerName) .withRegion(Region.US_EAST2) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .create(); SqlServer sqlOtherServer = sqlServerManager .sqlServers() .define(sqlOtherServerName) .withRegion(Region.US_SOUTH_CENTRAL) .withExistingResourceGroup(rgName) .withAdministratorLogin(administratorLogin) .withAdministratorPassword(administratorPassword) .create(); SqlFailoverGroup failoverGroup = sqlPrimaryServer .failoverGroups() .define(failoverGroupName) .withManualReadWriteEndpointPolicy() .withPartnerServerId(sqlSecondaryServer.id()) .withReadOnlyEndpointPolicyDisabled() .create(); Assertions.assertNotNull(failoverGroup); Assertions.assertEquals(failoverGroupName, failoverGroup.name()); Assertions.assertEquals(rgName, failoverGroup.resourceGroupName()); Assertions.assertEquals(sqlPrimaryServerName, failoverGroup.sqlServerName()); Assertions.assertEquals(FailoverGroupReplicationRole.PRIMARY, failoverGroup.replicationRole()); Assertions.assertEquals(1, failoverGroup.partnerServers().size()); Assertions.assertEquals(sqlSecondaryServer.id(), failoverGroup.partnerServers().get(0).id()); Assertions .assertEquals( FailoverGroupReplicationRole.SECONDARY, failoverGroup.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroup.databases().size()); Assertions.assertEquals(0, failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, failoverGroup.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.DISABLED, failoverGroup.readOnlyEndpointPolicy()); SqlFailoverGroup failoverGroupOnPartner = sqlSecondaryServer.failoverGroups().get(failoverGroup.name()); Assertions.assertEquals(failoverGroupName, failoverGroupOnPartner.name()); Assertions.assertEquals(rgName, failoverGroupOnPartner.resourceGroupName()); Assertions.assertEquals(sqlSecondaryServerName, failoverGroupOnPartner.sqlServerName()); Assertions.assertEquals(FailoverGroupReplicationRole.SECONDARY, failoverGroupOnPartner.replicationRole()); Assertions.assertEquals(1, failoverGroupOnPartner.partnerServers().size()); Assertions.assertEquals(sqlPrimaryServer.id(), failoverGroupOnPartner.partnerServers().get(0).id()); Assertions .assertEquals( FailoverGroupReplicationRole.PRIMARY, failoverGroupOnPartner.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroupOnPartner.databases().size()); Assertions.assertEquals(0, failoverGroupOnPartner.readWriteEndpointDataLossGracePeriodMinutes()); Assertions .assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, failoverGroupOnPartner.readWriteEndpointPolicy()); Assertions .assertEquals(ReadOnlyEndpointFailoverPolicy.DISABLED, failoverGroupOnPartner.readOnlyEndpointPolicy()); SqlFailoverGroup failoverGroup2 = sqlPrimaryServer .failoverGroups() .define(failoverGroupName2) .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) .withPartnerServerId(sqlOtherServer.id()) .withReadOnlyEndpointPolicyEnabled() .create(); Assertions.assertNotNull(failoverGroup2); Assertions.assertEquals(failoverGroupName2, failoverGroup2.name()); Assertions.assertEquals(rgName, failoverGroup2.resourceGroupName()); Assertions.assertEquals(sqlPrimaryServerName, failoverGroup2.sqlServerName()); Assertions.assertEquals(FailoverGroupReplicationRole.PRIMARY, failoverGroup2.replicationRole()); Assertions.assertEquals(1, failoverGroup2.partnerServers().size()); Assertions.assertEquals(sqlOtherServer.id(), failoverGroup2.partnerServers().get(0).id()); Assertions .assertEquals( FailoverGroupReplicationRole.SECONDARY, failoverGroup2.partnerServers().get(0).replicationRole()); Assertions.assertEquals(0, failoverGroup2.databases().size()); Assertions.assertEquals(120, failoverGroup2.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.AUTOMATIC, failoverGroup2.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.ENABLED, failoverGroup2.readOnlyEndpointPolicy()); failoverGroup .update() .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) .withReadOnlyEndpointPolicyEnabled() .withTag("tag1", "value1") .apply(); Assertions.assertEquals(120, failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.AUTOMATIC, failoverGroup.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.ENABLED, failoverGroup.readOnlyEndpointPolicy()); SqlDatabase db = sqlPrimaryServer.databases().get(dbName); failoverGroup .update() .withManualReadWriteEndpointPolicy() .withReadOnlyEndpointPolicyDisabled() .withNewDatabaseId(db.id()) .apply(); Assertions.assertEquals(1, failoverGroup.databases().size()); Assertions.assertEquals(db.id(), failoverGroup.databases().get(0)); Assertions.assertEquals(0, failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()); Assertions.assertEquals(ReadWriteEndpointFailoverPolicy.MANUAL, failoverGroup.readWriteEndpointPolicy()); Assertions.assertEquals(ReadOnlyEndpointFailoverPolicy.DISABLED, failoverGroup.readOnlyEndpointPolicy()); List<SqlFailoverGroup> failoverGroupsList = sqlPrimaryServer.failoverGroups().list(); Assertions.assertEquals(2, failoverGroupsList.size()); failoverGroupsList = sqlSecondaryServer.failoverGroups().list(); Assertions.assertEquals(1, failoverGroupsList.size()); sqlPrimaryServer.failoverGroups().delete(failoverGroup2.name()); } @Test public void canChangeSqlServerAndDatabaseAutomaticTuning() throws Exception { String sqlServerAdminName = "sqladmin"; String sqlServerAdminPassword = password(); String databaseName = "db-from-sample"; String id = generateRandomUuid(); String storageName = generateRandomResourceName(sqlServerName, 22); SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .defineDatabase(databaseName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withBasicEdition() .attach() .create(); SqlDatabase dbFromSample = sqlServer.databases().get(databaseName); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); SqlServerAutomaticTuning serverAutomaticTuning = sqlServer.getServerAutomaticTuning(); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.desiredState()); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.actualState()); Assertions.assertEquals(4, serverAutomaticTuning.tuningOptions().size()); serverAutomaticTuning .update() .withAutomaticTuningMode(AutomaticTuningServerMode.AUTO) .withAutomaticTuningOption("createIndex", AutomaticTuningOptionModeDesired.OFF) .withAutomaticTuningOption("dropIndex", AutomaticTuningOptionModeDesired.ON) .withAutomaticTuningOption("forceLastGoodPlan", AutomaticTuningOptionModeDesired.DEFAULT) .apply(); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.desiredState()); Assertions.assertEquals(AutomaticTuningServerMode.AUTO, serverAutomaticTuning.actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.OFF, serverAutomaticTuning.tuningOptions().get("createIndex").desiredState()); Assertions .assertEquals( AutomaticTuningOptionModeActual.OFF, serverAutomaticTuning.tuningOptions().get("createIndex").actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.ON, serverAutomaticTuning.tuningOptions().get("dropIndex").desiredState()); Assertions .assertEquals( AutomaticTuningOptionModeActual.ON, serverAutomaticTuning.tuningOptions().get("dropIndex").actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.DEFAULT, serverAutomaticTuning.tuningOptions().get("forceLastGoodPlan").desiredState()); SqlDatabaseAutomaticTuning databaseAutomaticTuning = dbFromSample.getDatabaseAutomaticTuning(); Assertions.assertEquals(4, databaseAutomaticTuning.tuningOptions().size()); databaseAutomaticTuning .update() .withAutomaticTuningMode(AutomaticTuningMode.AUTO) .withAutomaticTuningOption("createIndex", AutomaticTuningOptionModeDesired.OFF) .withAutomaticTuningOption("dropIndex", AutomaticTuningOptionModeDesired.ON) .withAutomaticTuningOption("forceLastGoodPlan", AutomaticTuningOptionModeDesired.DEFAULT) .apply(); Assertions.assertEquals(AutomaticTuningMode.AUTO, databaseAutomaticTuning.desiredState()); Assertions.assertEquals(AutomaticTuningMode.AUTO, databaseAutomaticTuning.actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.OFF, databaseAutomaticTuning.tuningOptions().get("createIndex").desiredState()); Assertions .assertEquals( AutomaticTuningOptionModeActual.OFF, databaseAutomaticTuning.tuningOptions().get("createIndex").actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.ON, databaseAutomaticTuning.tuningOptions().get("dropIndex").desiredState()); Assertions .assertEquals( AutomaticTuningOptionModeActual.ON, databaseAutomaticTuning.tuningOptions().get("dropIndex").actualState()); Assertions .assertEquals( AutomaticTuningOptionModeDesired.DEFAULT, databaseAutomaticTuning.tuningOptions().get("forceLastGoodPlan").desiredState()); dbFromSample.delete(); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName); } @Test public void canCreateAndAquireServerDnsAlias() throws Exception { String sqlServerName1 = sqlServerName + "1"; String sqlServerName2 = sqlServerName + "2"; String sqlServerAdminName = "sqladmin"; String sqlServerAdminPassword = password(); SqlServer sqlServer1 = sqlServerManager .sqlServers() .define(sqlServerName1) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .create(); Assertions.assertNotNull(sqlServer1); SqlServerDnsAlias dnsAlias = sqlServer1.dnsAliases().define(sqlServerName).create(); Assertions.assertNotNull(dnsAlias); Assertions.assertEquals(rgName, dnsAlias.resourceGroupName()); Assertions.assertEquals(sqlServerName1, dnsAlias.sqlServerName()); dnsAlias = sqlServerManager.sqlServers().dnsAliases().getBySqlServer(rgName, sqlServerName1, sqlServerName); Assertions.assertNotNull(dnsAlias); Assertions.assertEquals(rgName, dnsAlias.resourceGroupName()); Assertions.assertEquals(sqlServerName1, dnsAlias.sqlServerName()); Assertions.assertEquals(1, sqlServer1.databases().list().size()); SqlServer sqlServer2 = sqlServerManager .sqlServers() .define(sqlServerName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .create(); Assertions.assertNotNull(sqlServer2); sqlServer2.dnsAliases().acquire(sqlServerName, sqlServer1.id()); ResourceManagerUtils.sleep(Duration.ofMinutes(3)); dnsAlias = sqlServer2.dnsAliases().get(sqlServerName); Assertions.assertNotNull(dnsAlias); Assertions.assertEquals(rgName, dnsAlias.resourceGroupName()); Assertions.assertEquals(sqlServerName2, dnsAlias.sqlServerName()); dnsAlias.delete(); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName1); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName2); } @Test public void canGetSqlServerCapabilitiesAndCreateIdentity() throws Exception { String sqlServerAdminName = "sqladmin"; String sqlServerAdminPassword = password(); String databaseName = "db-from-sample"; RegionCapabilities regionCapabilities = sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST); Assertions.assertNotNull(regionCapabilities); Assertions.assertNotNull(regionCapabilities.supportedCapabilitiesByServerVersion().get("12.0")); Assertions .assertTrue( regionCapabilities.supportedCapabilitiesByServerVersion().get("12.0").supportedEditions().size() > 0); Assertions .assertTrue( regionCapabilities .supportedCapabilitiesByServerVersion() .get("12.0") .supportedElasticPoolEditions() .size() > 0); SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .withSystemAssignedManagedServiceIdentity() .defineDatabase(databaseName) .fromSample(SampleName.ADVENTURE_WORKS_LT) .withBasicEdition() .attach() .create(); SqlDatabase dbFromSample = sqlServer.databases().get(databaseName); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); Assertions.assertTrue(sqlServer.isManagedServiceIdentityEnabled()); Assertions.assertEquals(sqlServerManager.tenantId(), sqlServer.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertNotNull(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()); sqlServer.update().withSystemAssignedManagedServiceIdentity().apply(); Assertions.assertTrue(sqlServer.isManagedServiceIdentityEnabled()); Assertions.assertEquals(sqlServerManager.tenantId(), sqlServer.systemAssignedManagedServiceIdentityTenantId()); Assertions.assertNotNull(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()); dbFromSample.delete(); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName); } @Test @DoNotRecord(skipInPlayback = true) public void canCRUDSqlServerWithImportDatabase() throws Exception { String sqlServerAdminName = "sqladmin"; String sqlServerAdminPassword = password(); String id = generateRandomUuid(); String storageName = generateRandomResourceName(sqlServerName, 22); SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(sqlServerAdminPassword) .withActiveDirectoryAdministrator("DSEng", id) .create(); SqlDatabase dbFromSample = sqlServer .databases() .define("db-from-sample") .fromSample(SampleName.ADVENTURE_WORKS_LT) .withBasicEdition() .withTag("tag1", "value1") .create(); Assertions.assertNotNull(dbFromSample); Assertions.assertEquals(DatabaseEdition.BASIC, dbFromSample.edition()); SqlDatabaseImportExportResponse exportedDB; StorageAccount storageAccount = null; try { storageAccount = storageManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); } catch (ManagementException e) { Assertions.assertEquals(404, e.getResponse().getStatusCode()); } if (storageAccount == null) { Creatable<StorageAccount> storageAccountCreatable = storageManager .storageAccounts() .define(storageName) .withRegion(sqlServer.regionName()) .withExistingResourceGroup(sqlServer.resourceGroupName()); exportedDB = dbFromSample .exportTo(storageAccountCreatable, "from-sample", "dbfromsample.bacpac") .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) .execute(); storageAccount = storageManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); } else { exportedDB = dbFromSample .exportTo(storageAccount, "from-sample", "dbfromsample.bacpac") .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) .execute(); } SqlDatabase dbFromImport = sqlServer .databases() .define("db-from-import") .defineElasticPool("ep1") .withBasicPool() .attach() .importFrom(storageAccount, "from-sample", "dbfromsample.bacpac") .withSqlAdministratorLoginAndPassword(sqlServerAdminName, sqlServerAdminPassword) .withTag("tag2", "value2") .create(); Assertions.assertNotNull(dbFromImport); Assertions.assertEquals("ep1", dbFromImport.elasticPoolName()); dbFromImport.delete(); dbFromSample.delete(); sqlServer.elasticPools().delete("ep1"); sqlServerManager.sqlServers().deleteByResourceGroup(rgName, sqlServerName); } @Test public void canCRUDSqlServerWithFirewallRule() throws Exception { String sqlServerAdminName = "sqladmin"; String id = generateRandomUuid(); if (!isPlaybackMode()) { id = clientIdFromFile(); } SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin(sqlServerAdminName) .withAdministratorPassword(password()) .withActiveDirectoryAdministrator("DSEng", id) .withoutAccessFromAzureServices() .defineFirewallRule("somefirewallrule1") .withIpAddress("0.0.0.1") .attach() .withTag("tag1", "value1") .create(); Assertions.assertEquals(sqlServerAdminName, sqlServer.administratorLogin()); Assertions.assertEquals("v12.0", sqlServer.kind()); Assertions.assertEquals("12.0", sqlServer.version()); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); Assertions.assertEquals(sqlServerAdminName, sqlServer.administratorLogin()); Assertions.assertEquals("v12.0", sqlServer.kind()); Assertions.assertEquals("12.0", sqlServer.version()); SqlActiveDirectoryAdministrator sqlADAdmin = sqlServer.getActiveDirectoryAdministrator(); Assertions.assertNotNull(sqlADAdmin); Assertions.assertEquals("DSEng", sqlADAdmin.signInName()); Assertions.assertNotNull(sqlADAdmin.id()); Assertions.assertEquals(AdministratorType.ACTIVE_DIRECTORY, sqlADAdmin.administratorType()); sqlADAdmin = sqlServer.setActiveDirectoryAdministrator("DSEngAll", id); Assertions.assertNotNull(sqlADAdmin); Assertions.assertEquals("DSEngAll", sqlADAdmin.signInName()); Assertions.assertNotNull(sqlADAdmin.id()); Assertions.assertEquals(AdministratorType.ACTIVE_DIRECTORY, sqlADAdmin.administratorType()); sqlServer.removeActiveDirectoryAdministrator(); final SqlServer finalSqlServer = sqlServer; validateResourceNotFound(() -> finalSqlServer.getActiveDirectoryAdministrator()); SqlFirewallRule firewallRule = sqlServerManager.sqlServers().firewallRules().getBySqlServer(rgName, sqlServerName, "somefirewallrule1"); Assertions.assertEquals("0.0.0.1", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.1", firewallRule.endIpAddress()); validateResourceNotFound( () -> sqlServerManager .sqlServers() .firewallRules() .getBySqlServer(rgName, sqlServerName, "AllowAllWindowsAzureIps")); sqlServer.enableAccessFromAzureServices(); firewallRule = sqlServerManager .sqlServers() .firewallRules() .getBySqlServer(rgName, sqlServerName, "AllowAllWindowsAzureIps"); Assertions.assertEquals("0.0.0.0", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.0", firewallRule.endIpAddress()); sqlServer.update().defineFirewallRule("newFirewallRule1") .withIpAddress("0.0.0.2") .attach() .apply(); sqlServer.firewallRules().delete("newFirewallRule2"); final SqlServer finalSqlServer1 = sqlServer; validateResourceNotFound(() -> finalSqlServer1.firewallRules().get("newFirewallRule2")); firewallRule = sqlServerManager .sqlServers() .firewallRules() .define("newFirewallRule2") .withExistingSqlServer(rgName, sqlServerName) .withIpAddress("0.0.0.3") .create(); Assertions.assertEquals("0.0.0.3", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.3", firewallRule.endIpAddress()); firewallRule = firewallRule.update().withStartIpAddress("0.0.0.1").apply(); Assertions.assertEquals("0.0.0.1", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.3", firewallRule.endIpAddress()); sqlServer.firewallRules().delete("somefirewallrule1"); validateResourceNotFound( () -> sqlServerManager .sqlServers() .firewallRules() .getBySqlServer(rgName, sqlServerName, "somefirewallrule1")); firewallRule = sqlServer.firewallRules().define("somefirewallrule2").withIpAddress("0.0.0.4").create(); Assertions.assertEquals("0.0.0.4", firewallRule.startIpAddress()); Assertions.assertEquals("0.0.0.4", firewallRule.endIpAddress()); firewallRule.delete(); } @Test public void canCRUDSqlServer() throws Exception { CheckNameAvailabilityResult checkNameResult = sqlServerManager.sqlServers().checkNameAvailability(sqlServerName); Assertions.assertTrue(checkNameResult.isAvailable()); SqlServer sqlServer = createSqlServer(); validateSqlServer(sqlServer); checkNameResult = sqlServerManager.sqlServers().checkNameAvailability(sqlServerName); Assertions.assertFalse(checkNameResult.isAvailable()); Assertions .assertEquals( CheckNameAvailabilityReason.ALREADY_EXISTS.toString(), checkNameResult.unavailabilityReason()); sqlServer.update().withAdministratorPassword("P@ssword~2").apply(); PagedIterable<SqlServer> sqlServers = sqlServerManager.sqlServers().listByResourceGroup(rgName); boolean found = false; for (SqlServer server : sqlServers) { if (server.name().equals(sqlServerName)) { found = true; } } Assertions.assertTrue(found); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); Assertions.assertNotNull(sqlServer); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test public void canUseCoolShortcutsForResourceCreation() throws Exception { String database2Name = "database2"; String database1InEPName = "database1InEP"; String database2InEPName = "database2InEP"; String elasticPool2Name = "elasticPool2"; String elasticPool3Name = "elasticPool3"; String elasticPool1Name = SQL_ELASTIC_POOL_NAME; SqlServer sqlServer = sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin("userName") .withAdministratorPassword("Password~1") .withoutAccessFromAzureServices() .defineDatabase(SQL_DATABASE_NAME).attach() .defineDatabase(database2Name).attach() .defineElasticPool(elasticPool1Name).withStandardPool().attach() .defineElasticPool(elasticPool2Name).withPremiumPool().attach() .defineElasticPool(elasticPool3Name).withStandardPool().attach() .defineDatabase(database1InEPName).withExistingElasticPool(elasticPool2Name).attach() .defineDatabase(database2InEPName).withExistingElasticPool(elasticPool2Name).attach() .defineFirewallRule(SQL_FIREWALLRULE_NAME).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddress(START_IPADDRESS).attach() .create(); validateMultiCreation( database2Name, database1InEPName, database2InEPName, elasticPool1Name, elasticPool2Name, elasticPool3Name, sqlServer, false); elasticPool1Name = SQL_ELASTIC_POOL_NAME + " U"; database2Name = "database2U"; database1InEPName = "database1InEPU"; database2InEPName = "database2InEPU"; elasticPool2Name = "elasticPool2U"; elasticPool3Name = "elasticPool3U"; sqlServer = sqlServer .update() .defineDatabase(SQL_DATABASE_NAME).attach() .defineDatabase(database2Name).attach() .defineElasticPool(elasticPool1Name).withStandardPool().attach() .defineElasticPool(elasticPool2Name).withPremiumPool().attach() .defineElasticPool(elasticPool3Name).withStandardPool().attach() .defineDatabase(database1InEPName).withExistingElasticPool(elasticPool2Name).attach() .defineDatabase(database2InEPName).withExistingElasticPool(elasticPool2Name).attach() .defineFirewallRule(SQL_FIREWALLRULE_NAME).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddressRange(START_IPADDRESS, END_IPADDRESS).attach() .defineFirewallRule(generateRandomResourceName("firewall_", 15)).withIpAddress(START_IPADDRESS).attach() .withTag("tag2", "value2") .apply(); validateMultiCreation( database2Name, database1InEPName, database2InEPName, elasticPool1Name, elasticPool2Name, elasticPool3Name, sqlServer, true); sqlServer.refresh(); Assertions.assertEquals(sqlServer.elasticPools().list().size(), 0); PagedIterable<SqlServer> sqlServers = sqlServerManager.sqlServers().listByResourceGroup(rgName); boolean found = false; for (SqlServer server : sqlServers) { if (server.name().equals(sqlServerName)) { found = true; } } Assertions.assertTrue(found); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); Assertions.assertNotNull(sqlServer); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test @Test public void canManageReplicationLinks() throws Exception { String anotherSqlServerName = sqlServerName + "another"; SqlServer sqlServer1 = createSqlServer(); SqlServer sqlServer2 = createSqlServer(anotherSqlServerName); Mono<SqlDatabase> resourceStream = sqlServer1 .databases() .define(SQL_DATABASE_NAME) .withCollation(COLLATION) .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) .createAsync(); SqlDatabase databaseInServer1 = resourceStream.block(); validateSqlDatabase(databaseInServer1, SQL_DATABASE_NAME); SqlDatabase databaseInServer2 = sqlServer2 .databases() .define(SQL_DATABASE_NAME) .withSourceDatabase(databaseInServer1.id()) .withMode(CreateMode.ONLINE_SECONDARY) .create(); ResourceManagerUtils.sleep(Duration.ofSeconds(2)); List<ReplicationLink> replicationLinksInDb1 = new ArrayList<>(databaseInServer1.listReplicationLinks().values()); Assertions.assertEquals(replicationLinksInDb1.size(), 1); Assertions.assertEquals(replicationLinksInDb1.get(0).partnerDatabase(), databaseInServer2.name()); Assertions.assertEquals(replicationLinksInDb1.get(0).partnerServer(), databaseInServer2.sqlServerName()); List<ReplicationLink> replicationLinksInDb2 = new ArrayList<>(databaseInServer2.listReplicationLinks().values()); Assertions.assertEquals(replicationLinksInDb2.size(), 1); Assertions.assertEquals(replicationLinksInDb2.get(0).partnerDatabase(), databaseInServer1.name()); Assertions.assertEquals(replicationLinksInDb2.get(0).partnerServer(), databaseInServer1.sqlServerName()); Assertions.assertNotNull(replicationLinksInDb1.get(0).refresh()); replicationLinksInDb2.get(0).failover(); replicationLinksInDb2.get(0).refresh(); ResourceManagerUtils.sleep(Duration.ofSeconds(30)); replicationLinksInDb1.get(0).forceFailoverAllowDataLoss(); replicationLinksInDb1.get(0).refresh(); ResourceManagerUtils.sleep(Duration.ofSeconds(30)); replicationLinksInDb2.get(0).delete(); Assertions.assertEquals(databaseInServer2.listReplicationLinks().size(), 0); sqlServer1.databases().delete(databaseInServer1.name()); sqlServer2.databases().delete(databaseInServer2.name()); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer2.resourceGroupName(), sqlServer2.name()); validateSqlServerNotFound(sqlServer2); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer1.resourceGroupName(), sqlServer1.name()); validateSqlServerNotFound(sqlServer1); } @Test public void canDoOperationsOnDataWarehouse() throws Exception { SqlServer sqlServer = createSqlServer(); validateSqlServer(sqlServer); Mono<SqlDatabase> resourceStream = sqlServer .databases() .define(SQL_DATABASE_NAME) .withCollation(COLLATION) .withSku(DatabaseSku.DATAWAREHOUSE_DW1000C) .createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); Assertions.assertNotNull(sqlDatabase); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertNotNull(sqlDatabase); Assertions.assertTrue(sqlDatabase.isDataWarehouse()); SqlWarehouse dataWarehouse = sqlServer.databases().get(SQL_DATABASE_NAME).asWarehouse(); Assertions.assertNotNull(dataWarehouse); Assertions.assertEquals(dataWarehouse.name(), SQL_DATABASE_NAME); Assertions.assertEquals(DatabaseEdition.DATA_WAREHOUSE, dataWarehouse.edition()); Assertions.assertNotNull(dataWarehouse.listRestorePoints()); dataWarehouse.pauseDataWarehouse(); dataWarehouse.resumeDataWarehouse(); sqlServer.databases().delete(SQL_DATABASE_NAME); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test public void canCRUDSqlDatabaseWithElasticPool() throws Exception { SqlServer sqlServer = createSqlServer(); Creatable<SqlElasticPool> sqlElasticPoolCreatable = sqlServer .elasticPools() .define(SQL_ELASTIC_POOL_NAME) .withStandardPool() .withTag("tag1", "value1"); Mono<SqlDatabase> resourceStream = sqlServer .databases() .define(SQL_DATABASE_NAME) .withNewElasticPool(sqlElasticPoolCreatable) .withCollation(COLLATION) .createAsync(); SqlDatabase sqlDatabase = resourceStream.block(); validateSqlDatabase(sqlDatabase, SQL_DATABASE_NAME); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); SqlElasticPool elasticPool = sqlServer.elasticPools().get(SQL_ELASTIC_POOL_NAME); validateSqlElasticPool(elasticPool); validateSqlDatabaseWithElasticPool(sqlServer.databases().get(SQL_DATABASE_NAME), SQL_DATABASE_NAME); validateListSqlDatabase(sqlServer.databases().list()); sqlDatabase .update() .withoutElasticPool() .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) .apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertNull(sqlDatabase.elasticPoolName()); sqlDatabase.update().withPremiumEdition(SqlDatabasePremiumServiceObjective.P1).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertEquals(sqlDatabase.edition(), DatabaseEdition.PREMIUM); Assertions.assertEquals(sqlDatabase.currentServiceObjectiveName(), ServiceObjectiveName.P1.toString()); sqlDatabase.update().withPremiumEdition(SqlDatabasePremiumServiceObjective.P2).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertEquals(sqlDatabase.currentServiceObjectiveName(), ServiceObjectiveName.P2.toString()); Assertions.assertEquals(sqlDatabase.requestedServiceObjectiveName(), ServiceObjectiveName.P2.toString()); sqlDatabase.update().withMaxSizeBytes(268435456000L).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertEquals(sqlDatabase.maxSizeBytes(), 268435456000L); sqlDatabase.update().withExistingElasticPool(SQL_ELASTIC_POOL_NAME).apply(); sqlDatabase = sqlServer.databases().get(SQL_DATABASE_NAME); Assertions.assertEquals(sqlDatabase.elasticPoolName(), SQL_ELASTIC_POOL_NAME); Assertions.assertNotNull(elasticPool.listActivities()); List<SqlDatabase> databasesInElasticPool = elasticPool.listDatabases(); Assertions.assertNotNull(databasesInElasticPool); Assertions.assertEquals(databasesInElasticPool.size(), 1); SqlDatabase databaseInElasticPool = elasticPool.getDatabase(SQL_DATABASE_NAME); validateSqlDatabase(databaseInElasticPool, SQL_DATABASE_NAME); databaseInElasticPool.refresh(); validateResourceNotFound(() -> elasticPool.getDatabase("does_not_exist")); sqlServer.databases().delete(SQL_DATABASE_NAME); validateSqlDatabaseNotFound(SQL_DATABASE_NAME); SqlElasticPool sqlElasticPool = sqlServer.elasticPools().get(SQL_ELASTIC_POOL_NAME); resourceStream = sqlServer .databases() .define("newDatabase") .withExistingElasticPool(sqlElasticPool) .withCollation(COLLATION) .createAsync(); sqlDatabase = resourceStream.block(); sqlServer.databases().delete(sqlDatabase.name()); validateSqlDatabaseNotFound("newDatabase"); sqlServer.elasticPools().delete(SQL_ELASTIC_POOL_NAME); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test public void canCRUDSqlElasticPool() throws Exception { SqlServer sqlServer = createSqlServer(); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); Mono<SqlElasticPool> resourceStream = sqlServer .elasticPools() .define(SQL_ELASTIC_POOL_NAME) .withStandardPool() .withTag("tag1", "value1") .createAsync(); SqlElasticPool sqlElasticPool = resourceStream.block(); validateSqlElasticPool(sqlElasticPool); Assertions.assertEquals(sqlElasticPool.listDatabases().size(), 0); sqlElasticPool = sqlElasticPool .update() .withReservedDtu(SqlElasticPoolBasicEDTUs.eDTU_100) .withDatabaseMaxCapacity(20) .withDatabaseMinCapacity(10) .withStorageCapacity(102400 * 1024 * 1024L) .withNewDatabase(SQL_DATABASE_NAME) .withTag("tag2", "value2") .apply(); validateSqlElasticPool(sqlElasticPool); Assertions.assertEquals(sqlElasticPool.listDatabases().size(), 1); Assertions.assertNotNull(sqlElasticPool.getDatabase(SQL_DATABASE_NAME)); validateSqlElasticPool(sqlServer.elasticPools().get(SQL_ELASTIC_POOL_NAME)); validateListSqlElasticPool(sqlServer.elasticPools().list()); sqlServer.databases().delete(SQL_DATABASE_NAME); sqlServer.elasticPools().delete(SQL_ELASTIC_POOL_NAME); validateSqlElasticPoolNotFound(sqlServer, SQL_ELASTIC_POOL_NAME); resourceStream = sqlServer.elasticPools().define("newElasticPool").withStandardPool().createAsync(); sqlElasticPool = resourceStream.block(); sqlServer.elasticPools().delete(sqlElasticPool.name()); validateSqlElasticPoolNotFound(sqlServer, "newElasticPool"); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } @Test public void canCRUDSqlFirewallRule() throws Exception { SqlServer sqlServer = createSqlServer(); sqlServer = sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName); validateSqlServer(sqlServer); Mono<SqlFirewallRule> resourceStream = sqlServer .firewallRules() .define(SQL_FIREWALLRULE_NAME) .withIpAddressRange(START_IPADDRESS, END_IPADDRESS) .createAsync(); SqlFirewallRule sqlFirewallRule = resourceStream.block(); validateSqlFirewallRule(sqlFirewallRule, SQL_FIREWALLRULE_NAME); validateSqlFirewallRule(sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME), SQL_FIREWALLRULE_NAME); String secondFirewallRuleName = "secondFireWallRule"; SqlFirewallRule secondFirewallRule = sqlServer.firewallRules().define(secondFirewallRuleName).withIpAddress(START_IPADDRESS).create(); Assertions.assertNotNull(secondFirewallRule); secondFirewallRule = sqlServer.firewallRules().get(secondFirewallRuleName); Assertions.assertNotNull(secondFirewallRule); Assertions.assertEquals(START_IPADDRESS, secondFirewallRule.endIpAddress()); secondFirewallRule = secondFirewallRule.update().withEndIpAddress(END_IPADDRESS).apply(); validateSqlFirewallRule(secondFirewallRule, secondFirewallRuleName); sqlServer.firewallRules().delete(secondFirewallRuleName); final SqlServer finalSqlServer = sqlServer; validateResourceNotFound(() -> finalSqlServer.firewallRules().get(secondFirewallRuleName)); sqlFirewallRule = sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME); validateSqlFirewallRule(sqlFirewallRule, SQL_FIREWALLRULE_NAME); sqlFirewallRule.update().withEndIpAddress(START_IPADDRESS).apply(); sqlFirewallRule = sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME); Assertions.assertEquals(sqlFirewallRule.endIpAddress(), START_IPADDRESS); validateListSqlFirewallRule(sqlServer.firewallRules().list()); sqlServer.firewallRules().delete(sqlFirewallRule.name()); validateSqlFirewallRuleNotFound(); sqlServerManager.sqlServers().deleteByResourceGroup(sqlServer.resourceGroupName(), sqlServer.name()); validateSqlServerNotFound(sqlServer); } private void validateMultiCreation( String database2Name, String database1InEPName, String database2InEPName, String elasticPool1Name, String elasticPool2Name, String elasticPool3Name, SqlServer sqlServer, boolean deleteUsingUpdate) { validateSqlServer(sqlServer); validateSqlServer(sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName)); validateSqlDatabase(sqlServer.databases().get(SQL_DATABASE_NAME), SQL_DATABASE_NAME); validateSqlFirewallRule(sqlServer.firewallRules().get(SQL_FIREWALLRULE_NAME), SQL_FIREWALLRULE_NAME); List<SqlFirewallRule> firewalls = sqlServer.firewallRules().list(); Assertions.assertEquals(3, firewalls.size()); int startIPAddress = 0; int endIPAddress = 0; for (SqlFirewallRule firewall : firewalls) { if (!firewall.name().equalsIgnoreCase(SQL_FIREWALLRULE_NAME)) { Assertions.assertEquals(firewall.startIpAddress(), START_IPADDRESS); if (firewall.endIpAddress().equalsIgnoreCase(START_IPADDRESS)) { startIPAddress++; } else if (firewall.endIpAddress().equalsIgnoreCase(END_IPADDRESS)) { endIPAddress++; } } } Assertions.assertEquals(startIPAddress, 1); Assertions.assertEquals(endIPAddress, 1); Assertions.assertNotNull(sqlServer.databases().get(database2Name)); Assertions.assertNotNull(sqlServer.databases().get(database1InEPName)); Assertions.assertNotNull(sqlServer.databases().get(database2InEPName)); SqlElasticPool ep1 = sqlServer.elasticPools().get(elasticPool1Name); validateSqlElasticPool(ep1, elasticPool1Name); SqlElasticPool ep2 = sqlServer.elasticPools().get(elasticPool2Name); Assertions.assertNotNull(ep2); Assertions.assertEquals(ElasticPoolEdition.PREMIUM, ep2.edition()); Assertions.assertEquals(ep2.listDatabases().size(), 2); Assertions.assertNotNull(ep2.getDatabase(database1InEPName)); Assertions.assertNotNull(ep2.getDatabase(database2InEPName)); SqlElasticPool ep3 = sqlServer.elasticPools().get(elasticPool3Name); Assertions.assertNotNull(ep3); Assertions.assertEquals(ElasticPoolEdition.STANDARD, ep3.edition()); if (!deleteUsingUpdate) { sqlServer.databases().delete(database2Name); sqlServer.databases().delete(database1InEPName); sqlServer.databases().delete(database2InEPName); sqlServer.databases().delete(SQL_DATABASE_NAME); Assertions.assertEquals(ep1.listDatabases().size(), 0); Assertions.assertEquals(ep2.listDatabases().size(), 0); Assertions.assertEquals(ep3.listDatabases().size(), 0); sqlServer.elasticPools().delete(elasticPool1Name); sqlServer.elasticPools().delete(elasticPool2Name); sqlServer.elasticPools().delete(elasticPool3Name); firewalls = sqlServer.firewallRules().list(); for (SqlFirewallRule firewallRule : firewalls) { firewallRule.delete(); } } else { sqlServer .update() .withoutDatabase(database2Name) .withoutElasticPool(elasticPool1Name) .withoutElasticPool(elasticPool2Name) .withoutElasticPool(elasticPool3Name) .withoutDatabase(database1InEPName) .withoutDatabase(SQL_DATABASE_NAME) .withoutDatabase(database2InEPName) .withoutFirewallRule(SQL_FIREWALLRULE_NAME) .apply(); Assertions.assertEquals(sqlServer.elasticPools().list().size(), 0); firewalls = sqlServer.firewallRules().list(); Assertions.assertEquals(firewalls.size(), 2); for (SqlFirewallRule firewallRule : firewalls) { firewallRule.delete(); } } Assertions.assertEquals(sqlServer.elasticPools().list().size(), 0); Assertions.assertEquals(sqlServer.databases().list().size(), 1); } private void validateSqlFirewallRuleNotFound() { validateResourceNotFound( () -> sqlServerManager .sqlServers() .getByResourceGroup(rgName, sqlServerName) .firewallRules() .get(SQL_FIREWALLRULE_NAME)); } private void validateSqlElasticPoolNotFound(SqlServer sqlServer, String elasticPoolName) { validateResourceNotFound(() -> sqlServer.elasticPools().get(elasticPoolName)); } private void validateSqlDatabaseNotFound(String newDatabase) { validateResourceNotFound( () -> sqlServerManager.sqlServers().getByResourceGroup(rgName, sqlServerName).databases().get(newDatabase)); } private void validateSqlServerNotFound(SqlServer sqlServer) { validateResourceNotFound(() -> sqlServerManager.sqlServers().getById(sqlServer.id())); } private void validateResourceNotFound(Supplier<Object> fetchResource) { try { Object result = fetchResource.get(); Assertions.assertNull(result); } catch (ManagementException e) { Assertions.assertEquals(404, e.getResponse().getStatusCode()); } } private SqlServer createSqlServer() { return createSqlServer(sqlServerName); } private SqlServer createSqlServer(String sqlServerName) { return sqlServerManager .sqlServers() .define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin("userName") .withAdministratorPassword("P@ssword~1") .create(); } private static void validateListSqlFirewallRule(List<SqlFirewallRule> sqlFirewallRules) { boolean found = false; for (SqlFirewallRule firewallRule : sqlFirewallRules) { if (firewallRule.name().equals(SQL_FIREWALLRULE_NAME)) { found = true; } } Assertions.assertTrue(found); } private void validateSqlFirewallRule(SqlFirewallRule sqlFirewallRule, String firewallName) { Assertions.assertNotNull(sqlFirewallRule); Assertions.assertEquals(firewallName, sqlFirewallRule.name()); Assertions.assertEquals(sqlServerName, sqlFirewallRule.sqlServerName()); Assertions.assertEquals(START_IPADDRESS, sqlFirewallRule.startIpAddress()); Assertions.assertEquals(END_IPADDRESS, sqlFirewallRule.endIpAddress()); Assertions.assertEquals(rgName, sqlFirewallRule.resourceGroupName()); Assertions.assertEquals(sqlServerName, sqlFirewallRule.sqlServerName()); Assertions.assertEquals(Region.US_EAST, sqlFirewallRule.region()); } private static void validateListSqlElasticPool(List<SqlElasticPool> sqlElasticPools) { boolean found = false; for (SqlElasticPool elasticPool : sqlElasticPools) { if (elasticPool.name().equals(SQL_ELASTIC_POOL_NAME)) { found = true; } } Assertions.assertTrue(found); } private void validateSqlElasticPool(SqlElasticPool sqlElasticPool) { validateSqlElasticPool(sqlElasticPool, SQL_ELASTIC_POOL_NAME); } private void validateSqlElasticPool(SqlElasticPool sqlElasticPool, String elasticPoolName) { Assertions.assertNotNull(sqlElasticPool); Assertions.assertEquals(rgName, sqlElasticPool.resourceGroupName()); Assertions.assertEquals(elasticPoolName, sqlElasticPool.name()); Assertions.assertEquals(sqlServerName, sqlElasticPool.sqlServerName()); Assertions.assertEquals(ElasticPoolEdition.STANDARD, sqlElasticPool.edition()); Assertions.assertNotNull(sqlElasticPool.creationDate()); Assertions.assertNotEquals(0, sqlElasticPool.databaseDtuMax()); Assertions.assertNotEquals(0, sqlElasticPool.dtu()); } private static void validateListSqlDatabase(List<SqlDatabase> sqlDatabases) { boolean found = false; for (SqlDatabase database : sqlDatabases) { if (database.name().equals(SQL_DATABASE_NAME)) { found = true; } } Assertions.assertTrue(found); } private void validateSqlServer(SqlServer sqlServer) { Assertions.assertNotNull(sqlServer); Assertions.assertEquals(rgName, sqlServer.resourceGroupName()); Assertions.assertNotNull(sqlServer.fullyQualifiedDomainName()); Assertions.assertEquals("userName", sqlServer.administratorLogin()); } private void validateSqlDatabase(SqlDatabase sqlDatabase, String databaseName) { Assertions.assertNotNull(sqlDatabase); Assertions.assertEquals(sqlDatabase.name(), databaseName); Assertions.assertEquals(sqlServerName, sqlDatabase.sqlServerName()); Assertions.assertEquals(sqlDatabase.collation(), COLLATION); Assertions.assertEquals(DatabaseEdition.STANDARD, sqlDatabase.edition()); } private void validateSqlDatabaseWithElasticPool(SqlDatabase sqlDatabase, String databaseName) { validateSqlDatabase(sqlDatabase, databaseName); Assertions.assertEquals(SQL_ELASTIC_POOL_NAME, sqlDatabase.elasticPoolName()); } @Test public void testRandomSku() { List<DatabaseSku> databaseSkus = DatabaseSku.getAll().stream().filter(sku -> !"M".equals(sku.toSku().family())).collect(Collectors.toCollection(LinkedList::new)); Collections.shuffle(databaseSkus); List<ElasticPoolSku> elasticPoolSkus = ElasticPoolSku.getAll().stream().filter(sku -> !"M".equals(sku.toSku().family())).collect(Collectors.toCollection(LinkedList::new)); Collections.shuffle(elasticPoolSkus); sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST).supportedCapabilitiesByServerVersion() .forEach((x, serverVersionCapability) -> { serverVersionCapability.supportedEditions().forEach(edition -> { edition.supportedServiceLevelObjectives().forEach(serviceObjective -> { if (serviceObjective.status() != CapabilityStatus.AVAILABLE && serviceObjective.status() != CapabilityStatus.DEFAULT || "M".equals(serviceObjective.sku().family())) { databaseSkus.remove(DatabaseSku.fromSku(serviceObjective.sku())); } }); }); serverVersionCapability.supportedElasticPoolEditions().forEach(edition -> { edition.supportedElasticPoolPerformanceLevels().forEach(performance -> { if (performance.status() != CapabilityStatus.AVAILABLE && performance.status() != CapabilityStatus.DEFAULT || "M".equals(performance.sku().family())) { elasticPoolSkus.remove(ElasticPoolSku.fromSku(performance.sku())); } }); }); }); SqlServer sqlServer = sqlServerManager.sqlServers().define(sqlServerName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .withAdministratorLogin("userName") .withAdministratorPassword(password()) .create(); Flux.merge( Flux.range(0, 3) .flatMap(i -> sqlServer.databases().define("database" + i).withSku(databaseSkus.get(i)).createAsync().cast(Indexable.class)), Flux.range(0, 3) .flatMap(i -> sqlServer.elasticPools().define("elasticPool" + i).withSku(elasticPoolSkus.get(i)).createAsync().cast(Indexable.class)) ) .blockLast(); } @Test @Disabled("Only run for updating sku") public void generateSku() throws IOException { StringBuilder databaseSkuBuilder = new StringBuilder(); StringBuilder elasticPoolSkuBuilder = new StringBuilder(); sqlServerManager.sqlServers().getCapabilitiesByRegion(Region.US_EAST).supportedCapabilitiesByServerVersion() .forEach((x, serverVersionCapability) -> { serverVersionCapability.supportedEditions().forEach(edition -> { if (edition.name().equalsIgnoreCase("System")) { return; } edition.supportedServiceLevelObjectives().forEach(serviceObjective -> { addStaticSkuDefinition(databaseSkuBuilder, edition.name(), serviceObjective.name(), serviceObjective.sku(), "DatabaseSku"); }); }); serverVersionCapability.supportedElasticPoolEditions().forEach(edition -> { if (edition.name().equalsIgnoreCase("System")) { return; } edition.supportedElasticPoolPerformanceLevels().forEach(performance -> { String detailName = String.format("%s_%d", performance.sku().name(), performance.sku().capacity()); addStaticSkuDefinition(elasticPoolSkuBuilder, edition.name(), detailName, performance.sku(), "ElasticPoolSku"); }); }); }); String databaseSku = new String(readAllBytes(getClass().getResourceAsStream("/DatabaseSku.java")), StandardCharsets.UTF_8); databaseSku = databaseSku.replace("<Generated>", databaseSkuBuilder.toString()); Files.write(new File("src/main/java/com/azure/resourcemanager/sql/models/DatabaseSku.java").toPath(), databaseSku.getBytes(StandardCharsets.UTF_8)); String elasticPoolSku = new String(readAllBytes(getClass().getResourceAsStream("/ElasticPoolSku.java")), StandardCharsets.UTF_8); elasticPoolSku = elasticPoolSku.replace("<Generated>", elasticPoolSkuBuilder.toString()); Files.write(new File("src/main/java/com/azure/resourcemanager/sql/models/ElasticPoolSku.java").toPath(), elasticPoolSku.getBytes(StandardCharsets.UTF_8)); sqlServerManager.resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST).create(); } private byte[] readAllBytes(InputStream inputStream) throws IOException { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] data = new byte[4096]; while (true) { int size = inputStream.read(data); if (size > 0) { outputStream.write(data, 0, size); } else { return outputStream.toByteArray(); } } } } private void addStaticSkuDefinition(StringBuilder builder, String edition, String detailName, Sku sku, String className) { builder .append("\n ").append("/** ").append(edition).append(" Edition with ").append(detailName).append(" sku. */") .append("\n ").append("public static final ").append(className).append(" ").append(String.format("%s_%s", edition.toUpperCase(Locale.ROOT), detailName.toUpperCase(Locale.ROOT))).append(" =") .append("\n new ").append(className).append("(") .append(sku.name() == null ? null : "\"" + sku.name() + "\"") .append(", ") .append(sku.tier() == null ? null : "\"" + sku.tier() + "\"") .append(", ") .append(sku.family() == null ? null : "\"" + sku.family() + "\"") .append(", ") .append(sku.capacity()) .append(", ") .append(sku.size() == null ? null : "\"" + sku.size() + "\"") .append(");"); } }
pls refactor according to https://github.com/Azure/azure-sdk-for-net/pull/31627/files#r1000528967
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { return getCommunicationUserIdentifier(identifier); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { return getPhoneNumberIdentifier(identifier, rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { return getMicrosoftTeamsUserIdentifier(identifier, rawId); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { return getCommunicationUserIdentifier(identifier); } if (identifier.getPhoneNumber() != null) { return getPhoneNumberIdentifier(identifier, rawId); } if (identifier.getMicrosoftTeamsUser() != null) { return getMicrosoftTeamsUserIdentifier(identifier, rawId); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
}
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationUserIdentifier getCommunicationUserIdentifier(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationUserIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } private static PhoneNumberIdentifier getPhoneNumberIdentifier(CommunicationIdentifierModel identifier, String rawId) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } private static MicrosoftTeamsUserIdentifier getMicrosoftTeamsUserIdentifier(CommunicationIdentifierModel identifier, String rawId) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
I guess it was changed manually, but we should not manually change the generated code as later code regeneration will override it and your changes will be lost. Instead you can customize the class using [azure-autorest-customization](https://github.com/Azure/autorest.java/blob/main/customization-base/README.md). The same comment for callingserver/implementation/converters/CommunicationIdentifierConverter.java
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
CommunicationIdentifierModelKind kind = identifier.getKind();
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
maybe here we should access directly `identifier.getPhoneNumber().getValue()` as the value is used in both places
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber();
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
in the constructor of the MicrosoftTeamsUserIdentifier the rawId is set, so I guess there is no need to reset it again
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
.setRawId(rawId)
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
in the constructor of the PhoneNumberIdentifier the rawId is set, so here if the rawId will be null it will be reset to null as we are not checking for non-nullability
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId);
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
This file is not auto-generated. Please check comments on the top of the file, it doesn't have 'auto-generated' comment. I've discussed it with Dominik and Minnie: not all files under /implementation are auto-generated, those that don't have a respective comments, are written manually
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
CommunicationIdentifierModelKind kind = identifier.getKind();
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
Thanks! Fixed
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber();
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
As far as I understand, only **user ID** is set in constructor and **raw ID** is generated. The logic with setting a raw ID explicitly to a defined value was already there, I'm not sure we should change it because there is no guarantee that the generated raw id will have the same value as a raw id from `CommunicationIdentifierModel` passed to this method as an argument ``` public MicrosoftTeamsUserIdentifier(String userId, boolean isAnonymous) { this.rawIdSet = false; this.cloudEnvironment = CommunicationCloudEnvironment.PUBLIC; if (CoreUtils.isNullOrEmpty(userId)) { throw new IllegalArgumentException("The initialization parameter [userId] cannot be null or empty."); } else { this.userId = userId; this.isAnonymous = isAnonymous; this.generateRawId(); } } ```
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
.setRawId(rawId)
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
Fixed
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId);
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
Oh, I see, sorry I thought it's part of the generated code
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
CommunicationIdentifierModelKind kind = identifier.getKind();
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
I think the value would be the same as this generating logic is approved solution and covered by tests. @petrsvihlik wdyt about setting it again?
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
.setRawId(rawId)
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
Done
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { return getCommunicationUserIdentifier(identifier); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { return getPhoneNumberIdentifier(identifier, rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { return getMicrosoftTeamsUserIdentifier(identifier, rawId); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { return getCommunicationUserIdentifier(identifier); } if (identifier.getPhoneNumber() != null) { return getPhoneNumberIdentifier(identifier, rawId); } if (identifier.getMicrosoftTeamsUser() != null) { return getMicrosoftTeamsUserIdentifier(identifier, rawId); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
}
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationUserIdentifier getCommunicationUserIdentifier(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationUserIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } private static PhoneNumberIdentifier getPhoneNumberIdentifier(CommunicationIdentifierModel identifier, String rawId) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } private static MicrosoftTeamsUserIdentifier getMicrosoftTeamsUserIdentifier(CommunicationIdentifierModel identifier, String rawId) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
maybe we have to specify an error message as follows to give more info which params should not be null: ```suggestion Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationUserIdentifierModel cannot be null."); ``` the same comment for all occurences of `Objects.requireNonNull` in this method
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber); Objects.requireNonNull(rawId); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber); Objects.requireNonNull(rawId); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
Objects.requireNonNull(identifier.getCommunicationUser().getId());
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
The following lines kind of duplicated, maybe it will be better in terms of maintenance to create separate methods for creation of each identifier: - 42->43 lines are identical to 72->73 - 48->51 & 77->80 - 56->64 & 84->92
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber); Objects.requireNonNull(rawId); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber); Objects.requireNonNull(rawId); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
Objects.requireNonNull(identifier.getCommunicationUser().getId());
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
Currently raw ID is generated based on user ID and cloud environment only. Under some circumstances, rawId from `CommunicationIdentifierModel` could be a totally different value (like `123abc`), which could not be generated. I'm not sure what expected behaviour is, but not setting a rawID explicitly will change the previous logic.
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
.setRawId(rawId)
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
Thanks! That's a good suggestion. Done
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber); Objects.requireNonNull(rawId); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber); Objects.requireNonNull(rawId); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
Objects.requireNonNull(identifier.getCommunicationUser().getId());
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
Thanks! That's a good suggestion. Done
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber); Objects.requireNonNull(rawId); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber); Objects.requireNonNull(rawId); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
Objects.requireNonNull(identifier.getCommunicationUser().getId());
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
This is an exception for PhoneNumbers and MSTeamsUsers. The rawId must be set explicitly to support some legacy identifiers.
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = identifier.getKind(); if (kind != null) { if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); } if (identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId()); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (identifier.getPhoneNumber() != null) { PhoneNumberIdentifierModel phoneNumberModel = identifier.getPhoneNumber(); Objects.requireNonNull(phoneNumberModel.getValue()); return new PhoneNumberIdentifier(phoneNumberModel.getValue()).setRawId(rawId); } if (identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId()); Objects.requireNonNull(teamsUserIdentifierModel.getCloud()); Objects.requireNonNull(rawId); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId); return new UnknownIdentifier(rawId); }
.setRawId(rawId)
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
`CommunicationUserIdentifierModel` doesn't contain a `PhoneNumber`. It should either be `CommunicationIdentifierModel`, or its submodel `PhoneNumberIdentifierModel`.
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationUserIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationUserIdentifierModel cannot be null.");
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
same here
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationUserIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationUserIdentifierModel cannot be null.");
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
```suggestion Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); ```
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationUserIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationUserIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
Objects.requireNonNull(rawId, "'RawID' of the CommunicationUserIdentifierModel cannot be null.");
public static CommunicationIdentifier convert(CommunicationIdentifierModel identifier) { if (identifier == null) { return null; } assertSingleType(identifier); String rawId = identifier.getRawId(); CommunicationIdentifierModelKind kind = (identifier.getKind() != null) ? identifier.getKind() : extractKind(identifier); if (kind == CommunicationIdentifierModelKind.COMMUNICATION_USER && identifier.getCommunicationUser() != null) { Objects.requireNonNull(identifier.getCommunicationUser().getId(), "'ID' of the CommunicationIdentifierModel cannot be null."); return new CommunicationUserIdentifier(identifier.getCommunicationUser().getId()); } if (kind == CommunicationIdentifierModelKind.PHONE_NUMBER && identifier.getPhoneNumber() != null) { String phoneNumber = identifier.getPhoneNumber().getValue(); Objects.requireNonNull(phoneNumber, "'PhoneNumber' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new PhoneNumberIdentifier(phoneNumber).setRawId(rawId); } if (kind == CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER && identifier.getMicrosoftTeamsUser() != null) { MicrosoftTeamsUserIdentifierModel teamsUserIdentifierModel = identifier.getMicrosoftTeamsUser(); Objects.requireNonNull(teamsUserIdentifierModel.getUserId(), "'UserID' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(teamsUserIdentifierModel.getCloud(), "'Cloud' of the CommunicationIdentifierModel cannot be null."); Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new MicrosoftTeamsUserIdentifier(teamsUserIdentifierModel.getUserId(), teamsUserIdentifierModel.isAnonymous()) .setRawId(rawId) .setCloudEnvironment(CommunicationCloudEnvironment .fromString(teamsUserIdentifierModel.getCloud().toString())); } Objects.requireNonNull(rawId, "'RawID' of the CommunicationIdentifierModel cannot be null."); return new UnknownIdentifier(rawId); }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
class CommunicationIdentifierConverter { /** * Maps from {@link CommunicationIdentifierModel} to {@link CommunicationIdentifier}. */ /** * Maps from {@link CommunicationIdentifier} to {@link CommunicationIdentifierModel}. */ public static CommunicationIdentifierModel convert(CommunicationIdentifier identifier) throws IllegalArgumentException { if (identifier == null) { return null; } if (identifier instanceof CommunicationUserIdentifier) { CommunicationUserIdentifier communicationUserIdentifier = (CommunicationUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(communicationUserIdentifier.getRawId()) .setCommunicationUser( new CommunicationUserIdentifierModel().setId(communicationUserIdentifier.getId())); } if (identifier instanceof PhoneNumberIdentifier) { PhoneNumberIdentifier phoneNumberIdentifier = (PhoneNumberIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(phoneNumberIdentifier.getRawId()) .setPhoneNumber(new PhoneNumberIdentifierModel().setValue(phoneNumberIdentifier.getPhoneNumber())); } if (identifier instanceof MicrosoftTeamsUserIdentifier) { MicrosoftTeamsUserIdentifier teamsUserIdentifier = (MicrosoftTeamsUserIdentifier) identifier; return new CommunicationIdentifierModel() .setRawId(teamsUserIdentifier.getRawId()) .setMicrosoftTeamsUser(new MicrosoftTeamsUserIdentifierModel() .setIsAnonymous(teamsUserIdentifier.isAnonymous()) .setUserId(teamsUserIdentifier.getUserId()) .setCloud(CommunicationCloudEnvironmentModel.fromString( teamsUserIdentifier.getCloudEnvironment().toString()))); } if (identifier instanceof UnknownIdentifier) { UnknownIdentifier unknownIdentifier = (UnknownIdentifier) identifier; return new CommunicationIdentifierModel().setRawId(unknownIdentifier.getId()); } throw new IllegalArgumentException(String.format("Unknown identifier class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } } private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; } }
pls provide an error message as well
private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; }
Objects.requireNonNull(identifier);
private static CommunicationIdentifierModelKind extractKind(CommunicationIdentifierModel identifier) { Objects.requireNonNull(identifier, "CommunicationIdentifierModel cannot be null."); if (identifier.getCommunicationUser() != null) { return CommunicationIdentifierModelKind.COMMUNICATION_USER; } if (identifier.getPhoneNumber() != null) { return CommunicationIdentifierModelKind.PHONE_NUMBER; } if (identifier.getMicrosoftTeamsUser() != null) { return CommunicationIdentifierModelKind.MICROSOFT_TEAMS_USER; } return CommunicationIdentifierModelKind.UNKNOWN; }
class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } }
class '%s'", identifier.getClass().getName())); } private static void assertSingleType(CommunicationIdentifierModel identifier) { CommunicationUserIdentifierModel communicationUser = identifier.getCommunicationUser(); PhoneNumberIdentifierModel phoneNumber = identifier.getPhoneNumber(); MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = identifier.getMicrosoftTeamsUser(); ArrayList<String> presentProperties = new ArrayList<>(); if (communicationUser != null) { presentProperties.add(communicationUser.getClass().getName()); } if (phoneNumber != null) { presentProperties.add(phoneNumber.getClass().getName()); } if (microsoftTeamsUser != null) { presentProperties.add(microsoftTeamsUser.getClass().getName()); } if (presentProperties.size() > 1) { throw new IllegalArgumentException( String.format( "Only one of the identifier models in %s should be present.", String.join(", ", presentProperties))); } }
Should AbstractiveSummaryAction() not be empty?
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<String> documents = new ArrayList<>(); documents.add( "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic," + " human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI" + " Cognitive Services, I have been working with a team of amazing scientists and engineers to turn " + "this quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship" + " among three attributes of human cognition: monolingual text (X), audio or visual sensory signals," + " (Y) and multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code" + " as illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear," + " see, and understand humans better. We believe XYZ-code will enable us to fulfill our long-term" + " vision: cross-domain transfer learning, spanning modalities and languages. The goal is to have" + " pretrained models that can jointly learn representations to support a broad range of downstream" + " AI tasks, much in the way humans do today. Over the past five years, we have achieved human" + " performance on benchmarks in conversational speech recognition, machine translation, " + "conversational question answering, machine reading comprehension, and image captioning. These" + " five breakthroughs provided us with strong signals toward our more ambitious aspiration to" + " produce a leap in AI capabilities, achieving multisensory and multilingual learning that " + "is closer in line with how humans learn and understand. I believe the joint XYZ-code is a " + "foundational component of this aspiration, if grounded with external knowledge sources in " + "the downstream AI tasks."); SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> syncPoller = client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setDisplayName("{tasks_display_name}") .setAbstractiveSummaryActions(new AbstractiveSummaryAction()), "en", new AnalyzeActionsOptions()); syncPoller.waitForCompletion(); syncPoller.getFinalResult().forEach(actionsResult -> { System.out.println("Abstractive summarization action results:"); for (AbstractiveSummaryActionResult actionResult : actionsResult.getAbstractiveSummaryResults()) { if (!actionResult.isError()) { for (AbstractiveSummaryResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { System.out.println("\tAbstract summary sentences:"); for (AbstractiveSummary summarySentence : documentResult.getSummaries()) { System.out.printf("\t\t Summary text: %s.%n", summarySentence.getText()); for (SummaryContext summaryContext : summarySentence.getSummaryContexts()) { System.out.printf("\t\t offset: %d, length: %d%n", summaryContext.getOffset(), summaryContext.getLength()); } } } else { System.out.printf("\tCannot get abstract summary. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot get Abstractive Summarization action. Error: %s%n", actionResult.getError().getMessage()); } } }); }
.setAbstractiveSummaryActions(new AbstractiveSummaryAction()),
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<String> documents = new ArrayList<>(); documents.add( "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic," + " human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI" + " Cognitive Services, I have been working with a team of amazing scientists and engineers to turn " + "this quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship" + " among three attributes of human cognition: monolingual text (X), audio or visual sensory signals," + " (Y) and multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code" + " as illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear," + " see, and understand humans better. We believe XYZ-code will enable us to fulfill our long-term" + " vision: cross-domain transfer learning, spanning modalities and languages. The goal is to have" + " pretrained models that can jointly learn representations to support a broad range of downstream" + " AI tasks, much in the way humans do today. Over the past five years, we have achieved human" + " performance on benchmarks in conversational speech recognition, machine translation, " + "conversational question answering, machine reading comprehension, and image captioning. These" + " five breakthroughs provided us with strong signals toward our more ambitious aspiration to" + " produce a leap in AI capabilities, achieving multisensory and multilingual learning that " + "is closer in line with how humans learn and understand. I believe the joint XYZ-code is a " + "foundational component of this aspiration, if grounded with external knowledge sources in " + "the downstream AI tasks."); SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> syncPoller = client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setDisplayName("{tasks_display_name}") .setAbstractiveSummaryActions(new AbstractiveSummaryAction().setMaxSentenceCount(3)), "en", new AnalyzeActionsOptions()); syncPoller.waitForCompletion(); syncPoller.getFinalResult().forEach(actionsResult -> { System.out.println("Abstractive summarization action results:"); for (AbstractiveSummaryActionResult actionResult : actionsResult.getAbstractiveSummaryResults()) { if (!actionResult.isError()) { for (AbstractiveSummaryResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { System.out.println("\tAbstract summary sentences:"); for (AbstractiveSummary summarySentence : documentResult.getSummaries()) { System.out.printf("\t\t Summary text: %s.%n", summarySentence.getText()); for (SummaryContext summaryContext : summarySentence.getSummaryContexts()) { System.out.printf("\t\t offset: %d, length: %d%n", summaryContext.getOffset(), summaryContext.getLength()); } } } else { System.out.printf("\tCannot get abstract summary. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot get Abstractive Summarization action. Error: %s%n", actionResult.getError().getMessage()); } } }); }
class AbstractiveSummarization { /** * Main method to invoke this demo about how to analyze an "Extractive Summarization" action. * * @param args Unused arguments to the program. */ }
class AbstractiveSummarization { /** * Main method to invoke this demo about how to analyze an "Extractive Summarization" action. * * @param args Unused arguments to the program. */ }
Can we have an assertion that without the ResponseDiagnosticsProcessor bean, spring data cosmos can be configured correctly?
void configureWithPopulateQueryMetricsDisabled() { try (MockedStatic<CosmosFactory> mockedStatic = mockStatic(CosmosFactory.class, RETURNS_MOCKS)) { when(cosmosClientBuilder.buildAsyncClient()).thenReturn(cosmosAsyncClient); mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder)) .thenReturn(cosmosAsyncClient); this.contextRunner .withBean(CosmosClientBuilder.class, () -> cosmosClientBuilder) .withBean(CosmosClient.class, () -> mock(CosmosClient.class)) .withPropertyValues( "spring.cloud.azure.cosmos.endpoint=" + ENDPOINT, "spring.cloud.azure.cosmos.database=test-database", "spring.cloud.azure.cosmos.populate-query-metrics=false") .run(context -> assertThat(context).doesNotHaveBean(ResponseDiagnosticsProcessor.class)); } }
}
void configureWithPopulateQueryMetricsDisabled() { this.contextRunner .withPropertyValues( "spring.cloud.azure.cosmos.populate-query-metrics=false") .run(context -> { assertThat(context).doesNotHaveBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).doesNotHaveBean(ResponseDiagnosticsProcessor.class); }); }
class CosmosDataDiagnosticsConfigurationTests { private static final String ENDPOINT = "https: private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( AzureGlobalPropertiesAutoConfiguration.class, AzureCosmosAutoConfiguration.class, CosmosDataAutoConfiguration.class)); CosmosClientBuilder cosmosClientBuilder = mock(CosmosClientBuilder.class); CosmosAsyncClient cosmosAsyncClient = mock(CosmosAsyncClient.class); @Test void configureWithPopulateQueryMetricsEnabled() { try (MockedStatic<CosmosFactory> mockedStatic = mockStatic(CosmosFactory.class, RETURNS_MOCKS)) { when(cosmosClientBuilder.buildAsyncClient()).thenReturn(cosmosAsyncClient); mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder)) .thenReturn(cosmosAsyncClient); this.contextRunner .withBean(CosmosClientBuilder.class, () -> cosmosClientBuilder) .withBean(CosmosClient.class, () -> mock(CosmosClient.class)) .withPropertyValues( "spring.cloud.azure.cosmos.endpoint=" + ENDPOINT, "spring.cloud.azure.cosmos.database=test", "spring.cloud.azure.cosmos.populate-query-metrics=true") .run(context -> assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class)); } } @Test @Test void configureWithUserProvideResponseDiagnosticsProcessor() { this.contextRunner .withConfiguration(AutoConfigurations.of(ResponseDiagnosticsProcessorConfiguration.class)) .run(context -> { ResponseDiagnosticsProcessor processor = (ResponseDiagnosticsProcessor) context.getBean("ResponseDiagnosticsProcessor"); assertTrue(processor instanceof ResponseDiagnosticsProcessorExtend); }); } @Configuration @AutoConfigureBefore(CosmosDataDiagnosticsConfiguration.class) static class ResponseDiagnosticsProcessorConfiguration { @Bean(name = "ResponseDiagnosticsProcessor") public ResponseDiagnosticsProcessor processor() { return new ResponseDiagnosticsProcessorExtend(); } } static class ResponseDiagnosticsProcessorExtend implements ResponseDiagnosticsProcessor { @Override public void processResponseDiagnostics(ResponseDiagnostics responseDiagnostics) { } } }
class CosmosDataDiagnosticsConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(TestAutoconfigurationClass.class)); @Test void configureWithPopulateQueryMetricsEnabled() { this.contextRunner .withPropertyValues( "spring.cloud.azure.cosmos.populate-query-metrics=true") .run(context -> { assertThat(context).hasSingleBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class); }); } @Test @Test void configureWithUserProvideResponseDiagnosticsProcessor() { this.contextRunner .withUserConfiguration(ResponseDiagnosticsProcessorConfiguration.class) .run(context -> { ResponseDiagnosticsProcessor processor = (ResponseDiagnosticsProcessor) context.getBean("ResponseDiagnosticsProcessor"); assertTrue(processor instanceof ResponseDiagnosticsProcessorExtend); }); } @Configuration static class ResponseDiagnosticsProcessorConfiguration { @Bean(name = "ResponseDiagnosticsProcessor") public ResponseDiagnosticsProcessor processor() { return new ResponseDiagnosticsProcessorExtend(); } } static class ResponseDiagnosticsProcessorExtend implements ResponseDiagnosticsProcessor { @Override public void processResponseDiagnostics(ResponseDiagnostics responseDiagnostics) { } } @Configuration @Import(CosmosDataDiagnosticsConfiguration.class) static class TestAutoconfigurationClass { } }
better have an assertion for the `CosmosDataDiagnosticsConfiguration` bean as well.
void configureWithPopulateQueryMetricsEnabled() { try (MockedStatic<CosmosFactory> mockedStatic = mockStatic(CosmosFactory.class, RETURNS_MOCKS)) { when(cosmosClientBuilder.buildAsyncClient()).thenReturn(cosmosAsyncClient); mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder)) .thenReturn(cosmosAsyncClient); this.contextRunner .withBean(CosmosClientBuilder.class, () -> cosmosClientBuilder) .withBean(CosmosClient.class, () -> mock(CosmosClient.class)) .withPropertyValues( "spring.cloud.azure.cosmos.endpoint=" + ENDPOINT, "spring.cloud.azure.cosmos.database=test", "spring.cloud.azure.cosmos.populate-query-metrics=true") .run(context -> assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class)); } }
.run(context -> assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class));
void configureWithPopulateQueryMetricsEnabled() { this.contextRunner .withPropertyValues( "spring.cloud.azure.cosmos.populate-query-metrics=true") .run(context -> { assertThat(context).hasSingleBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class); }); }
class CosmosDataDiagnosticsConfigurationTests { private static final String ENDPOINT = "https: private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( AzureGlobalPropertiesAutoConfiguration.class, AzureCosmosAutoConfiguration.class, CosmosDataAutoConfiguration.class)); CosmosClientBuilder cosmosClientBuilder = mock(CosmosClientBuilder.class); CosmosAsyncClient cosmosAsyncClient = mock(CosmosAsyncClient.class); @Test @Test void configureWithPopulateQueryMetricsDisabled() { try (MockedStatic<CosmosFactory> mockedStatic = mockStatic(CosmosFactory.class, RETURNS_MOCKS)) { when(cosmosClientBuilder.buildAsyncClient()).thenReturn(cosmosAsyncClient); mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder)) .thenReturn(cosmosAsyncClient); this.contextRunner .withBean(CosmosClientBuilder.class, () -> cosmosClientBuilder) .withBean(CosmosClient.class, () -> mock(CosmosClient.class)) .withPropertyValues( "spring.cloud.azure.cosmos.endpoint=" + ENDPOINT, "spring.cloud.azure.cosmos.database=test-database", "spring.cloud.azure.cosmos.populate-query-metrics=false") .run(context -> assertThat(context).doesNotHaveBean(ResponseDiagnosticsProcessor.class)); } } @Test void configureWithUserProvideResponseDiagnosticsProcessor() { this.contextRunner .withConfiguration(AutoConfigurations.of(ResponseDiagnosticsProcessorConfiguration.class)) .run(context -> { ResponseDiagnosticsProcessor processor = (ResponseDiagnosticsProcessor) context.getBean("ResponseDiagnosticsProcessor"); assertTrue(processor instanceof ResponseDiagnosticsProcessorExtend); }); } @Configuration @AutoConfigureBefore(CosmosDataDiagnosticsConfiguration.class) static class ResponseDiagnosticsProcessorConfiguration { @Bean(name = "ResponseDiagnosticsProcessor") public ResponseDiagnosticsProcessor processor() { return new ResponseDiagnosticsProcessorExtend(); } } static class ResponseDiagnosticsProcessorExtend implements ResponseDiagnosticsProcessor { @Override public void processResponseDiagnostics(ResponseDiagnostics responseDiagnostics) { } } }
class CosmosDataDiagnosticsConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(TestAutoconfigurationClass.class)); @Test @Test void configureWithPopulateQueryMetricsDisabled() { this.contextRunner .withPropertyValues( "spring.cloud.azure.cosmos.populate-query-metrics=false") .run(context -> { assertThat(context).doesNotHaveBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).doesNotHaveBean(ResponseDiagnosticsProcessor.class); }); } @Test void configureWithUserProvideResponseDiagnosticsProcessor() { this.contextRunner .withUserConfiguration(ResponseDiagnosticsProcessorConfiguration.class) .run(context -> { ResponseDiagnosticsProcessor processor = (ResponseDiagnosticsProcessor) context.getBean("ResponseDiagnosticsProcessor"); assertTrue(processor instanceof ResponseDiagnosticsProcessorExtend); }); } @Configuration static class ResponseDiagnosticsProcessorConfiguration { @Bean(name = "ResponseDiagnosticsProcessor") public ResponseDiagnosticsProcessor processor() { return new ResponseDiagnosticsProcessorExtend(); } } static class ResponseDiagnosticsProcessorExtend implements ResponseDiagnosticsProcessor { @Override public void processResponseDiagnostics(ResponseDiagnostics responseDiagnostics) { } } @Configuration @Import(CosmosDataDiagnosticsConfiguration.class) static class TestAutoconfigurationClass { } }
withUserConfiguration instead, the ResponseDiagnosticsProcessorConfiguration should not a AutoConfiguration class, it's provided by the user.
void configureWithUserProvideResponseDiagnosticsProcessor() { this.contextRunner .withConfiguration(AutoConfigurations.of(ResponseDiagnosticsProcessorConfiguration.class)) .run(context -> { ResponseDiagnosticsProcessor processor = (ResponseDiagnosticsProcessor) context.getBean("ResponseDiagnosticsProcessor"); assertTrue(processor instanceof ResponseDiagnosticsProcessorExtend); }); }
.withConfiguration(AutoConfigurations.of(ResponseDiagnosticsProcessorConfiguration.class))
void configureWithUserProvideResponseDiagnosticsProcessor() { this.contextRunner .withUserConfiguration(ResponseDiagnosticsProcessorConfiguration.class) .run(context -> { ResponseDiagnosticsProcessor processor = (ResponseDiagnosticsProcessor) context.getBean("ResponseDiagnosticsProcessor"); assertTrue(processor instanceof ResponseDiagnosticsProcessorExtend); }); }
class CosmosDataDiagnosticsConfigurationTests { private static final String ENDPOINT = "https: private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( AzureGlobalPropertiesAutoConfiguration.class, AzureCosmosAutoConfiguration.class, CosmosDataAutoConfiguration.class)); CosmosClientBuilder cosmosClientBuilder = mock(CosmosClientBuilder.class); CosmosAsyncClient cosmosAsyncClient = mock(CosmosAsyncClient.class); @Test void configureWithPopulateQueryMetricsEnabled() { try (MockedStatic<CosmosFactory> mockedStatic = mockStatic(CosmosFactory.class, RETURNS_MOCKS)) { when(cosmosClientBuilder.buildAsyncClient()).thenReturn(cosmosAsyncClient); mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder)) .thenReturn(cosmosAsyncClient); this.contextRunner .withBean(CosmosClientBuilder.class, () -> cosmosClientBuilder) .withBean(CosmosClient.class, () -> mock(CosmosClient.class)) .withPropertyValues( "spring.cloud.azure.cosmos.endpoint=" + ENDPOINT, "spring.cloud.azure.cosmos.database=test", "spring.cloud.azure.cosmos.populate-query-metrics=true") .run(context -> assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class)); } } @Test void configureWithPopulateQueryMetricsDisabled() { try (MockedStatic<CosmosFactory> mockedStatic = mockStatic(CosmosFactory.class, RETURNS_MOCKS)) { when(cosmosClientBuilder.buildAsyncClient()).thenReturn(cosmosAsyncClient); mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder)) .thenReturn(cosmosAsyncClient); this.contextRunner .withBean(CosmosClientBuilder.class, () -> cosmosClientBuilder) .withBean(CosmosClient.class, () -> mock(CosmosClient.class)) .withPropertyValues( "spring.cloud.azure.cosmos.endpoint=" + ENDPOINT, "spring.cloud.azure.cosmos.database=test-database", "spring.cloud.azure.cosmos.populate-query-metrics=false") .run(context -> assertThat(context).doesNotHaveBean(ResponseDiagnosticsProcessor.class)); } } @Test @Configuration @AutoConfigureBefore(CosmosDataDiagnosticsConfiguration.class) static class ResponseDiagnosticsProcessorConfiguration { @Bean(name = "ResponseDiagnosticsProcessor") public ResponseDiagnosticsProcessor processor() { return new ResponseDiagnosticsProcessorExtend(); } } static class ResponseDiagnosticsProcessorExtend implements ResponseDiagnosticsProcessor { @Override public void processResponseDiagnostics(ResponseDiagnostics responseDiagnostics) { } } }
class CosmosDataDiagnosticsConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(TestAutoconfigurationClass.class)); @Test void configureWithPopulateQueryMetricsEnabled() { this.contextRunner .withPropertyValues( "spring.cloud.azure.cosmos.populate-query-metrics=true") .run(context -> { assertThat(context).hasSingleBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class); }); } @Test void configureWithPopulateQueryMetricsDisabled() { this.contextRunner .withPropertyValues( "spring.cloud.azure.cosmos.populate-query-metrics=false") .run(context -> { assertThat(context).doesNotHaveBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).doesNotHaveBean(ResponseDiagnosticsProcessor.class); }); } @Test @Configuration static class ResponseDiagnosticsProcessorConfiguration { @Bean(name = "ResponseDiagnosticsProcessor") public ResponseDiagnosticsProcessor processor() { return new ResponseDiagnosticsProcessorExtend(); } } static class ResponseDiagnosticsProcessorExtend implements ResponseDiagnosticsProcessor { @Override public void processResponseDiagnostics(ResponseDiagnostics responseDiagnostics) { } } @Configuration @Import(CosmosDataDiagnosticsConfiguration.class) static class TestAutoconfigurationClass { } }
I think we don't need to mock cosmos factory?
void configureWithPopulateQueryMetricsEnabled() { try (MockedStatic<CosmosFactory> mockedStatic = mockStatic(CosmosFactory.class, RETURNS_MOCKS)) { when(cosmosClientBuilder.buildAsyncClient()).thenReturn(cosmosAsyncClient); mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder)) .thenReturn(cosmosAsyncClient); this.contextRunner .withBean(CosmosClientBuilder.class, () -> cosmosClientBuilder) .withBean(CosmosClient.class, () -> mock(CosmosClient.class)) .withPropertyValues( "spring.cloud.azure.cosmos.endpoint=" + ENDPOINT, "spring.cloud.azure.cosmos.database=test", "spring.cloud.azure.cosmos.populate-query-metrics=true") .run(context -> { assertThat(context).hasSingleBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class); }); } }
mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder))
void configureWithPopulateQueryMetricsEnabled() { this.contextRunner .withPropertyValues( "spring.cloud.azure.cosmos.populate-query-metrics=true") .run(context -> { assertThat(context).hasSingleBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).hasSingleBean(ResponseDiagnosticsProcessor.class); }); }
class CosmosDataDiagnosticsConfigurationTests { private static final String ENDPOINT = "https: private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of( AzureGlobalPropertiesAutoConfiguration.class, AzureCosmosAutoConfiguration.class, CosmosDataAutoConfiguration.class)); CosmosClientBuilder cosmosClientBuilder = mock(CosmosClientBuilder.class); CosmosAsyncClient cosmosAsyncClient = mock(CosmosAsyncClient.class); @Test @Test void configureWithPopulateQueryMetricsDisabled() { try (MockedStatic<CosmosFactory> mockedStatic = mockStatic(CosmosFactory.class, RETURNS_MOCKS)) { when(cosmosClientBuilder.buildAsyncClient()).thenReturn(cosmosAsyncClient); mockedStatic.when(() -> CosmosFactory.createCosmosAsyncClient(cosmosClientBuilder)) .thenReturn(cosmosAsyncClient); this.contextRunner .withBean(CosmosClientBuilder.class, () -> cosmosClientBuilder) .withBean(CosmosClient.class, () -> mock(CosmosClient.class)) .withPropertyValues( "spring.cloud.azure.cosmos.endpoint=" + ENDPOINT, "spring.cloud.azure.cosmos.database=test-database", "spring.cloud.azure.cosmos.populate-query-metrics=false") .run(context -> { assertThat(context).doesNotHaveBean(ResponseDiagnosticsProcessor.class); assertThat(context).hasSingleBean(CosmosDataAutoConfiguration.class); }); } } @Test void configureWithUserProvideResponseDiagnosticsProcessor() { this.contextRunner .withUserConfiguration(ResponseDiagnosticsProcessorConfiguration.class) .run(context -> { ResponseDiagnosticsProcessor processor = (ResponseDiagnosticsProcessor) context.getBean("ResponseDiagnosticsProcessor"); assertTrue(processor instanceof ResponseDiagnosticsProcessorExtend); }); } @Configuration static class ResponseDiagnosticsProcessorConfiguration { @Bean(name = "ResponseDiagnosticsProcessor") public ResponseDiagnosticsProcessor processor() { return new ResponseDiagnosticsProcessorExtend(); } } static class ResponseDiagnosticsProcessorExtend implements ResponseDiagnosticsProcessor { @Override public void processResponseDiagnostics(ResponseDiagnostics responseDiagnostics) { } } }
class CosmosDataDiagnosticsConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(TestAutoconfigurationClass.class)); @Test @Test void configureWithPopulateQueryMetricsDisabled() { this.contextRunner .withPropertyValues( "spring.cloud.azure.cosmos.populate-query-metrics=false") .run(context -> { assertThat(context).doesNotHaveBean(CosmosDataDiagnosticsConfiguration.class); assertThat(context).doesNotHaveBean(ResponseDiagnosticsProcessor.class); }); } @Test void configureWithUserProvideResponseDiagnosticsProcessor() { this.contextRunner .withUserConfiguration(ResponseDiagnosticsProcessorConfiguration.class) .run(context -> { ResponseDiagnosticsProcessor processor = (ResponseDiagnosticsProcessor) context.getBean("ResponseDiagnosticsProcessor"); assertTrue(processor instanceof ResponseDiagnosticsProcessorExtend); }); } @Configuration static class ResponseDiagnosticsProcessorConfiguration { @Bean(name = "ResponseDiagnosticsProcessor") public ResponseDiagnosticsProcessor processor() { return new ResponseDiagnosticsProcessorExtend(); } } static class ResponseDiagnosticsProcessorExtend implements ResponseDiagnosticsProcessor { @Override public void processResponseDiagnostics(ResponseDiagnostics responseDiagnostics) { } } @Configuration @Import(CosmosDataDiagnosticsConfiguration.class) static class TestAutoconfigurationClass { } }
This probably isn't that hot a path so it isn't a big deal, but why increase the allocation here?
private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } }
byte[] buffer = new byte[4096];
private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient() { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder.validateAuthority(false); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { return OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); userAgent = UserAgentUtil.toUserAgentString(null, clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } }
class IdentityClientBase { static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); static final String WINDOWS_STARTER = "cmd.exe"; static final String LINUX_MAC_STARTER = "/bin/sh"; static final String WINDOWS_SWITCHER = "/c"; static final String LINUX_MAC_SWITCHER = "-c"; static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; static final Pattern LINUX_MAC_PROCESS_ERROR_MESSAGE = Pattern.compile("(.*)az:(.*)not found"); static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; static final String MSI_ENDPOINT_VERSION = "2017-09-01"; static final String ARC_MANAGED_IDENTITY_ENDPOINT_API_VERSION = "2019-11-01"; static final String ADFS_TENANT = "adfs"; static final String HTTP_LOCALHOST = "http: static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; static final ClientLogger LOGGER = new ClientLogger(IdentityClient.class); static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("\"accessToken\": \"(.*?)(\"|$)"); static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); private static final String AZURE_IDENTITY_PROPERTIES = "azure-identity.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private final Map<String, String> properties; final IdentityClientOptions options; final String tenantId; final String clientId; final String resourceId; final String clientSecret; final String clientAssertionFilePath; final InputStream certificate; final String certificatePath; final Supplier<String> clientAssertionSupplier; final String certificatePassword; HttpPipelineAdapter httpPipelineAdapter; String userAgent = UserAgentUtil.DEFAULT_USER_AGENT_HEADER; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param resourceId the resource ID of the application * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param clientAssertionTimeout the timeout to use for the client assertion. * @param options the options configuring the client. */ IdentityClientBase(String tenantId, String clientId, String clientSecret, String certificatePath, String clientAssertionFilePath, String resourceId, Supplier<String> clientAssertionSupplier, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, Duration clientAssertionTimeout, IdentityClientOptions options) { if (tenantId == null) { tenantId = IdentityUtil.DEFAULT_TENANT; options.setAdditionallyAllowedTenants(Collections.singletonList(IdentityUtil.ALL_TENANTS)); } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.resourceId = resourceId; this.clientSecret = clientSecret; this.clientAssertionFilePath = clientAssertionFilePath; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.clientAssertionSupplier = clientAssertionSupplier; this.options = options; properties = CoreUtils.getProperties(AZURE_IDENTITY_PROPERTIES); } ConfidentialClientApplication getConfidentialClient() { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { try (InputStream pfxCertificateStream = getCertificateInputStream()) { credential = ClientCredentialFactory.createFromCertificate(pfxCertificateStream, certificatePassword); } } } catch (IOException | GeneralSecurityException e) { throw LOGGER.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e)); } } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return confidentialClientApplication; } PublicClientApplication getPublicClient(boolean sharedTokenCacheCredential) { if (clientId == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); try { builder = builder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { builder.httpClient(httpPipelineAdapter); } else { builder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { builder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); builder.clientCapabilities(set); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw LOGGER.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); if (tokenCache != null) { tokenCache.registerCache(); } return publicClientApplication; } ConfidentialClientApplication getManagedIdentityConfidentialClient() { String authorityUrl = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; IClientCredential credential = ClientCredentialFactory .createFromSecret(clientSecret != null ? clientSecret : "dummy-secret"); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId == null ? "SYSTEM-ASSIGNED-MANAGED-IDENTITY" : clientId, credential); applicationBuilder.validateAuthority(false); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw LOGGER.logExceptionAsWarning(new IllegalStateException(e)); } if (options.getManagedIdentityType() == null) { throw LOGGER.logExceptionAsError( new CredentialUnavailableException("Managed Identity type not configured, authentication not available.")); } applicationBuilder.appTokenProvider(appTokenProviderParameters -> { TokenRequestContext trc = new TokenRequestContext() .setScopes(new ArrayList<>(appTokenProviderParameters.scopes)) .setClaims(appTokenProviderParameters.claims) .setTenantId(appTokenProviderParameters.tenantId); Mono<AccessToken> accessTokenAsync = getTokenFromTargetManagedIdentity(trc); return accessTokenAsync.map(accessToken -> { TokenProviderResult result = new TokenProviderResult(); result.setAccessToken(accessToken.getToken()); result.setTenantId(trc.getTenantId()); result.setExpiresInSeconds(accessToken.getExpiresAt().toEpochSecond()); return result; }).toFuture(); }); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); } DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder buildDeviceCodeFlowParameters(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return parametersBuilder; } OnBehalfOfParameters buildOBOFlowParameters(TokenRequestContext request) { return OnBehalfOfParameters .builder(new HashSet<>(request.getScopes()), options.getUserAssertion()) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)) .build(); } InteractiveRequestParameters.InteractiveRequestParametersBuilder buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT) .tenant(IdentityUtil .resolveTenantId(tenantId, request, options)); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } return builder; } UserNamePasswordParameters.UserNamePasswordParametersBuilder buildUsernamePasswordFlowParameters(TokenRequestContext request, String username, String password) { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } userNamePasswordParametersBuilder.tenant( IdentityUtil.resolveTenantId(tenantId, request, options)); return userNamePasswordParametersBuilder; } AccessToken getTokenFromAzureCLIAuthentication(StringBuilder azCommand) { AccessToken token; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw LOGGER.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from. To mitigate this issue, please refer to the troubleshooting " + " guidelines here at https: } builder.redirectErrorStream(true); Process process = builder.start(); StringBuilder output = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || LINUX_MAC_PROCESS_ERROR_MESSAGE.matcher(line).matches()) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed." + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https: } output.append(line); } } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo(processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw LoggingUtil.logCredentialUnavailableException(LOGGER, options, new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account. To further mitigate this" + " issue, please refer to the troubleshooting guidelines here at " + "https: } throw LOGGER.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw LOGGER.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } LOGGER.verbose("Azure CLI Authentication => A token response was received from Azure CLI, deserializing the" + " response into an Access Token."); Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } return token; } String getSafeWorkingDirectory() { if (isWindowsPlatform()) { String windowsSystemRoot = System.getenv("SystemRoot"); if (CoreUtils.isNullOrEmpty(windowsSystemRoot)) { return null; } return windowsSystemRoot + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } String redactInfo(String input) { return ACCESS_TOKEN_PATTERN.matcher(input).replaceAll("****"); } abstract Mono<AccessToken> getTokenFromTargetManagedIdentity(TokenRequestContext tokenRequestContext); HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); userAgent = UserAgentUtil.toUserAgentString(null, clientName, clientVersion, buildConfiguration); policies.add(new UserAgentPolicy(userAgent)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline, options); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient), options); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault()), options); } } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new BufferedInputStream(new FileInputStream(certificatePath)); } else { return certificate; } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Proxy.Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Proxy.Type.HTTP, options.getAddress()); } } }
Can I know what eventRaised() will do? why it doesn't use in receiver?
public ServiceBusProcessorTest(ServiceBusStressOptions options) { super(options); CONNECTION_STRING = System.getenv(AZURE_SERVICE_BUS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(CONNECTION_STRING)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format("Environment variable %s must be set", AZURE_SERVICE_BUS_CONNECTION_STRING))); } QUEUE_NAME = System.getenv(AZURE_SERVICEBUS_QUEUE_NAME); if (CoreUtils.isNullOrEmpty(QUEUE_NAME)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format("Environment variable %s must be set", AZURE_SERVICEBUS_QUEUE_NAME))); } processor = new ServiceBusClientBuilder() .connectionString(CONNECTION_STRING) .processor() .queueName(QUEUE_NAME) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .maxConcurrentCalls(options.getMaxConcurrentCalls()) .prefetchCount(options.getPrefetchCount()) .processMessage(messageContext -> { eventRaised(); }) .processError(errorContext -> { errorRaised(errorContext.getException()); }) .buildProcessorClient(); }
eventRaised();
public ServiceBusProcessorTest(ServiceBusStressOptions options) { super(options); }
class ServiceBusProcessorTest extends EventPerfTest<ServiceBusStressOptions> { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusProcessorTest.class); private static final String AZURE_SERVICE_BUS_CONNECTION_STRING = "AZURE_SERVICE_BUS_CONNECTION_STRING"; private static final String AZURE_SERVICEBUS_QUEUE_NAME = "AZURE_SERVICEBUS_QUEUE_NAME"; private final String CONNECTION_STRING; private final String QUEUE_NAME; private final ServiceBusProcessorClient processor; /** * Creates an instance of performance test. * * @param options the options configured for the test. * @throws IllegalStateException if SSL context cannot be created. */ @Override public Mono<Void> globalSetupAsync() { ServiceBusSenderClient sender = new ServiceBusClientBuilder() .connectionString(CONNECTION_STRING) .sender() .queueName(QUEUE_NAME) .buildClient(); String messageContent = TestDataCreationHelper.generateRandomString(options.getMessagesSizeBytesToSend()); for (int i = 0; i < options.getMessageBatchSendTimes(); i++) { ServiceBusMessageBatch batch = sender.createMessageBatch(); for (int j = 0; j < options.getMessagesToSend(); j++) { ServiceBusMessage message = new ServiceBusMessage(messageContent); message.setMessageId(UUID.randomUUID().toString()); batch.tryAddMessage(message); } sender.sendMessages(batch); } return Mono.empty(); } @Override public Mono<Void> setupAsync() { return super.setupAsync().then(Mono.defer(() -> { processor.start(); return Mono.empty(); })); } @Override public Mono<Void> cleanupAsync() { return Mono.defer(() -> { processor.stop(); return Mono.empty(); }).then(super.cleanupAsync()); } }
class ServiceBusProcessorTest extends ServiceBusEventTest<ServiceBusStressOptions> { /** * Creates an instance of performance test. * * @param options the options configured for the test. * @throws IllegalStateException if SSL context cannot be created. */ @Override public Mono<Void> setupAsync() { return super.setupAsync().then(Mono.defer(() -> { processor.start(); return Mono.empty(); })); } @Override public Mono<Void> cleanupAsync() { return Mono.defer(() -> { processor.stop(); return Mono.empty(); }).then(super.cleanupAsync()); } }
the send and receive test extends BatchPerfTest and return the count of message in reactor chain. the processor test extends EventPerfTest and use eventRaised to record the count of process message.
public ServiceBusProcessorTest(ServiceBusStressOptions options) { super(options); CONNECTION_STRING = System.getenv(AZURE_SERVICE_BUS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(CONNECTION_STRING)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format("Environment variable %s must be set", AZURE_SERVICE_BUS_CONNECTION_STRING))); } QUEUE_NAME = System.getenv(AZURE_SERVICEBUS_QUEUE_NAME); if (CoreUtils.isNullOrEmpty(QUEUE_NAME)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format("Environment variable %s must be set", AZURE_SERVICEBUS_QUEUE_NAME))); } processor = new ServiceBusClientBuilder() .connectionString(CONNECTION_STRING) .processor() .queueName(QUEUE_NAME) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .maxConcurrentCalls(options.getMaxConcurrentCalls()) .prefetchCount(options.getPrefetchCount()) .processMessage(messageContext -> { eventRaised(); }) .processError(errorContext -> { errorRaised(errorContext.getException()); }) .buildProcessorClient(); }
eventRaised();
public ServiceBusProcessorTest(ServiceBusStressOptions options) { super(options); }
class ServiceBusProcessorTest extends EventPerfTest<ServiceBusStressOptions> { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusProcessorTest.class); private static final String AZURE_SERVICE_BUS_CONNECTION_STRING = "AZURE_SERVICE_BUS_CONNECTION_STRING"; private static final String AZURE_SERVICEBUS_QUEUE_NAME = "AZURE_SERVICEBUS_QUEUE_NAME"; private final String CONNECTION_STRING; private final String QUEUE_NAME; private final ServiceBusProcessorClient processor; /** * Creates an instance of performance test. * * @param options the options configured for the test. * @throws IllegalStateException if SSL context cannot be created. */ @Override public Mono<Void> globalSetupAsync() { ServiceBusSenderClient sender = new ServiceBusClientBuilder() .connectionString(CONNECTION_STRING) .sender() .queueName(QUEUE_NAME) .buildClient(); String messageContent = TestDataCreationHelper.generateRandomString(options.getMessagesSizeBytesToSend()); for (int i = 0; i < options.getMessageBatchSendTimes(); i++) { ServiceBusMessageBatch batch = sender.createMessageBatch(); for (int j = 0; j < options.getMessagesToSend(); j++) { ServiceBusMessage message = new ServiceBusMessage(messageContent); message.setMessageId(UUID.randomUUID().toString()); batch.tryAddMessage(message); } sender.sendMessages(batch); } return Mono.empty(); } @Override public Mono<Void> setupAsync() { return super.setupAsync().then(Mono.defer(() -> { processor.start(); return Mono.empty(); })); } @Override public Mono<Void> cleanupAsync() { return Mono.defer(() -> { processor.stop(); return Mono.empty(); }).then(super.cleanupAsync()); } }
class ServiceBusProcessorTest extends ServiceBusEventTest<ServiceBusStressOptions> { /** * Creates an instance of performance test. * * @param options the options configured for the test. * @throws IllegalStateException if SSL context cannot be created. */ @Override public Mono<Void> setupAsync() { return super.setupAsync().then(Mono.defer(() -> { processor.start(); return Mono.empty(); })); } @Override public Mono<Void> cleanupAsync() { return Mono.defer(() -> { processor.stop(); return Mono.empty(); }).then(super.cleanupAsync()); } }
The receiver test is counting for messages, it seems more like EventPerfTest not BatchPerfTest?
public ServiceBusProcessorTest(ServiceBusStressOptions options) { super(options); CONNECTION_STRING = System.getenv(AZURE_SERVICE_BUS_CONNECTION_STRING); if (CoreUtils.isNullOrEmpty(CONNECTION_STRING)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format("Environment variable %s must be set", AZURE_SERVICE_BUS_CONNECTION_STRING))); } QUEUE_NAME = System.getenv(AZURE_SERVICEBUS_QUEUE_NAME); if (CoreUtils.isNullOrEmpty(QUEUE_NAME)) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format("Environment variable %s must be set", AZURE_SERVICEBUS_QUEUE_NAME))); } processor = new ServiceBusClientBuilder() .connectionString(CONNECTION_STRING) .processor() .queueName(QUEUE_NAME) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .maxConcurrentCalls(options.getMaxConcurrentCalls()) .prefetchCount(options.getPrefetchCount()) .processMessage(messageContext -> { eventRaised(); }) .processError(errorContext -> { errorRaised(errorContext.getException()); }) .buildProcessorClient(); }
eventRaised();
public ServiceBusProcessorTest(ServiceBusStressOptions options) { super(options); }
class ServiceBusProcessorTest extends EventPerfTest<ServiceBusStressOptions> { private static final ClientLogger LOGGER = new ClientLogger(ServiceBusProcessorTest.class); private static final String AZURE_SERVICE_BUS_CONNECTION_STRING = "AZURE_SERVICE_BUS_CONNECTION_STRING"; private static final String AZURE_SERVICEBUS_QUEUE_NAME = "AZURE_SERVICEBUS_QUEUE_NAME"; private final String CONNECTION_STRING; private final String QUEUE_NAME; private final ServiceBusProcessorClient processor; /** * Creates an instance of performance test. * * @param options the options configured for the test. * @throws IllegalStateException if SSL context cannot be created. */ @Override public Mono<Void> globalSetupAsync() { ServiceBusSenderClient sender = new ServiceBusClientBuilder() .connectionString(CONNECTION_STRING) .sender() .queueName(QUEUE_NAME) .buildClient(); String messageContent = TestDataCreationHelper.generateRandomString(options.getMessagesSizeBytesToSend()); for (int i = 0; i < options.getMessageBatchSendTimes(); i++) { ServiceBusMessageBatch batch = sender.createMessageBatch(); for (int j = 0; j < options.getMessagesToSend(); j++) { ServiceBusMessage message = new ServiceBusMessage(messageContent); message.setMessageId(UUID.randomUUID().toString()); batch.tryAddMessage(message); } sender.sendMessages(batch); } return Mono.empty(); } @Override public Mono<Void> setupAsync() { return super.setupAsync().then(Mono.defer(() -> { processor.start(); return Mono.empty(); })); } @Override public Mono<Void> cleanupAsync() { return Mono.defer(() -> { processor.stop(); return Mono.empty(); }).then(super.cleanupAsync()); } }
class ServiceBusProcessorTest extends ServiceBusEventTest<ServiceBusStressOptions> { /** * Creates an instance of performance test. * * @param options the options configured for the test. * @throws IllegalStateException if SSL context cannot be created. */ @Override public Mono<Void> setupAsync() { return super.setupAsync().then(Mono.defer(() -> { processor.start(); return Mono.empty(); })); } @Override public Mono<Void> cleanupAsync() { return Mono.defer(() -> { processor.stop(); return Mono.empty(); }).then(super.cleanupAsync()); } }
The Random String can be generated only once in the constructor and reused in the for loop below.
public Mono<Void> setupAsync() { String messageContent = TestDataCreationHelper.generateRandomString(options.getMessagesSizeBytesToSend()); for (int i = 0; i < options.getMessageBatchSendTimes(); i++) { ServiceBusMessageBatch batch = sender.createMessageBatch(); for (int j = 0; j < options.getMessageBatchSize(); j++) { ServiceBusMessage message = new ServiceBusMessage(messageContent); message.setMessageId(UUID.randomUUID().toString()); batch.tryAddMessage(message); } sender.sendMessages(batch); } return Mono.empty(); }
String messageContent = TestDataCreationHelper.generateRandomString(options.getMessagesSizeBytesToSend());
public Mono<Void> setupAsync() { for (int i = 0; i < TOTAL_MESSAGE_MULTIPLIER; i++) { List<ServiceBusMessage> messages = ServiceBusTestUtil.geMessagesToSend(options.getMessagesSizeBytesToSend(), options.getMessagesToSend()); sender.sendMessages(messages); } return Mono.empty(); }
class ReceiveMessagesTest extends ServiceBusBatchTest<ServiceBusStressOptions> { private static final ClientLogger LOGGER = new ClientLogger(ReceiveMessagesTest.class); /** * Creates an instance of Batch performance test. * * @param options the options configured for the test. * @throws IllegalStateException if SSL context cannot be created. */ public ReceiveMessagesTest(ServiceBusStressOptions options) { super(options); } @Override public int runBatch() { int count = 0; for (ServiceBusReceivedMessage message : receiver.receiveMessages(options.getMessagesToReceive())) { if (!options.getIsDeleteMode()) { receiver.complete(message); } count++; } if (count <= 0) { throw LOGGER.logExceptionAsWarning(new RuntimeException("Error. Should have received some messages.")); } return count; } @Override public Mono<Integer> runBatchAsync() { int receiveCount = options.getMessagesToReceive(); return Mono.using( receiverClientBuilder::buildAsyncClient, receiverAsync -> { return receiverAsync.receiveMessages() .take(receiveCount) .flatMap(message -> { if (!options.getIsDeleteMode()) { receiverAsync.complete(message); } return Mono.empty(); }, 1) .then() .thenReturn(receiveCount); }, ServiceBusReceiverAsyncClient::close, true ); } @Override }
class ReceiveMessagesTest extends ServiceBusBatchTest<ServiceBusStressOptions> { private static final ClientLogger LOGGER = new ClientLogger(ReceiveMessagesTest.class); /** * Creates an instance of Batch performance test. * * @param options the options configured for the test. * @throws IllegalStateException if SSL context cannot be created. */ public ReceiveMessagesTest(ServiceBusStressOptions options) { super(options); } @Override public int runBatch() { int count = 0; for (ServiceBusReceivedMessage message : receiver.receiveMessages(options.getMessagesToReceive())) { if (!options.getIsDeleteMode()) { receiver.complete(message); } count++; } if (count <= 0) { throw LOGGER.logExceptionAsWarning(new RuntimeException("Error. Should have received some messages.")); } return count; } @Override public Mono<Integer> runBatchAsync() { int receiveCount = options.getMessagesToReceive(); return Mono.using( receiverClientBuilder::buildAsyncClient, receiverAsync -> { return receiverAsync.receiveMessages() .take(receiveCount) .flatMap(message -> { if (!options.getIsDeleteMode()) { receiverAsync.complete(message); } return Mono.empty(); }, 1) .then() .thenReturn(receiveCount); }, ServiceBusReceiverAsyncClient::close, true ); } @Override }
It seems kind of odd to me to pass the API version in as the modelVersion (even if they do match)
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<TextDocumentInput> documents = Arrays.asList( new TextDocumentInput("A", "Satya Nadella is the CEO of Microsoft.").setLanguage("en"), new TextDocumentInput("B", "The cat is 1 year old and weighs 10 pounds.").setLanguage("en") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions() .setIncludeStatistics(true).setModelVersion(TextAnalyticsServiceVersion.getLatest().getVersion()); Response<RecognizeEntitiesResultCollection> entitiesBatchResultResponse = client.recognizeEntitiesBatchWithResponse(documents, requestOptions, Context.NONE); System.out.printf("Status code of request response: %d%n", entitiesBatchResultResponse.getStatusCode()); RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = entitiesBatchResultResponse.getValue(); System.out.printf("Results of \"Entities Recognition\" Model, version: %s%n", recognizeEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (RecognizeEntitiesResult entitiesResult : recognizeEntitiesResultCollection) { System.out.printf("%n%s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(entity -> { System.out.printf( "Recognized entity: %s, entity category: %s, entity subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()); Iterable<? extends BaseResolution> resolutions = entity.getResolutions(); if (resolutions != null) { for (BaseResolution resolution : resolutions) { if (resolution instanceof WeightResolution) { WeightResolution weightResolution = (WeightResolution) resolution; System.out.printf("\tWeightResolution: unit: %s. value: %s.%n", weightResolution.getUnit(), weightResolution.getValue()); } else if (resolution instanceof AgeResolution) { AgeResolution weightResolution = (AgeResolution) resolution; System.out.printf("\tAgeResolution: unit: %s. value: %s.%n", weightResolution.getUnit(), weightResolution.getValue()); } } } }); } } }
.setIncludeStatistics(true).setModelVersion(TextAnalyticsServiceVersion.getLatest().getVersion());
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<TextDocumentInput> documents = Arrays.asList( new TextDocumentInput("A", "Satya Nadella is the CEO of Microsoft.").setLanguage("en"), new TextDocumentInput("B", "The cat is 1 year old and weighs 10 pounds.").setLanguage("en") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions() .setIncludeStatistics(true).setModelVersion("2022-10-01-preview"); Response<RecognizeEntitiesResultCollection> entitiesBatchResultResponse = client.recognizeEntitiesBatchWithResponse(documents, requestOptions, Context.NONE); System.out.printf("Status code of request response: %d%n", entitiesBatchResultResponse.getStatusCode()); RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = entitiesBatchResultResponse.getValue(); System.out.printf("Results of \"Entities Recognition\" Model, version: %s%n", recognizeEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (RecognizeEntitiesResult entitiesResult : recognizeEntitiesResultCollection) { System.out.printf("%n%s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(entity -> { System.out.printf( "Recognized entity: %s, entity category: %s, entity subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()); Iterable<? extends BaseResolution> resolutions = entity.getResolutions(); if (resolutions != null) { for (BaseResolution resolution : resolutions) { if (resolution instanceof WeightResolution) { WeightResolution weightResolution = (WeightResolution) resolution; System.out.printf("\tWeightResolution: unit: %s. value: %f.%n", weightResolution.getUnit(), weightResolution.getValue()); } else if (resolution instanceof AgeResolution) { AgeResolution weightResolution = (AgeResolution) resolution; System.out.printf("\tAgeResolution: unit: %s. value: %f.%n", weightResolution.getUnit(), weightResolution.getValue()); } } } }); } } }
class RecognizeEntitiesBatchDocuments { /** * Main method to invoke this demo about how to recognize the entities of {@link TextDocumentInput} documents. * * @param args Unused arguments to the program. */ }
class RecognizeEntitiesBatchDocuments { /** * Main method to invoke this demo about how to recognize the entities of {@link TextDocumentInput} documents. * * @param args Unused arguments to the program. */ }
I think value is float for both weight/age
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); List<TextDocumentInput> documents = Arrays.asList( new TextDocumentInput("A", "Satya Nadella is the CEO of Microsoft.").setLanguage("en"), new TextDocumentInput("B", "The cat is 1 year old and weighs 10 pounds.").setLanguage("en") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true) .setModelVersion(TextAnalyticsServiceVersion.getLatest().getVersion()); client.recognizeEntitiesBatchWithResponse(documents, requestOptions).subscribe( entitiesBatchResultResponse -> { System.out.printf("Status code of request response: %d%n", entitiesBatchResultResponse.getStatusCode()); RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = entitiesBatchResultResponse.getValue(); System.out.printf("Results of \"Entities Recognition\" Model, version: %s%n", recognizeEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (RecognizeEntitiesResult entitiesResult : recognizeEntitiesResultCollection) { System.out.printf("%n%s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(entity -> { System.out.printf( "Recognized entity: %s, entity category: %s, entity subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()); Iterable<? extends BaseResolution> resolutions = entity.getResolutions(); if (resolutions != null) { for (BaseResolution resolution : resolutions) { if (resolution instanceof WeightResolution) { WeightResolution weightResolution = (WeightResolution) resolution; System.out.printf("\tWeightResolution: unit: %s. value: %s.%n", weightResolution.getUnit(), weightResolution.getValue()); } else if (resolution instanceof AgeResolution) { AgeResolution weightResolution = (AgeResolution) resolution; System.out.printf("\tAgeResolution: unit: %s. value: %s.%n", weightResolution.getUnit(), weightResolution.getValue()); } } } }); } } }, error -> System.err.println("There was an error recognizing entities of the documents." + error), () -> System.out.println("Batch of entities recognized.")); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignored) { } }
System.out.printf("\tWeightResolution: unit: %s. value: %s.%n", weightResolution.getUnit(),
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); List<TextDocumentInput> documents = Arrays.asList( new TextDocumentInput("A", "Satya Nadella is the CEO of Microsoft.").setLanguage("en"), new TextDocumentInput("B", "The cat is 1 year old and weighs 10 pounds.").setLanguage("en") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true) .setModelVersion("2022-10-01-preview"); client.recognizeEntitiesBatchWithResponse(documents, requestOptions).subscribe( entitiesBatchResultResponse -> { System.out.printf("Status code of request response: %d%n", entitiesBatchResultResponse.getStatusCode()); RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = entitiesBatchResultResponse.getValue(); System.out.printf("Results of \"Entities Recognition\" Model, version: %s%n", recognizeEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (RecognizeEntitiesResult entitiesResult : recognizeEntitiesResultCollection) { System.out.printf("%n%s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(entity -> { System.out.printf( "Recognized entity: %s, entity category: %s, entity subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()); Iterable<? extends BaseResolution> resolutions = entity.getResolutions(); if (resolutions != null) { for (BaseResolution resolution : resolutions) { if (resolution instanceof WeightResolution) { WeightResolution weightResolution = (WeightResolution) resolution; System.out.printf("\tWeightResolution: unit: %s. value: %f.%n", weightResolution.getUnit(), weightResolution.getValue()); } else if (resolution instanceof AgeResolution) { AgeResolution weightResolution = (AgeResolution) resolution; System.out.printf("\tAgeResolution: unit: %s. value: %f.%n", weightResolution.getUnit(), weightResolution.getValue()); } } } }); } } }, error -> System.err.println("There was an error recognizing entities of the documents." + error), () -> System.out.println("Batch of entities recognized.")); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignored) { } }
class RecognizeEntitiesBatchDocumentsAsync { /** * Main method to invoke this demo about how to recognize the entities of {@link TextDocumentInput} documents. * * @param args Unused arguments to the program. */ }
class RecognizeEntitiesBatchDocumentsAsync { /** * Main method to invoke this demo about how to recognize the entities of {@link TextDocumentInput} documents. * * @param args Unused arguments to the program. */ }
should this be an info or a debug level?
private String getDefaultScope(Properties properties) { String ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); String authorityHost = AuthProperty.AUTHORITY_HOST.get(properties); if (AzureAuthorityHosts.AZURE_PUBLIC_CLOUD.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); } else if (AzureAuthorityHosts.AZURE_CHINA.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_CHINA); } else if (AzureAuthorityHosts.AZURE_GERMANY.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GERMANY); } else if (AzureAuthorityHosts.AZURE_GOVERNMENT.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GOVERNMENT); } LOGGER.info("Ossrdbms scope set to ", ossrdbmsScope); return ossrdbmsScope; }
LOGGER.info("Ossrdbms scope set to ", ossrdbmsScope);
private String getDefaultScope(Properties properties) { String ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); String authorityHost = AuthProperty.AUTHORITY_HOST.get(properties); if (AzureAuthorityHosts.AZURE_PUBLIC_CLOUD.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); } else if (AzureAuthorityHosts.AZURE_CHINA.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_CHINA); } else if (AzureAuthorityHosts.AZURE_GERMANY.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GERMANY); } else if (AzureAuthorityHosts.AZURE_GOVERNMENT.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GOVERNMENT); } LOGGER.info("Ossrdbms scope set to {}.", ossrdbmsScope); return ossrdbmsScope; }
class AccessTokenResolverOptions { private static final ClientLogger LOGGER = new ClientLogger(AccessTokenResolverOptions.class); private static final HashMap<String, String> OSS_RDBMS_SCOPE_MAP = new HashMap<String, String>() { { put(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "https: put(AzureAuthorityHosts.AZURE_CHINA, "https: put(AzureAuthorityHosts.AZURE_GERMANY, "https: put(AzureAuthorityHosts.AZURE_GOVERNMENT, "https: } }; private String claims; private String tenantId; private String[] scopes; public AccessTokenResolverOptions() { } public AccessTokenResolverOptions(Properties properties) { this.tenantId = AuthProperty.TENANT_ID.get(properties); this.claims = AuthProperty.CLAIMS.get(properties); String scopeProperty = AuthProperty.SCOPES.get(properties); if (scopeProperty == null) { scopeProperty = getDefaultScope(properties); } this.scopes = scopeProperty.split(","); } public String getClaims() { return claims; } public void setClaims(String claims) { this.claims = claims; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String[] getScopes() { return scopes == null ? null : scopes.clone(); } public void setScopes(String[] scopes) { this.scopes = scopes.clone(); } }
class AccessTokenResolverOptions { private static final ClientLogger LOGGER = new ClientLogger(AccessTokenResolverOptions.class); private static final Map<String, String> OSS_RDBMS_SCOPE_MAP = new HashMap<String, String>() { { put(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "https: put(AzureAuthorityHosts.AZURE_CHINA, "https: put(AzureAuthorityHosts.AZURE_GERMANY, "https: put(AzureAuthorityHosts.AZURE_GOVERNMENT, "https: } }; private String claims; private String tenantId; private String[] scopes; public AccessTokenResolverOptions() { } public AccessTokenResolverOptions(Properties properties) { this.tenantId = AuthProperty.TENANT_ID.get(properties); this.claims = AuthProperty.CLAIMS.get(properties); String scopeProperty = AuthProperty.SCOPES.get(properties); if (scopeProperty == null) { scopeProperty = getDefaultScope(properties); } this.scopes = scopeProperty.split(","); } public String getClaims() { return claims; } public void setClaims(String claims) { this.claims = claims; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String[] getScopes() { return scopes == null ? null : scopes.clone(); } public void setScopes(String[] scopes) { this.scopes = scopes.clone(); } }
please make sure all assertions methods have been updated.
void testConstructorWithProperties() { Properties properties = new Properties(); properties.setProperty(AuthProperty.TENANT_ID.getPropertyKey(), "fake-tenant-id"); properties.setProperty(AuthProperty.CLAIMS.getPropertyKey(), "fake-claims"); properties.setProperty(AuthProperty.SCOPES.getPropertyKey(), "fake-scopes"); AccessTokenResolverOptions accessTokenResolverOptions = new AccessTokenResolverOptions(properties); assertEquals(accessTokenResolverOptions.getClaims(), "fake-claims"); assertArrayEquals(new String[]{"fake-scopes"}, accessTokenResolverOptions.getScopes()); assertEquals(accessTokenResolverOptions.getTenantId(), "fake-tenant-id"); }
assertEquals(accessTokenResolverOptions.getClaims(), "fake-claims");
void testConstructorWithProperties() { Properties properties = new Properties(); properties.setProperty(AuthProperty.TENANT_ID.getPropertyKey(), "fake-tenant-id"); properties.setProperty(AuthProperty.CLAIMS.getPropertyKey(), "fake-claims"); properties.setProperty(AuthProperty.SCOPES.getPropertyKey(), "fake-scopes"); AccessTokenResolverOptions accessTokenResolverOptions = new AccessTokenResolverOptions(properties); assertEquals("fake-claims", accessTokenResolverOptions.getClaims()); assertArrayEquals(new String[]{"fake-scopes"}, accessTokenResolverOptions.getScopes()); assertEquals("fake-tenant-id", accessTokenResolverOptions.getTenantId()); }
class AccessTokenResolverOptionsTest { @Test void testDefaultConstructor() { AccessTokenResolverOptions accessTokenResolverOptions = new AccessTokenResolverOptions(); assertNull(accessTokenResolverOptions.getClaims()); assertNull(accessTokenResolverOptions.getScopes()); assertNull(accessTokenResolverOptions.getTenantId()); } @Test @ParameterizedTest @MethodSource("provideAuthorityHostScopeMap") void testDifferentAuthorties(String authorityHost, String scope) { Properties properties = new Properties(); AuthProperty.AUTHORITY_HOST.setProperty(properties, authorityHost); AccessTokenResolverOptions accessTokenResolverOptions = new AccessTokenResolverOptions(properties); assertArrayEquals(new String[]{scope}, accessTokenResolverOptions.getScopes()); } private static Stream<Arguments> provideAuthorityHostScopeMap() { return Stream.of( Arguments.of(null, "https: Arguments.of("", "https: Arguments.of(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "https: Arguments.of(AzureAuthorityHosts.AZURE_CHINA, "https: Arguments.of(AzureAuthorityHosts.AZURE_GERMANY, "https: Arguments.of(AzureAuthorityHosts.AZURE_GOVERNMENT, "https: ); } }
class AccessTokenResolverOptionsTest { @Test void testDefaultConstructor() { AccessTokenResolverOptions accessTokenResolverOptions = new AccessTokenResolverOptions(); assertNull(accessTokenResolverOptions.getClaims()); assertNull(accessTokenResolverOptions.getScopes()); assertNull(accessTokenResolverOptions.getTenantId()); } @Test @ParameterizedTest @MethodSource("provideAuthorityHostScopeMap") void testDifferentAuthorties(String authorityHost, String scope) { Properties properties = new Properties(); AuthProperty.AUTHORITY_HOST.setProperty(properties, authorityHost); AccessTokenResolverOptions accessTokenResolverOptions = new AccessTokenResolverOptions(properties); assertArrayEquals(new String[]{scope}, accessTokenResolverOptions.getScopes()); } private static Stream<Arguments> provideAuthorityHostScopeMap() { return Stream.of( Arguments.of(null, "https: Arguments.of("", "https: Arguments.of(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "https: Arguments.of(AzureAuthorityHosts.AZURE_CHINA, "https: Arguments.of(AzureAuthorityHosts.AZURE_GERMANY, "https: Arguments.of(AzureAuthorityHosts.AZURE_GOVERNMENT, "https: ); } }
I prefer it to be an info log.
private String getDefaultScope(Properties properties) { String ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); String authorityHost = AuthProperty.AUTHORITY_HOST.get(properties); if (AzureAuthorityHosts.AZURE_PUBLIC_CLOUD.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); } else if (AzureAuthorityHosts.AZURE_CHINA.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_CHINA); } else if (AzureAuthorityHosts.AZURE_GERMANY.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GERMANY); } else if (AzureAuthorityHosts.AZURE_GOVERNMENT.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GOVERNMENT); } LOGGER.info("Ossrdbms scope set to ", ossrdbmsScope); return ossrdbmsScope; }
LOGGER.info("Ossrdbms scope set to ", ossrdbmsScope);
private String getDefaultScope(Properties properties) { String ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); String authorityHost = AuthProperty.AUTHORITY_HOST.get(properties); if (AzureAuthorityHosts.AZURE_PUBLIC_CLOUD.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); } else if (AzureAuthorityHosts.AZURE_CHINA.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_CHINA); } else if (AzureAuthorityHosts.AZURE_GERMANY.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GERMANY); } else if (AzureAuthorityHosts.AZURE_GOVERNMENT.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GOVERNMENT); } LOGGER.info("Ossrdbms scope set to {}.", ossrdbmsScope); return ossrdbmsScope; }
class AccessTokenResolverOptions { private static final ClientLogger LOGGER = new ClientLogger(AccessTokenResolverOptions.class); private static final HashMap<String, String> OSS_RDBMS_SCOPE_MAP = new HashMap<String, String>() { { put(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "https: put(AzureAuthorityHosts.AZURE_CHINA, "https: put(AzureAuthorityHosts.AZURE_GERMANY, "https: put(AzureAuthorityHosts.AZURE_GOVERNMENT, "https: } }; private String claims; private String tenantId; private String[] scopes; public AccessTokenResolverOptions() { } public AccessTokenResolverOptions(Properties properties) { this.tenantId = AuthProperty.TENANT_ID.get(properties); this.claims = AuthProperty.CLAIMS.get(properties); String scopeProperty = AuthProperty.SCOPES.get(properties); if (scopeProperty == null) { scopeProperty = getDefaultScope(properties); } this.scopes = scopeProperty.split(","); } public String getClaims() { return claims; } public void setClaims(String claims) { this.claims = claims; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String[] getScopes() { return scopes == null ? null : scopes.clone(); } public void setScopes(String[] scopes) { this.scopes = scopes.clone(); } }
class AccessTokenResolverOptions { private static final ClientLogger LOGGER = new ClientLogger(AccessTokenResolverOptions.class); private static final Map<String, String> OSS_RDBMS_SCOPE_MAP = new HashMap<String, String>() { { put(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "https: put(AzureAuthorityHosts.AZURE_CHINA, "https: put(AzureAuthorityHosts.AZURE_GERMANY, "https: put(AzureAuthorityHosts.AZURE_GOVERNMENT, "https: } }; private String claims; private String tenantId; private String[] scopes; public AccessTokenResolverOptions() { } public AccessTokenResolverOptions(Properties properties) { this.tenantId = AuthProperty.TENANT_ID.get(properties); this.claims = AuthProperty.CLAIMS.get(properties); String scopeProperty = AuthProperty.SCOPES.get(properties); if (scopeProperty == null) { scopeProperty = getDefaultScope(properties); } this.scopes = scopeProperty.split(","); } public String getClaims() { return claims; } public void setClaims(String claims) { this.claims = claims; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String[] getScopes() { return scopes == null ? null : scopes.clone(); } public void setScopes(String[] scopes) { this.scopes = scopes.clone(); } }
```suggestion LOGGER.info("Ossrdbms scope set to {}", ossrdbmsScope); ```
private String getDefaultScope(Properties properties) { String ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); String authorityHost = AuthProperty.AUTHORITY_HOST.get(properties); if (AzureAuthorityHosts.AZURE_PUBLIC_CLOUD.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); } else if (AzureAuthorityHosts.AZURE_CHINA.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_CHINA); } else if (AzureAuthorityHosts.AZURE_GERMANY.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GERMANY); } else if (AzureAuthorityHosts.AZURE_GOVERNMENT.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GOVERNMENT); } LOGGER.info("Ossrdbms scope set to ", ossrdbmsScope); return ossrdbmsScope; }
LOGGER.info("Ossrdbms scope set to ", ossrdbmsScope);
private String getDefaultScope(Properties properties) { String ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); String authorityHost = AuthProperty.AUTHORITY_HOST.get(properties); if (AzureAuthorityHosts.AZURE_PUBLIC_CLOUD.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); } else if (AzureAuthorityHosts.AZURE_CHINA.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_CHINA); } else if (AzureAuthorityHosts.AZURE_GERMANY.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GERMANY); } else if (AzureAuthorityHosts.AZURE_GOVERNMENT.startsWith(authorityHost)) { ossrdbmsScope = OSS_RDBMS_SCOPE_MAP.get(AzureAuthorityHosts.AZURE_GOVERNMENT); } LOGGER.info("Ossrdbms scope set to {}.", ossrdbmsScope); return ossrdbmsScope; }
class AccessTokenResolverOptions { private static final ClientLogger LOGGER = new ClientLogger(AccessTokenResolverOptions.class); private static final HashMap<String, String> OSS_RDBMS_SCOPE_MAP = new HashMap<String, String>() { { put(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "https: put(AzureAuthorityHosts.AZURE_CHINA, "https: put(AzureAuthorityHosts.AZURE_GERMANY, "https: put(AzureAuthorityHosts.AZURE_GOVERNMENT, "https: } }; private String claims; private String tenantId; private String[] scopes; public AccessTokenResolverOptions() { } public AccessTokenResolverOptions(Properties properties) { this.tenantId = AuthProperty.TENANT_ID.get(properties); this.claims = AuthProperty.CLAIMS.get(properties); String scopeProperty = AuthProperty.SCOPES.get(properties); if (scopeProperty == null) { scopeProperty = getDefaultScope(properties); } this.scopes = scopeProperty.split(","); } public String getClaims() { return claims; } public void setClaims(String claims) { this.claims = claims; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String[] getScopes() { return scopes == null ? null : scopes.clone(); } public void setScopes(String[] scopes) { this.scopes = scopes.clone(); } }
class AccessTokenResolverOptions { private static final ClientLogger LOGGER = new ClientLogger(AccessTokenResolverOptions.class); private static final Map<String, String> OSS_RDBMS_SCOPE_MAP = new HashMap<String, String>() { { put(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "https: put(AzureAuthorityHosts.AZURE_CHINA, "https: put(AzureAuthorityHosts.AZURE_GERMANY, "https: put(AzureAuthorityHosts.AZURE_GOVERNMENT, "https: } }; private String claims; private String tenantId; private String[] scopes; public AccessTokenResolverOptions() { } public AccessTokenResolverOptions(Properties properties) { this.tenantId = AuthProperty.TENANT_ID.get(properties); this.claims = AuthProperty.CLAIMS.get(properties); String scopeProperty = AuthProperty.SCOPES.get(properties); if (scopeProperty == null) { scopeProperty = getDefaultScope(properties); } this.scopes = scopeProperty.split(","); } public String getClaims() { return claims; } public void setClaims(String claims) { this.claims = claims; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String[] getScopes() { return scopes == null ? null : scopes.clone(); } public void setScopes(String[] scopes) { this.scopes = scopes.clone(); } }
Doesn't this equal to MYSQL_USER_AGENT?
void mySqlAuthPluginOnClassPath() { contextRunner .withPropertyValues( "spring.datasource.azure.passwordless-enabled=true", "spring.datasource.url=" + MYSQL_CONNECTION_STRING ) .run( context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(DataSourceProperties.class); DataSourceProperties dataSourceProperties = context.getBean(DataSourceProperties.class); String expectedJdbcUrl = enhanceJdbcUrl( DatabaseType.MYSQL, MYSQL_CONNECTION_STRING, PUBLIC_AUTHORITY_HOST_STRING, PropertyKey.connectionAttributes.getKeyName() + "=_extension_version:" + AzureSpringIdentifier.AZURE_SPRING_MYSQL_OAUTH, AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.getPropertyKey() + "=" + SpringTokenCredentialProvider.class.getName() ); assertEquals(expectedJdbcUrl, dataSourceProperties.getUrl()); } ); }
PropertyKey.connectionAttributes.getKeyName() + "=_extension_version:" + AzureSpringIdentifier.AZURE_SPRING_MYSQL_OAUTH,
void mySqlAuthPluginOnClassPath() { contextRunner .withPropertyValues( "spring.datasource.azure.passwordless-enabled=true", "spring.datasource.url=" + MYSQL_CONNECTION_STRING ) .run( context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(DataSourceProperties.class); DataSourceProperties dataSourceProperties = context.getBean(DataSourceProperties.class); String expectedJdbcUrl = enhanceJdbcUrl( DatabaseType.MYSQL, MYSQL_CONNECTION_STRING, PUBLIC_AUTHORITY_HOST_STRING, MYSQL_USER_AGENT, AuthProperty.TOKEN_CREDENTIAL_PROVIDER_CLASS_NAME.getPropertyKey() + "=" + SpringTokenCredentialProvider.class.getName() ); assertEquals(expectedJdbcUrl, dataSourceProperties.getUrl()); } ); }
class JdbcPropertiesBeanPostProcessorWithApplicationContextRunnerTest { private static final String MYSQL_CONNECTION_STRING = "jdbc:mysql: private static final String PUBLIC_AUTHORITY_HOST_STRING = AuthProperty.AUTHORITY_HOST.getPropertyKey() + "=" + "https: private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AzureJdbcAutoConfiguration.class, DataSourceProperties.class, AzurePasswordlessProperties.class, AzureGlobalPropertiesAutoConfiguration.class, AzureTokenCredentialAutoConfiguration.class)); @Test void mySqlAuthPluginNotOnClassPath() { contextRunner .withClassLoader(new FilteredClassLoader(AzureIdentityMysqlAuthenticationPlugin.class)) .withPropertyValues( "spring.datasource.azure.passwordless-enabled=true", "spring.datasource.url=" + MYSQL_CONNECTION_STRING ) .run( context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(DataSourceProperties.class); DataSourceProperties dataSourceProperties = context.getBean(DataSourceProperties.class); assertEquals(MYSQL_CONNECTION_STRING, dataSourceProperties.getUrl()); } ); } @Test @Test void shouldNotConfigureWithoutDataSourceProperties() { this.contextRunner .withClassLoader(new FilteredClassLoader(DataSourceProperties.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureJdbcAutoConfiguration.class)); } @Test void shouldConfigure() { this.contextRunner .run(context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(SpringTokenCredentialProviderContextProvider.class); }); } @Test void testBindSpringBootProperties() { this.contextRunner .withPropertyValues( "spring.datasource.azure.credential.client-id=fake-jdbc-client-id", "spring.cloud.azure.credential.client-id=azure-client-id" ) .run(context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(SpringTokenCredentialProviderContextProvider.class); ConfigurableEnvironment environment = context.getEnvironment(); AzurePasswordlessProperties properties = Binder.get(environment).bindOrCreate("spring.datasource.azure", AzurePasswordlessProperties.class); assertNotEquals("azure-client-id", properties.getCredential().getClientId()); assertEquals("fake-jdbc-client-id", properties.getCredential().getClientId()); }); } @Test void testBindAzureGlobalProperties() { this.contextRunner .withPropertyValues( "spring.cloud.azure.credential.client-id=azure-client-id" ) .run(context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(SpringTokenCredentialProviderContextProvider.class); assertThat(context).hasSingleBean(AzureGlobalProperties.class); AzureGlobalProperties azureGlobalProperties = context.getBean(AzureGlobalProperties.class); assertEquals("azure-client-id", azureGlobalProperties.getCredential().getClientId()); }); } }
class JdbcPropertiesBeanPostProcessorWithApplicationContextRunnerTest { private static final String MYSQL_CONNECTION_STRING = "jdbc:mysql: private static final String PUBLIC_AUTHORITY_HOST_STRING = AuthProperty.AUTHORITY_HOST.getPropertyKey() + "=" + "https: private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AzureJdbcAutoConfiguration.class, DataSourceProperties.class, AzurePasswordlessProperties.class, AzureGlobalPropertiesAutoConfiguration.class, AzureTokenCredentialAutoConfiguration.class)); @Test void mySqlAuthPluginNotOnClassPath() { contextRunner .withClassLoader(new FilteredClassLoader(AzureIdentityMysqlAuthenticationPlugin.class)) .withPropertyValues( "spring.datasource.azure.passwordless-enabled=true", "spring.datasource.url=" + MYSQL_CONNECTION_STRING ) .run( context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(DataSourceProperties.class); DataSourceProperties dataSourceProperties = context.getBean(DataSourceProperties.class); assertEquals(MYSQL_CONNECTION_STRING, dataSourceProperties.getUrl()); } ); } @Test @Test void shouldNotConfigureWithoutDataSourceProperties() { this.contextRunner .withClassLoader(new FilteredClassLoader(DataSourceProperties.class)) .run(context -> assertThat(context).doesNotHaveBean(AzureJdbcAutoConfiguration.class)); } @Test void shouldConfigure() { this.contextRunner .run(context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(SpringTokenCredentialProviderContextProvider.class); }); } @Test void testBindSpringBootProperties() { this.contextRunner .withPropertyValues( "spring.datasource.azure.credential.client-id=fake-jdbc-client-id", "spring.cloud.azure.credential.client-id=azure-client-id" ) .run(context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(SpringTokenCredentialProviderContextProvider.class); ConfigurableEnvironment environment = context.getEnvironment(); AzurePasswordlessProperties properties = Binder.get(environment).bindOrCreate("spring.datasource.azure", AzurePasswordlessProperties.class); assertNotEquals("azure-client-id", properties.getCredential().getClientId()); assertEquals("fake-jdbc-client-id", properties.getCredential().getClientId()); }); } @Test void testBindAzureGlobalProperties() { this.contextRunner .withPropertyValues( "spring.cloud.azure.credential.client-id=azure-client-id" ) .run(context -> { assertThat(context).hasSingleBean(AzureJdbcAutoConfiguration.class); assertThat(context).hasSingleBean(JdbcPropertiesBeanPostProcessor.class); assertThat(context).hasSingleBean(SpringTokenCredentialProviderContextProvider.class); assertThat(context).hasSingleBean(AzureGlobalProperties.class); AzureGlobalProperties azureGlobalProperties = context.getBean(AzureGlobalProperties.class); assertEquals("azure-client-id", azureGlobalProperties.getCredential().getClientId()); }); } }
Did this test fail because of the changes in this PR or is this unrelated?
public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keysToList) -> { String keyName = null; for (CreateKeyOptions key : keysToList) { keyName = key.getName(); StepVerifier.create(keyAsyncClient.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)) .verifyComplete(); } sleepInRecordMode(30000); StepVerifier.create(keyAsyncClient.listPropertiesOfKeyVersions(keyName).collectList()) .assertNext(actualKeys -> assertEquals(keysToList.size(), actualKeys.size())) .verifyComplete(); }); }
.verifyComplete();
public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keysToList) -> { String keyName = null; for (CreateKeyOptions key : keysToList) { keyName = key.getName(); StepVerifier.create(keyAsyncClient.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)) .verifyComplete(); } sleepInRecordMode(30000); StepVerifier.create(keyAsyncClient.listPropertiesOfKeyVersions(keyName).collectList()) .assertNext(actualKeys -> assertEquals(keysToList.size(), actualKeys.size())) .verifyComplete(); }); }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient keyAsyncClient; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion, null); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion, String testTenantId) { HttpPipeline httpPipeline = getHttpPipeline(buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), testTenantId); KeyClientImpl implClient = spy(new KeyClientImpl(getEndpoint(), httpPipeline, serviceVersion)); if (interceptorManager.isPlaybackMode()) { when(implClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } keyAsyncClient = new KeyAsyncClient(implClient); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { BiFunction<HttpRequest, Context, Boolean> skipRequestFunction = (request, context) -> { String callerMethod = (String) context.getData("caller-method").orElse(""); return (callerMethod.contains("list") || callerMethod.contains("getKeys") || callerMethod.contains("getKeyVersions") || callerMethod.contains("delete") || callerMethod.contains("recover") || callerMethod.contains("Cryptography")); }; return new AssertingHttpClientBuilder(httpClient) .skipRequest(skipRequestFunction) .assertAsync() .build(); } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that a key can be created in the key vault while using a different tenant ID than the one that will be * provided in the authentication challenge. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyWithMultipleTenants(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); KeyVaultCredentialPolicy.clearCache(); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createRsaKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); final KeyType keyType; if (runManagedHsmTest) { keyType = KeyType.RSA_HSM; } else { keyType = KeyType.RSA; } StepVerifier.create(keyAsyncClient.createKey("", keyType)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyEmptyValueRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey) .flatMap(response -> { assertKeyEquals(originalKey, response); return keyAsyncClient.updateKeyProperties(response.getProperties() .setExpiresOn(updatedKey.getExpiresOn())); })) .assertNext(response -> assertKeyEquals(updatedKey, response)) .verifyComplete()); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey) .flatMap(response -> { assertKeyEquals(originalKey, response); return keyAsyncClient.updateKeyProperties(response.getProperties() .setExpiresOn(updatedKey.getExpiresOn())); })) .assertNext(response -> assertKeyEquals(updatedKey, response)) .verifyComplete()); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((keyToSetAndGet) -> { StepVerifier.create(keyAsyncClient.createKey(keyToSetAndGet)) .assertNext(response -> assertKeyEquals(keyToSetAndGet, response)) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKey(keyToSetAndGet.getName())) .assertNext(response -> assertKeyEquals(keyToSetAndGet, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((keyWithOriginalValue, keyWithNewValue) -> { final KeyVaultKey keyVersionOne = keyAsyncClient.createKey(keyWithOriginalValue).block(); final KeyVaultKey keyVersionTwo = keyAsyncClient.createKey(keyWithNewValue).block(); StepVerifier.create(keyAsyncClient.getKey(keyWithOriginalValue.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithOriginalValue, response)) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKey(keyWithNewValue.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewValue, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.beginDeleteKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getDeletedKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = keyAsyncClient.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(keyAsyncClient.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(keyAsyncClient.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.backupKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(keyAsyncClient.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)) .verifyComplete(); byte[] backup = keyAsyncClient.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(keyAsyncClient.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode())) .verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(keyAsyncClient.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(keyAsyncClient.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)) .verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(keyAsyncClient.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (interceptorManager.isLiveMode()) { return; } listDeletedKeysRunner((keysToList) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keysToList.values()) { StepVerifier.create(keyAsyncClient.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keysToList.values()) { PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = keyAsyncClient.listDeletedKeys() .map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keysToList) -> { for (CreateKeyOptions key : keysToList.values()) { assertKeyEquals(key, keyAsyncClient.createKey(key).block()); } sleepInRecordMode(10000); keyAsyncClient.listPropertiesOfKeys().map(actualKey -> { if (keysToList.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keysToList.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keysToList.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keysToList.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(runManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(keyAsyncClient.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)) .verifyComplete(); String targetAttestationToken = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { targetAttestationToken = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(keyAsyncClient.releaseKey(keyToRelease.getName(), targetAttestationToken)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(testResourceNamer.randomName("nonExistentKey", 20))) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(keyName)) .assertNext(keyRotationPolicy -> { assertNotNull(keyRotationPolicy); assertNull(keyRotationPolicy.getId()); assertNull(keyRotationPolicy.getCreatedOn()); assertNull(keyRotationPolicy.getUpdatedOn()); assertNull(keyRotationPolicy.getExpiresIn()); assertEquals(1, keyRotationPolicy.getLifetimeActions().size()); assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getAction()); assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry()); assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate()); }).verifyComplete(); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @Disabled("Disable after https: public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicy) -> { StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), keyAsyncClient.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that an key rotation policy can be updated with all possible properties, then retrieves it. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicy) -> { StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), keyAsyncClient.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that a key can be rotated. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName)) .flatMap(createdKey -> Mono.zip(Mono.just(createdKey), keyAsyncClient.rotateKey(keyName)))) .assertNext(tuple -> { KeyVaultKey createdKey = tuple.getT1(); KeyVaultKey rotatedKey = tuple.getT2(); assertEquals(createdKey.getName(), rotatedKey.getName()); assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags()); }).verifyComplete(); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests * that cryptographic operations can be performed with said cryptography client. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyRunner((keyToCreate) -> { StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete(); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient(keyToCreate.getName()); assertNotNull(cryptographyAsyncClient); byte[] plaintext = "myPlaintext".getBytes(); StepVerifier.create(cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) .map(EncryptResult::getCipherText) .flatMap(ciphertext -> cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) .map(DecryptResult::getPlainText))) .assertNext(decryptedText -> assertArrayEquals(plaintext, decryptedText)) .verifyComplete(); }); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key and version using a * {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", "6A385B124DEF4096AF1361A85B16C204"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", ""); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", null); assertNotNull(cryptographyAsyncClient); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = keyAsyncClient.getDeletedKey(keyName).block(); } catch (ResourceNotFoundException ignored) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient keyAsyncClient; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion, null); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion, String testTenantId) { HttpPipeline httpPipeline = getHttpPipeline(buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), testTenantId); KeyClientImpl implClient = spy(new KeyClientImpl(getEndpoint(), httpPipeline, serviceVersion)); if (interceptorManager.isPlaybackMode()) { when(implClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } keyAsyncClient = new KeyAsyncClient(implClient); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { BiFunction<HttpRequest, Context, Boolean> skipRequestFunction = (request, context) -> { String callerMethod = (String) context.getData("caller-method").orElse(""); return (callerMethod.contains("list") || callerMethod.contains("getKeys") || callerMethod.contains("getKeyVersions") || callerMethod.contains("delete") || callerMethod.contains("recover") || callerMethod.contains("Cryptography")); }; return new AssertingHttpClientBuilder(httpClient) .skipRequest(skipRequestFunction) .assertAsync() .build(); } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that a key can be created in the key vault while using a different tenant ID than the one that will be * provided in the authentication challenge. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyWithMultipleTenants(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); KeyVaultCredentialPolicy.clearCache(); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createRsaKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); final KeyType keyType; if (runManagedHsmTest) { keyType = KeyType.RSA_HSM; } else { keyType = KeyType.RSA; } StepVerifier.create(keyAsyncClient.createKey("", keyType)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyEmptyValueRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey) .flatMap(response -> { assertKeyEquals(originalKey, response); return keyAsyncClient.updateKeyProperties(response.getProperties() .setExpiresOn(updatedKey.getExpiresOn())); })) .assertNext(response -> assertKeyEquals(updatedKey, response)) .verifyComplete()); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey) .flatMap(response -> { assertKeyEquals(originalKey, response); return keyAsyncClient.updateKeyProperties(response.getProperties() .setExpiresOn(updatedKey.getExpiresOn())); })) .assertNext(response -> assertKeyEquals(updatedKey, response)) .verifyComplete()); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((keyToSetAndGet) -> { StepVerifier.create(keyAsyncClient.createKey(keyToSetAndGet)) .assertNext(response -> assertKeyEquals(keyToSetAndGet, response)) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKey(keyToSetAndGet.getName())) .assertNext(response -> assertKeyEquals(keyToSetAndGet, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((keyWithOriginalValue, keyWithNewValue) -> { final KeyVaultKey keyVersionOne = keyAsyncClient.createKey(keyWithOriginalValue).block(); final KeyVaultKey keyVersionTwo = keyAsyncClient.createKey(keyWithNewValue).block(); StepVerifier.create(keyAsyncClient.getKey(keyWithOriginalValue.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithOriginalValue, response)) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKey(keyWithNewValue.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewValue, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.beginDeleteKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getDeletedKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = keyAsyncClient.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(keyAsyncClient.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(keyAsyncClient.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.backupKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(keyAsyncClient.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)) .verifyComplete(); byte[] backup = keyAsyncClient.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(keyAsyncClient.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode())) .verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(keyAsyncClient.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(keyAsyncClient.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)) .verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(keyAsyncClient.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (interceptorManager.isLiveMode()) { return; } listDeletedKeysRunner((keysToList) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keysToList.values()) { StepVerifier.create(keyAsyncClient.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keysToList.values()) { PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = keyAsyncClient.listDeletedKeys() .map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keysToList) -> { for (CreateKeyOptions key : keysToList.values()) { assertKeyEquals(key, keyAsyncClient.createKey(key).block()); } sleepInRecordMode(10000); keyAsyncClient.listPropertiesOfKeys().map(actualKey -> { if (keysToList.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keysToList.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keysToList.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keysToList.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(runManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(keyAsyncClient.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)) .verifyComplete(); String targetAttestationToken = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { targetAttestationToken = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(keyAsyncClient.releaseKey(keyToRelease.getName(), targetAttestationToken)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(testResourceNamer.randomName("nonExistentKey", 20))) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(keyName)) .assertNext(keyRotationPolicy -> { assertNotNull(keyRotationPolicy); assertNull(keyRotationPolicy.getId()); assertNull(keyRotationPolicy.getCreatedOn()); assertNull(keyRotationPolicy.getUpdatedOn()); assertNull(keyRotationPolicy.getExpiresIn()); assertEquals(1, keyRotationPolicy.getLifetimeActions().size()); assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getAction()); assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry()); assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate()); }).verifyComplete(); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @Disabled("Disable after https: public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicy) -> { StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), keyAsyncClient.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that an key rotation policy can be updated with all possible properties, then retrieves it. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicy) -> { StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), keyAsyncClient.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that a key can be rotated. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName)) .flatMap(createdKey -> Mono.zip(Mono.just(createdKey), keyAsyncClient.rotateKey(keyName)))) .assertNext(tuple -> { KeyVaultKey createdKey = tuple.getT1(); KeyVaultKey rotatedKey = tuple.getT2(); assertEquals(createdKey.getName(), rotatedKey.getName()); assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags()); }).verifyComplete(); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests * that cryptographic operations can be performed with said cryptography client. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyRunner((keyToCreate) -> { StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete(); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient(keyToCreate.getName()); assertNotNull(cryptographyAsyncClient); byte[] plaintext = "myPlaintext".getBytes(); StepVerifier.create(cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) .map(EncryptResult::getCipherText) .flatMap(ciphertext -> cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) .map(DecryptResult::getPlainText))) .assertNext(decryptedText -> assertArrayEquals(plaintext, decryptedText)) .verifyComplete(); }); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key and version using a * {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", "6A385B124DEF4096AF1361A85B16C204"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", ""); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", null); assertNotNull(cryptographyAsyncClient); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = keyAsyncClient.getDeletedKey(keyName).block(); } catch (ResourceNotFoundException ignored) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
I believe it was the PR. Adding `publishOn` does change the thread running the reactive stream which likely introduced a minor bit of delay causing this test to fail. That said, the design of this test has issues with timing given the subscribe and a non-deterministic delay in playback.
public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keysToList) -> { String keyName = null; for (CreateKeyOptions key : keysToList) { keyName = key.getName(); StepVerifier.create(keyAsyncClient.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)) .verifyComplete(); } sleepInRecordMode(30000); StepVerifier.create(keyAsyncClient.listPropertiesOfKeyVersions(keyName).collectList()) .assertNext(actualKeys -> assertEquals(keysToList.size(), actualKeys.size())) .verifyComplete(); }); }
.verifyComplete();
public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keysToList) -> { String keyName = null; for (CreateKeyOptions key : keysToList) { keyName = key.getName(); StepVerifier.create(keyAsyncClient.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)) .verifyComplete(); } sleepInRecordMode(30000); StepVerifier.create(keyAsyncClient.listPropertiesOfKeyVersions(keyName).collectList()) .assertNext(actualKeys -> assertEquals(keysToList.size(), actualKeys.size())) .verifyComplete(); }); }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient keyAsyncClient; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion, null); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion, String testTenantId) { HttpPipeline httpPipeline = getHttpPipeline(buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), testTenantId); KeyClientImpl implClient = spy(new KeyClientImpl(getEndpoint(), httpPipeline, serviceVersion)); if (interceptorManager.isPlaybackMode()) { when(implClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } keyAsyncClient = new KeyAsyncClient(implClient); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { BiFunction<HttpRequest, Context, Boolean> skipRequestFunction = (request, context) -> { String callerMethod = (String) context.getData("caller-method").orElse(""); return (callerMethod.contains("list") || callerMethod.contains("getKeys") || callerMethod.contains("getKeyVersions") || callerMethod.contains("delete") || callerMethod.contains("recover") || callerMethod.contains("Cryptography")); }; return new AssertingHttpClientBuilder(httpClient) .skipRequest(skipRequestFunction) .assertAsync() .build(); } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that a key can be created in the key vault while using a different tenant ID than the one that will be * provided in the authentication challenge. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyWithMultipleTenants(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); KeyVaultCredentialPolicy.clearCache(); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createRsaKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); final KeyType keyType; if (runManagedHsmTest) { keyType = KeyType.RSA_HSM; } else { keyType = KeyType.RSA; } StepVerifier.create(keyAsyncClient.createKey("", keyType)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyEmptyValueRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey) .flatMap(response -> { assertKeyEquals(originalKey, response); return keyAsyncClient.updateKeyProperties(response.getProperties() .setExpiresOn(updatedKey.getExpiresOn())); })) .assertNext(response -> assertKeyEquals(updatedKey, response)) .verifyComplete()); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey) .flatMap(response -> { assertKeyEquals(originalKey, response); return keyAsyncClient.updateKeyProperties(response.getProperties() .setExpiresOn(updatedKey.getExpiresOn())); })) .assertNext(response -> assertKeyEquals(updatedKey, response)) .verifyComplete()); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((keyToSetAndGet) -> { StepVerifier.create(keyAsyncClient.createKey(keyToSetAndGet)) .assertNext(response -> assertKeyEquals(keyToSetAndGet, response)) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKey(keyToSetAndGet.getName())) .assertNext(response -> assertKeyEquals(keyToSetAndGet, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((keyWithOriginalValue, keyWithNewValue) -> { final KeyVaultKey keyVersionOne = keyAsyncClient.createKey(keyWithOriginalValue).block(); final KeyVaultKey keyVersionTwo = keyAsyncClient.createKey(keyWithNewValue).block(); StepVerifier.create(keyAsyncClient.getKey(keyWithOriginalValue.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithOriginalValue, response)) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKey(keyWithNewValue.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewValue, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.beginDeleteKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getDeletedKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = keyAsyncClient.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(keyAsyncClient.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(keyAsyncClient.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.backupKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(keyAsyncClient.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)) .verifyComplete(); byte[] backup = keyAsyncClient.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(keyAsyncClient.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode())) .verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(keyAsyncClient.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(keyAsyncClient.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)) .verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(keyAsyncClient.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (interceptorManager.isLiveMode()) { return; } listDeletedKeysRunner((keysToList) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keysToList.values()) { StepVerifier.create(keyAsyncClient.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keysToList.values()) { PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = keyAsyncClient.listDeletedKeys() .map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keysToList) -> { for (CreateKeyOptions key : keysToList.values()) { assertKeyEquals(key, keyAsyncClient.createKey(key).block()); } sleepInRecordMode(10000); keyAsyncClient.listPropertiesOfKeys().map(actualKey -> { if (keysToList.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keysToList.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keysToList.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keysToList.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(runManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(keyAsyncClient.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)) .verifyComplete(); String targetAttestationToken = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { targetAttestationToken = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(keyAsyncClient.releaseKey(keyToRelease.getName(), targetAttestationToken)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(testResourceNamer.randomName("nonExistentKey", 20))) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(keyName)) .assertNext(keyRotationPolicy -> { assertNotNull(keyRotationPolicy); assertNull(keyRotationPolicy.getId()); assertNull(keyRotationPolicy.getCreatedOn()); assertNull(keyRotationPolicy.getUpdatedOn()); assertNull(keyRotationPolicy.getExpiresIn()); assertEquals(1, keyRotationPolicy.getLifetimeActions().size()); assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getAction()); assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry()); assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate()); }).verifyComplete(); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @Disabled("Disable after https: public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicy) -> { StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), keyAsyncClient.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that an key rotation policy can be updated with all possible properties, then retrieves it. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicy) -> { StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), keyAsyncClient.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that a key can be rotated. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName)) .flatMap(createdKey -> Mono.zip(Mono.just(createdKey), keyAsyncClient.rotateKey(keyName)))) .assertNext(tuple -> { KeyVaultKey createdKey = tuple.getT1(); KeyVaultKey rotatedKey = tuple.getT2(); assertEquals(createdKey.getName(), rotatedKey.getName()); assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags()); }).verifyComplete(); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests * that cryptographic operations can be performed with said cryptography client. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyRunner((keyToCreate) -> { StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete(); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient(keyToCreate.getName()); assertNotNull(cryptographyAsyncClient); byte[] plaintext = "myPlaintext".getBytes(); StepVerifier.create(cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) .map(EncryptResult::getCipherText) .flatMap(ciphertext -> cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) .map(DecryptResult::getPlainText))) .assertNext(decryptedText -> assertArrayEquals(plaintext, decryptedText)) .verifyComplete(); }); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key and version using a * {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", "6A385B124DEF4096AF1361A85B16C204"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", ""); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", null); assertNotNull(cryptographyAsyncClient); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = keyAsyncClient.getDeletedKey(keyName).block(); } catch (ResourceNotFoundException ignored) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient keyAsyncClient; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion, null); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion, String testTenantId) { HttpPipeline httpPipeline = getHttpPipeline(buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), testTenantId); KeyClientImpl implClient = spy(new KeyClientImpl(getEndpoint(), httpPipeline, serviceVersion)); if (interceptorManager.isPlaybackMode()) { when(implClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } keyAsyncClient = new KeyAsyncClient(implClient); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { BiFunction<HttpRequest, Context, Boolean> skipRequestFunction = (request, context) -> { String callerMethod = (String) context.getData("caller-method").orElse(""); return (callerMethod.contains("list") || callerMethod.contains("getKeys") || callerMethod.contains("getKeyVersions") || callerMethod.contains("delete") || callerMethod.contains("recover") || callerMethod.contains("Cryptography")); }; return new AssertingHttpClientBuilder(httpClient) .skipRequest(skipRequestFunction) .assertAsync() .build(); } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that a key can be created in the key vault while using a different tenant ID than the one that will be * provided in the authentication challenge. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyWithMultipleTenants(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); KeyVaultCredentialPolicy.clearCache(); createKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createRsaKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); final KeyType keyType; if (runManagedHsmTest) { keyType = KeyType.RSA_HSM; } else { keyType = KeyType.RSA; } StepVerifier.create(keyAsyncClient.createKey("", keyType)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyEmptyValueRunner((keyToCreate) -> StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey) .flatMap(response -> { assertKeyEquals(originalKey, response); return keyAsyncClient.updateKeyProperties(response.getProperties() .setExpiresOn(updatedKey.getExpiresOn())); })) .assertNext(response -> assertKeyEquals(updatedKey, response)) .verifyComplete()); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((originalKey, updatedKey) -> StepVerifier.create(keyAsyncClient.createKey(originalKey) .flatMap(response -> { assertKeyEquals(originalKey, response); return keyAsyncClient.updateKeyProperties(response.getProperties() .setExpiresOn(updatedKey.getExpiresOn())); })) .assertNext(response -> assertKeyEquals(updatedKey, response)) .verifyComplete()); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((keyToSetAndGet) -> { StepVerifier.create(keyAsyncClient.createKey(keyToSetAndGet)) .assertNext(response -> assertKeyEquals(keyToSetAndGet, response)) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKey(keyToSetAndGet.getName())) .assertNext(response -> assertKeyEquals(keyToSetAndGet, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((keyWithOriginalValue, keyWithNewValue) -> { final KeyVaultKey keyVersionOne = keyAsyncClient.createKey(keyWithOriginalValue).block(); final KeyVaultKey keyVersionTwo = keyAsyncClient.createKey(keyWithNewValue).block(); StepVerifier.create(keyAsyncClient.getKey(keyWithOriginalValue.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithOriginalValue, response)) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKey(keyWithNewValue.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewValue, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.beginDeleteKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getDeletedKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = keyAsyncClient.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(keyAsyncClient.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(keyAsyncClient.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.backupKey("non-existing")) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(keyAsyncClient.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)) .verifyComplete(); byte[] backup = keyAsyncClient.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(keyAsyncClient.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode())) .verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(keyAsyncClient.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(keyAsyncClient.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(e -> assertRestException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(keyAsyncClient.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)) .verifyComplete(); PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(keyAsyncClient.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (interceptorManager.isLiveMode()) { return; } listDeletedKeysRunner((keysToList) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keysToList.values()) { StepVerifier.create(keyAsyncClient.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keysToList.values()) { PollerFlux<DeletedKey, Void> poller = keyAsyncClient.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = keyAsyncClient.listDeletedKeys() .map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keysToList) -> { for (CreateKeyOptions key : keysToList.values()) { assertKeyEquals(key, keyAsyncClient.createKey(key).block()); } sleepInRecordMode(10000); keyAsyncClient.listPropertiesOfKeys().map(actualKey -> { if (keysToList.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keysToList.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keysToList.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keysToList.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(runManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(keyAsyncClient.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)) .verifyComplete(); String targetAttestationToken = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { targetAttestationToken = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(keyAsyncClient.releaseKey(keyToRelease.getName(), targetAttestationToken)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void getKeyRotationPolicyOfNonExistentKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(testResourceNamer.randomName("nonExistentKey", 20))) .verifyErrorSatisfies(e -> assertRestException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void getKeyRotationPolicyWithNoPolicySet(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.getKeyRotationPolicy(keyName)) .assertNext(keyRotationPolicy -> { assertNotNull(keyRotationPolicy); assertNull(keyRotationPolicy.getId()); assertNull(keyRotationPolicy.getCreatedOn()); assertNull(keyRotationPolicy.getUpdatedOn()); assertNull(keyRotationPolicy.getExpiresIn()); assertEquals(1, keyRotationPolicy.getLifetimeActions().size()); assertEquals(KeyRotationPolicyAction.NOTIFY, keyRotationPolicy.getLifetimeActions().get(0).getAction()); assertEquals("P30D", keyRotationPolicy.getLifetimeActions().get(0).getTimeBeforeExpiry()); assertNull(keyRotationPolicy.getLifetimeActions().get(0).getTimeAfterCreate()); }).verifyComplete(); } /** * Tests that fetching the key rotation policy of a non-existent key throws. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @Disabled("Disable after https: public void updateGetKeyRotationPolicyWithMinimumProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithMinimumPropertiesRunner((keyName, keyRotationPolicy) -> { StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), keyAsyncClient.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that an key rotation policy can be updated with all possible properties, then retrieves it. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void updateGetKeyRotationPolicyWithAllProperties(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); updateGetKeyRotationPolicyWithAllPropertiesRunner((keyName, keyRotationPolicy) -> { StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName))) .assertNext(Assertions::assertNotNull) .verifyComplete(); StepVerifier.create(keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) .flatMap(updatedKeyRotationPolicy -> Mono.zip(Mono.just(updatedKeyRotationPolicy), keyAsyncClient.getKeyRotationPolicy(keyName)))) .assertNext(tuple -> assertKeyVaultRotationPolicyEquals(tuple.getT1(), tuple.getT2())) .verifyComplete(); }); } /** * Tests that a key can be rotated. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @DisabledIfSystemProperty(named = "IS_SKIP_ROTATION_POLICY_TEST", matches = "true") public void rotateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(!isHsmEnabled); createKeyAsyncClient(httpClient, serviceVersion); String keyName = testResourceNamer.randomName("rotateKey", 20); StepVerifier.create(keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName)) .flatMap(createdKey -> Mono.zip(Mono.just(createdKey), keyAsyncClient.rotateKey(keyName)))) .assertNext(tuple -> { KeyVaultKey createdKey = tuple.getT1(); KeyVaultKey rotatedKey = tuple.getT2(); assertEquals(createdKey.getName(), rotatedKey.getName()); assertEquals(createdKey.getProperties().getTags(), rotatedKey.getProperties().getTags()); }).verifyComplete(); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyClient} can be created for a given key using a {@link KeyClient}. Also tests * that cryptographic operations can be performed with said cryptography client. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientAndEncryptDecrypt(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createKeyRunner((keyToCreate) -> { StepVerifier.create(keyAsyncClient.createKey(keyToCreate)) .assertNext(response -> assertKeyEquals(keyToCreate, response)) .verifyComplete(); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient(keyToCreate.getName()); assertNotNull(cryptographyAsyncClient); byte[] plaintext = "myPlaintext".getBytes(); StepVerifier.create(cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) .map(EncryptResult::getCipherText) .flatMap(ciphertext -> cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) .map(DecryptResult::getPlainText))) .assertNext(decryptedText -> assertArrayEquals(plaintext, decryptedText)) .verifyComplete(); }); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key and version using a * {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", "6A385B124DEF4096AF1361A85B16C204"); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithEmptyKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", ""); assertNotNull(cryptographyAsyncClient); } /** * Tests that a {@link CryptographyAsyncClient} can be created for a given key using a {@link KeyAsyncClient}. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCryptographyAsyncClientWithNullKeyVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); CryptographyAsyncClient cryptographyAsyncClient = keyAsyncClient.getCryptographyAsyncClient("myKey", null); assertNotNull(cryptographyAsyncClient); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = keyAsyncClient.getDeletedKey(keyName).block(); } catch (ResourceNotFoundException ignored) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
only the first got updated in this one
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<String> documents = Arrays.asList( "The food was delicious and there were wonderful staff.", "The pitot tube is used to measure airspeed." ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true).setModelVersion("latest"); ExtractKeyPhrasesResultCollection keyPhrasesBatchResultCollection = client.extractKeyPhrasesBatch(documents, "en", requestOptions); System.out.printf("Results of \"Key Phrases Extraction\" Model, version: %s%n", keyPhrasesBatchResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = keyPhrasesBatchResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %d, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (ExtractKeyPhraseResult extractKeyPhraseResult : keyPhrasesBatchResultCollection) { System.out.printf("%nText = %s%n", documents.get(counter.getAndIncrement())); if (extractKeyPhraseResult.isError()) { System.out.printf("Cannot extract key phrases. Error: %s%n", extractKeyPhraseResult.getError().getMessage()); } else { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrases -> System.out.printf("\t%s.%n", keyPhrases)); } } }
System.out.printf("Documents statistics: document count = %d, erroneous document count = %s, transaction count = %s, valid document count = %s.%n",
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<String> documents = Arrays.asList( "The food was delicious and there were wonderful staff.", "The pitot tube is used to measure airspeed." ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true).setModelVersion("latest"); ExtractKeyPhrasesResultCollection keyPhrasesBatchResultCollection = client.extractKeyPhrasesBatch(documents, "en", requestOptions); System.out.printf("Results of \"Key Phrases Extraction\" Model, version: %s%n", keyPhrasesBatchResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = keyPhrasesBatchResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %d, erroneous document count = %d, transaction count = %d, valid document count = %d.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (ExtractKeyPhraseResult extractKeyPhraseResult : keyPhrasesBatchResultCollection) { System.out.printf("%nText = %s%n", documents.get(counter.getAndIncrement())); if (extractKeyPhraseResult.isError()) { System.out.printf("Cannot extract key phrases. Error: %s%n", extractKeyPhraseResult.getError().getMessage()); } else { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrases -> System.out.printf("\t%s.%n", keyPhrases)); } } }
class ExtractKeyPhrasesBatchStringDocuments { /** * Main method to invoke this demo about how to extract the key phrases of {@code String} documents. * * @param args Unused arguments to the program. */ }
class ExtractKeyPhrasesBatchStringDocuments { /** * Main method to invoke this demo about how to extract the key phrases of {@code String} documents. * * @param args Unused arguments to the program. */ }
same here
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true).setModelVersion("latest"); RecognizeLinkedEntitiesResultCollection linkedEntitiesResultCollection = client.recognizeLinkedEntitiesBatch(documents, "en", requestOptions); System.out.printf("Results of \"Linked Entities Recognition\" Model, version: %s%n", linkedEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = linkedEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %d, erroneous document count = %s, transaction count = %s, valid document count = %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (RecognizeLinkedEntitiesResult entitiesResult : linkedEntitiesResultCollection) { System.out.printf("%nText = %s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize linked entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("\tName: %s, entity ID in data source: %s, URL: %s, data source: %s," + " Bing Entity Search API ID: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource(), linkedEntity.getBingEntitySearchApiId()); linkedEntity.getMatches().forEach(entityMatch -> System.out.printf( "\tMatched entity: %s, confidence score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } } }
System.out.printf("Documents statistics: document count = %d, erroneous document count = %s, transaction count = %s, valid document count = %s.%n",
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true).setModelVersion("latest"); RecognizeLinkedEntitiesResultCollection linkedEntitiesResultCollection = client.recognizeLinkedEntitiesBatch(documents, "en", requestOptions); System.out.printf("Results of \"Linked Entities Recognition\" Model, version: %s%n", linkedEntitiesResultCollection.getModelVersion()); TextDocumentBatchStatistics batchStatistics = linkedEntitiesResultCollection.getStatistics(); System.out.printf("Documents statistics: document count = %d, erroneous document count = %d, transaction count = %d, valid document count = %d.%n", batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); AtomicInteger counter = new AtomicInteger(); for (RecognizeLinkedEntitiesResult entitiesResult : linkedEntitiesResultCollection) { System.out.printf("%nText = %s%n", documents.get(counter.getAndIncrement())); if (entitiesResult.isError()) { System.out.printf("Cannot recognize linked entities. Error: %s%n", entitiesResult.getError().getMessage()); } else { entitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("\tName: %s, entity ID in data source: %s, URL: %s, data source: %s," + " Bing Entity Search API ID: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource(), linkedEntity.getBingEntitySearchApiId()); linkedEntity.getMatches().forEach(entityMatch -> System.out.printf( "\tMatched entity: %s, confidence score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } } }
class RecognizeLinkedEntitiesBatchStringDocuments { /** * Main method to invoke this demo about how to recognize the linked entities of {@code String} documents. * * @param args Unused arguments to the program. */ }
class RecognizeLinkedEntitiesBatchStringDocuments { /** * Main method to invoke this demo about how to recognize the linked entities of {@code String} documents. * * @param args Unused arguments to the program. */ }
fakeCredentialPlaceholder -> fakeCredential ?
public void testValidUserCredential() throws Exception { String username = "testuser"; String password = "fakeCredentialPlaceholder"; String token1 = "token1"; String token2 = "token2"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: TokenRequestContext request2 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request1, username, password)).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalToken(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).password(password).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(accessToken -> token1.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); StepVerifier.create(credential.getToken(request2)) .expectNextMatches(accessToken -> token2.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); Assert.assertNotNull(identityClientMock); } try (MockedConstruction<IdentitySyncClient> identityClientMock = mockConstruction(IdentitySyncClient.class, (identitySyncClient, context) -> { when(identitySyncClient.authenticateWithUsernamePassword(request1, username, password)).thenReturn(TestUtils.getMockMsalTokenSync(token1, expiresAt)); when(identitySyncClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalTokenSync(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).password(password).build(); AccessToken accessToken = credential.getTokenSync(request1); Assert.assertEquals(token1, accessToken.getToken()); Assert.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); accessToken = credential.getTokenSync(request2); Assert.assertEquals(token2, accessToken.getToken()); Assert.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); Assert.assertNotNull(identityClientMock); } }
String password = "fakeCredentialPlaceholder";
public void testValidUserCredential() throws Exception { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; String token1 = "token1"; String token2 = "token2"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: TokenRequestContext request2 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request1, fakeUsernamePlaceholder, fakePasswordPlaceholder)).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalToken(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(accessToken -> token1.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); StepVerifier.create(credential.getToken(request2)) .expectNextMatches(accessToken -> token2.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); Assert.assertNotNull(identityClientMock); } try (MockedConstruction<IdentitySyncClient> identityClientMock = mockConstruction(IdentitySyncClient.class, (identitySyncClient, context) -> { when(identitySyncClient.authenticateWithUsernamePassword(request1, fakeUsernamePlaceholder, fakePasswordPlaceholder)).thenReturn(TestUtils.getMockMsalTokenSync(token1, expiresAt)); when(identitySyncClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalTokenSync(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).build(); AccessToken accessToken = credential.getTokenSync(request1); Assert.assertEquals(token1, accessToken.getToken()); Assert.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); accessToken = credential.getTokenSync(request2); Assert.assertEquals(token2, accessToken.getToken()); Assert.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); Assert.assertNotNull(identityClientMock); } }
class UsernamePasswordCredentialTest { private final String clientId = UUID.randomUUID().toString(); @Test @Test public void testInvalidUserCredential() throws Exception { String username = "testuser"; String badPassword = "Password"; TokenRequestContext request = new TokenRequestContext().addScopes("https: try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request, username, badPassword)).thenThrow(new MsalServiceException("bad credential", "BadCredential")); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); when(identityClient.getIdentityClientOptions()).thenReturn(new IdentityClientOptions()); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).password(badPassword).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(t -> t instanceof MsalServiceException && "bad credential".equals(t.getMessage())) .verify(); Assert.assertNotNull(identityClientMock); } try (MockedConstruction<IdentitySyncClient> identityClientMock = mockConstruction(IdentitySyncClient.class, (identitySyncClient, context) -> { when(identitySyncClient.authenticateWithUsernamePassword(request, username, badPassword)).thenThrow(new MsalServiceException("bad credential", "BadCredential")); when(identitySyncClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); when(identitySyncClient.getIdentityClientOptions()).thenReturn(new IdentityClientOptions()); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).password(badPassword).build(); try { credential.getTokenSync(request); } catch (Exception e) { Assert.assertTrue(e instanceof MsalServiceException && "bad credential".equals(e.getMessage())); } Assert.assertNotNull(identityClientMock); } } @Test public void testInvalidParameters() throws Exception { String username = "testuser"; String password = "fakeCredentialPlaceholder"; String token1 = "token1"; TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request, username, password)).thenReturn(TestUtils.getMockMsalToken(token1, expiresOn)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); })) { try { new UsernamePasswordCredentialBuilder().username(username).password(password).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("clientId")); } try { new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("password")); } try { new UsernamePasswordCredentialBuilder().clientId(clientId).password(password).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("username")); } Assert.assertNotNull(identityClientMock); } } @Test public void testValidAuthenticate() throws Exception { String username = "testuser"; String password = "fakeCredentialPlaceholder"; String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(eq(request1), eq(username), eq(password))) .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId) .username(username).password(password).build(); StepVerifier.create(credential.authenticate(request1)) .expectNextMatches(authenticationRecord -> authenticationRecord.getAuthority() .equals("http: && authenticationRecord.getUsername().equals("testuser") && authenticationRecord.getHomeAccountId() != null) .verifyComplete(); Assert.assertNotNull(identityClientMock); } } @Test public void testAdditionalTenantNoImpact() { String username = "testuser"; String password = "fakeCredentialPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().username(username).password(password) .clientId(clientId).additionallyAllowedTenants("RANDOM").build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e.getCause() instanceof MsalServiceException) .verify(); } @Test public void testInvalidMultiTenantAuth() { String username = "testuser"; String password = "fakeCredentialPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().tenantId("tenant").username(username).password(password) .clientId(clientId).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e instanceof ClientAuthenticationException && (e.getCause().getMessage().startsWith("The current credential is not configured to"))) .verify(); } @Test public void testValidMultiTenantAuth() { String username = "testuser"; String password = "fakeCredentialPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().username(username).password(password).tenantId("tenant") .clientId(clientId).additionallyAllowedTenants(IdentityUtil.ALL_TENANTS).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e.getCause() instanceof MsalServiceException) .verify(); } }
class UsernamePasswordCredentialTest { private final String clientId = UUID.randomUUID().toString(); @Test @Test public void testInvalidUserCredential() throws Exception { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String badPassword = "Password"; TokenRequestContext request = new TokenRequestContext().addScopes("https: try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request, fakeUsernamePlaceholder, badPassword)).thenThrow(new MsalServiceException("bad credential", "BadCredential")); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); when(identityClient.getIdentityClientOptions()).thenReturn(new IdentityClientOptions()); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).password(badPassword).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(t -> t instanceof MsalServiceException && "bad credential".equals(t.getMessage())) .verify(); Assert.assertNotNull(identityClientMock); } try (MockedConstruction<IdentitySyncClient> identityClientMock = mockConstruction(IdentitySyncClient.class, (identitySyncClient, context) -> { when(identitySyncClient.authenticateWithUsernamePassword(request, fakeUsernamePlaceholder, badPassword)).thenThrow(new MsalServiceException("bad credential", "BadCredential")); when(identitySyncClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); when(identitySyncClient.getIdentityClientOptions()).thenReturn(new IdentityClientOptions()); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).password(badPassword).build(); try { credential.getTokenSync(request); } catch (Exception e) { Assert.assertTrue(e instanceof MsalServiceException && "bad credential".equals(e.getMessage())); } Assert.assertNotNull(identityClientMock); } } @Test public void testInvalidParameters() throws Exception { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; String token1 = "token1"; TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request, fakeUsernamePlaceholder, fakePasswordPlaceholder)).thenReturn(TestUtils.getMockMsalToken(token1, expiresOn)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); })) { try { new UsernamePasswordCredentialBuilder().username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("clientId")); } try { new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("password")); } try { new UsernamePasswordCredentialBuilder().clientId(clientId).password(fakePasswordPlaceholder).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("username")); } Assert.assertNotNull(identityClientMock); } } @Test public void testValidAuthenticate() throws Exception { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(eq(request1), eq(fakeUsernamePlaceholder), eq(fakePasswordPlaceholder))) .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId) .username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).build(); StepVerifier.create(credential.authenticate(request1)) .expectNextMatches(authenticationRecord -> authenticationRecord.getAuthority() .equals("http: && authenticationRecord.getUsername().equals("testuser") && authenticationRecord.getHomeAccountId() != null) .verifyComplete(); Assert.assertNotNull(identityClientMock); } } @Test public void testAdditionalTenantNoImpact() { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder) .clientId(clientId).additionallyAllowedTenants("RANDOM").build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e.getCause() instanceof MsalServiceException) .verify(); } @Test public void testInvalidMultiTenantAuth() { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().tenantId("tenant").username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder) .clientId(clientId).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e instanceof ClientAuthenticationException && (e.getCause().getMessage().startsWith("The current credential is not configured to"))) .verify(); } @Test public void testValidMultiTenantAuth() { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).tenantId("tenant") .clientId(clientId).additionallyAllowedTenants(IdentityUtil.ALL_TENANTS).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e.getCause() instanceof MsalServiceException) .verify(); } }
Credscan will skip the check for the keyword `placeholder`. Use the string contains 'placeholder' in src code is better than suppress `fakeCredential` in CredScanSuppression file as it suppresses the specific place instead of every occurrence in repo (We have the guidance to suppress as specific as possible).
public void testValidUserCredential() throws Exception { String username = "testuser"; String password = "fakeCredentialPlaceholder"; String token1 = "token1"; String token2 = "token2"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: TokenRequestContext request2 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request1, username, password)).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalToken(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).password(password).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(accessToken -> token1.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); StepVerifier.create(credential.getToken(request2)) .expectNextMatches(accessToken -> token2.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); Assert.assertNotNull(identityClientMock); } try (MockedConstruction<IdentitySyncClient> identityClientMock = mockConstruction(IdentitySyncClient.class, (identitySyncClient, context) -> { when(identitySyncClient.authenticateWithUsernamePassword(request1, username, password)).thenReturn(TestUtils.getMockMsalTokenSync(token1, expiresAt)); when(identitySyncClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalTokenSync(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).password(password).build(); AccessToken accessToken = credential.getTokenSync(request1); Assert.assertEquals(token1, accessToken.getToken()); Assert.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); accessToken = credential.getTokenSync(request2); Assert.assertEquals(token2, accessToken.getToken()); Assert.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); Assert.assertNotNull(identityClientMock); } }
String password = "fakeCredentialPlaceholder";
public void testValidUserCredential() throws Exception { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; String token1 = "token1"; String token2 = "token2"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: TokenRequestContext request2 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request1, fakeUsernamePlaceholder, fakePasswordPlaceholder)).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalToken(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).build(); StepVerifier.create(credential.getToken(request1)) .expectNextMatches(accessToken -> token1.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); StepVerifier.create(credential.getToken(request2)) .expectNextMatches(accessToken -> token2.equals(accessToken.getToken()) && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()) .verifyComplete(); Assert.assertNotNull(identityClientMock); } try (MockedConstruction<IdentitySyncClient> identityClientMock = mockConstruction(IdentitySyncClient.class, (identitySyncClient, context) -> { when(identitySyncClient.authenticateWithUsernamePassword(request1, fakeUsernamePlaceholder, fakePasswordPlaceholder)).thenReturn(TestUtils.getMockMsalTokenSync(token1, expiresAt)); when(identitySyncClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> { TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { return TestUtils.getMockMsalTokenSync(token2, expiresAt); } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { return Mono.error(new UnsupportedOperationException("nothing cached")); } else { throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument)); } }); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).build(); AccessToken accessToken = credential.getTokenSync(request1); Assert.assertEquals(token1, accessToken.getToken()); Assert.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); accessToken = credential.getTokenSync(request2); Assert.assertEquals(token2, accessToken.getToken()); Assert.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); Assert.assertNotNull(identityClientMock); } }
class UsernamePasswordCredentialTest { private final String clientId = UUID.randomUUID().toString(); @Test @Test public void testInvalidUserCredential() throws Exception { String username = "testuser"; String badPassword = "Password"; TokenRequestContext request = new TokenRequestContext().addScopes("https: try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request, username, badPassword)).thenThrow(new MsalServiceException("bad credential", "BadCredential")); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); when(identityClient.getIdentityClientOptions()).thenReturn(new IdentityClientOptions()); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).password(badPassword).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(t -> t instanceof MsalServiceException && "bad credential".equals(t.getMessage())) .verify(); Assert.assertNotNull(identityClientMock); } try (MockedConstruction<IdentitySyncClient> identityClientMock = mockConstruction(IdentitySyncClient.class, (identitySyncClient, context) -> { when(identitySyncClient.authenticateWithUsernamePassword(request, username, badPassword)).thenThrow(new MsalServiceException("bad credential", "BadCredential")); when(identitySyncClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); when(identitySyncClient.getIdentityClientOptions()).thenReturn(new IdentityClientOptions()); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).password(badPassword).build(); try { credential.getTokenSync(request); } catch (Exception e) { Assert.assertTrue(e instanceof MsalServiceException && "bad credential".equals(e.getMessage())); } Assert.assertNotNull(identityClientMock); } } @Test public void testInvalidParameters() throws Exception { String username = "testuser"; String password = "fakeCredentialPlaceholder"; String token1 = "token1"; TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request, username, password)).thenReturn(TestUtils.getMockMsalToken(token1, expiresOn)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); })) { try { new UsernamePasswordCredentialBuilder().username(username).password(password).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("clientId")); } try { new UsernamePasswordCredentialBuilder().clientId(clientId).username(username).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("password")); } try { new UsernamePasswordCredentialBuilder().clientId(clientId).password(password).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("username")); } Assert.assertNotNull(identityClientMock); } } @Test public void testValidAuthenticate() throws Exception { String username = "testuser"; String password = "fakeCredentialPlaceholder"; String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(eq(request1), eq(username), eq(password))) .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId) .username(username).password(password).build(); StepVerifier.create(credential.authenticate(request1)) .expectNextMatches(authenticationRecord -> authenticationRecord.getAuthority() .equals("http: && authenticationRecord.getUsername().equals("testuser") && authenticationRecord.getHomeAccountId() != null) .verifyComplete(); Assert.assertNotNull(identityClientMock); } } @Test public void testAdditionalTenantNoImpact() { String username = "testuser"; String password = "fakeCredentialPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().username(username).password(password) .clientId(clientId).additionallyAllowedTenants("RANDOM").build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e.getCause() instanceof MsalServiceException) .verify(); } @Test public void testInvalidMultiTenantAuth() { String username = "testuser"; String password = "fakeCredentialPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().tenantId("tenant").username(username).password(password) .clientId(clientId).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e instanceof ClientAuthenticationException && (e.getCause().getMessage().startsWith("The current credential is not configured to"))) .verify(); } @Test public void testValidMultiTenantAuth() { String username = "testuser"; String password = "fakeCredentialPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().username(username).password(password).tenantId("tenant") .clientId(clientId).additionallyAllowedTenants(IdentityUtil.ALL_TENANTS).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e.getCause() instanceof MsalServiceException) .verify(); } }
class UsernamePasswordCredentialTest { private final String clientId = UUID.randomUUID().toString(); @Test @Test public void testInvalidUserCredential() throws Exception { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String badPassword = "Password"; TokenRequestContext request = new TokenRequestContext().addScopes("https: try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request, fakeUsernamePlaceholder, badPassword)).thenThrow(new MsalServiceException("bad credential", "BadCredential")); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); when(identityClient.getIdentityClientOptions()).thenReturn(new IdentityClientOptions()); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).password(badPassword).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(t -> t instanceof MsalServiceException && "bad credential".equals(t.getMessage())) .verify(); Assert.assertNotNull(identityClientMock); } try (MockedConstruction<IdentitySyncClient> identityClientMock = mockConstruction(IdentitySyncClient.class, (identitySyncClient, context) -> { when(identitySyncClient.authenticateWithUsernamePassword(request, fakeUsernamePlaceholder, badPassword)).thenThrow(new MsalServiceException("bad credential", "BadCredential")); when(identitySyncClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); when(identitySyncClient.getIdentityClientOptions()).thenReturn(new IdentityClientOptions()); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).password(badPassword).build(); try { credential.getTokenSync(request); } catch (Exception e) { Assert.assertTrue(e instanceof MsalServiceException && "bad credential".equals(e.getMessage())); } Assert.assertNotNull(identityClientMock); } } @Test public void testInvalidParameters() throws Exception { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; String token1 = "token1"; TokenRequestContext request = new TokenRequestContext().addScopes("https: OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(request, fakeUsernamePlaceholder, fakePasswordPlaceholder)).thenReturn(TestUtils.getMockMsalToken(token1, expiresOn)); when(identityClient.authenticateWithPublicClientCache(any(), any())) .thenAnswer(invocation -> Mono.error(new UnsupportedOperationException("nothing cached"))); })) { try { new UsernamePasswordCredentialBuilder().username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("clientId")); } try { new UsernamePasswordCredentialBuilder().clientId(clientId).username(fakeUsernamePlaceholder).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("password")); } try { new UsernamePasswordCredentialBuilder().clientId(clientId).password(fakePasswordPlaceholder).build(); fail(); } catch (IllegalArgumentException e) { Assert.assertTrue(e.getMessage().contains("username")); } Assert.assertNotNull(identityClientMock); } } @Test public void testValidAuthenticate() throws Exception { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; String token1 = "token1"; TokenRequestContext request1 = new TokenRequestContext().addScopes("https: OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); try (MockedConstruction<IdentityClient> identityClientMock = mockConstruction(IdentityClient.class, (identityClient, context) -> { when(identityClient.authenticateWithUsernamePassword(eq(request1), eq(fakeUsernamePlaceholder), eq(fakePasswordPlaceholder))) .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); })) { UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().clientId(clientId) .username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).build(); StepVerifier.create(credential.authenticate(request1)) .expectNextMatches(authenticationRecord -> authenticationRecord.getAuthority() .equals("http: && authenticationRecord.getUsername().equals("testuser") && authenticationRecord.getHomeAccountId() != null) .verifyComplete(); Assert.assertNotNull(identityClientMock); } } @Test public void testAdditionalTenantNoImpact() { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder) .clientId(clientId).additionallyAllowedTenants("RANDOM").build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e.getCause() instanceof MsalServiceException) .verify(); } @Test public void testInvalidMultiTenantAuth() { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().tenantId("tenant").username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder) .clientId(clientId).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e instanceof ClientAuthenticationException && (e.getCause().getMessage().startsWith("The current credential is not configured to"))) .verify(); } @Test public void testValidMultiTenantAuth() { String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; String fakePasswordPlaceholder = "fakePasswordPlaceholder"; TokenRequestContext request = new TokenRequestContext().addScopes("https: .setTenantId("newTenant"); UsernamePasswordCredential credential = new UsernamePasswordCredentialBuilder().username(fakeUsernamePlaceholder).password(fakePasswordPlaceholder).tenantId("tenant") .clientId(clientId).additionallyAllowedTenants(IdentityUtil.ALL_TENANTS).build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e.getCause() instanceof MsalServiceException) .verify(); } }
bug was in retry logic
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (providers == null) { return next.process(); } return next.clone().process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( body -> { String bodyStr = new String(body, StandardCharsets.UTF_8); SerializerAdapter jacksonAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); ManagementError managementError; try { managementError = jacksonAdapter.deserialize( bodyStr, ManagementError.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.just(bufferedResponse); } if (managementError != null && MISSING_SUBSCRIPTION_REGISTRATION.equals(managementError.getCode())) { String resourceNamespace = null; if (managementError.getDetails() != null) { resourceNamespace = managementError.getDetails().stream() .filter(d -> MISSING_SUBSCRIPTION_REGISTRATION.equals(d.getCode())) .map(ManagementError::getTarget) .findFirst().orElse(null); } if (resourceNamespace == null) { Pattern providerPattern = Pattern.compile(".*'(.*)'"); Matcher providerMatcher = providerPattern.matcher(managementError.getMessage()); if (!providerMatcher.find()) { return Mono.just(bufferedResponse); } resourceNamespace = providerMatcher.group(1); } return registerProviderUntilSuccess(resourceNamespace) .then(Mono.just(bufferedResponse)) .onErrorReturn(bufferedResponse) .then(next.clone().process()); } return Mono.just(bufferedResponse); } ); } return Mono.just(response); } ); }
.then(next.clone().process());
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (providers == null) { return next.process(); } return next.clone().process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( body -> { String bodyStr = new String(body, StandardCharsets.UTF_8); SerializerAdapter jacksonAdapter = SerializerFactory.createDefaultManagementSerializerAdapter(); ManagementError managementError; try { managementError = jacksonAdapter.deserialize( bodyStr, ManagementError.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.just(bufferedResponse); } if (managementError != null && MISSING_SUBSCRIPTION_REGISTRATION.equals(managementError.getCode())) { String resourceNamespace = null; if (managementError.getDetails() != null) { resourceNamespace = managementError.getDetails().stream() .filter(d -> MISSING_SUBSCRIPTION_REGISTRATION.equals(d.getCode()) && d.getTarget() != null) .map(ManagementError::getTarget) .findFirst().orElse(null); } if (resourceNamespace == null) { Pattern providerPattern = Pattern.compile(".*'(.*)'"); Matcher providerMatcher = providerPattern.matcher(managementError.getMessage()); if (!providerMatcher.find()) { return Mono.just(bufferedResponse); } resourceNamespace = providerMatcher.group(1); } return registerProviderUntilSuccess(resourceNamespace) .then(Mono.just(bufferedResponse)) .onErrorReturn(bufferedResponse) .then(next.clone().process()); } return Mono.just(bufferedResponse); } ); } return Mono.just(response); } ); }
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private Providers providers; /** * Initialize a provider registration policy to automatically register the provider. */ public ProviderRegistrationPolicy() { } /** * Initialize a provider registration policy to automatically register the provider. * @param resourceManager the Resource Manager that provider providers endpoint */ public ProviderRegistrationPolicy(ResourceManager resourceManager) { providers = resourceManager.providers(); } /** * Initialize a provider registration policy to automatically register the provider. * @param providers the providers endpoint */ public ProviderRegistrationPolicy(Providers providers) { this.providers = providers; } /** * Sets the providers endpoint after initialized * @param providers the providers endpoint */ public void setProviders(Providers providers) { this.providers = providers; } /** * @return the providers endpoint contained in policy */ public Providers getProviders() { return providers; } private boolean isResponseSuccessful(HttpResponse response) { return response.getStatusCode() >= 200 && response.getStatusCode() < 300; } @Override private Mono<Void> registerProviderUntilSuccess(String namespace) { return providers.registerAsync(namespace) .flatMap( provider -> { if (isProviderRegistered(provider)) { return Mono.empty(); } return providers.getByNameAsync(namespace) .flatMap(this::checkProviderRegistered) .retryWhen(Retry .fixedDelay(30, ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(10))) .filter(ProviderUnregisteredException.class::isInstance)); } ); } private Mono<Void> checkProviderRegistered(Provider provider) throws ProviderUnregisteredException { if (isProviderRegistered(provider)) { return Mono.empty(); } return Mono.error(new ProviderUnregisteredException()); } private boolean isProviderRegistered(Provider provider) { return "Registered".equalsIgnoreCase(provider.registrationState()); } private static class ProviderUnregisteredException extends RuntimeException { } }
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private Providers providers; /** * Initialize a provider registration policy to automatically register the provider. */ public ProviderRegistrationPolicy() { } /** * Initialize a provider registration policy to automatically register the provider. * @param resourceManager the Resource Manager that provider providers endpoint */ public ProviderRegistrationPolicy(ResourceManager resourceManager) { providers = resourceManager.providers(); } /** * Initialize a provider registration policy to automatically register the provider. * @param providers the providers endpoint */ public ProviderRegistrationPolicy(Providers providers) { this.providers = providers; } /** * Sets the providers endpoint after initialized * @param providers the providers endpoint */ public void setProviders(Providers providers) { this.providers = providers; } /** * @return the providers endpoint contained in policy */ public Providers getProviders() { return providers; } private boolean isResponseSuccessful(HttpResponse response) { return response.getStatusCode() >= 200 && response.getStatusCode() < 300; } @Override private Mono<Void> registerProviderUntilSuccess(String namespace) { return providers.registerAsync(namespace) .flatMap( provider -> { if (isProviderRegistered(provider)) { return Mono.empty(); } return providers.getByNameAsync(namespace) .flatMap(this::checkProviderRegistered) .retryWhen(Retry .fixedDelay(30, ResourceManagerUtils.InternalRuntimeContext.getDelayDuration(Duration.ofSeconds(10))) .filter(ProviderUnregisteredException.class::isInstance)); } ); } private Mono<Void> checkProviderRegistered(Provider provider) throws ProviderUnregisteredException { if (isProviderRegistered(provider)) { return Mono.empty(); } return Mono.error(new ProviderUnregisteredException()); } private boolean isProviderRegistered(Provider provider) { return "Registered".equalsIgnoreCase(provider.registrationState()); } private static class ProviderUnregisteredException extends RuntimeException { } }
seems working fine. can you add basic logging so we can see API calls in log? e.g. https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/mediaservices/azure-resourcemanager-mediaservices/src/test/java/com/azure/resourcemanager/mediaservices/MediaServicesTests.java#L53
public void prepareTests() { setupCredential(); setupProfile(); resourceGroupName = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); loadTestManager = LoadTestManager .configure() .authenticate(credential, profile); }
.configure()
public void prepareTests() { setupCredential(); setupProfile(); resourceGroupName = Configuration.getGlobalConfiguration().get("AZURE_RESOURCE_GROUP_NAME"); loadTestManager = LoadTestManager .configure() .authenticate(credential, profile); }
class TestOrchestrator extends TestBase { private static final Random RANDOM = new Random(); private static final Region LOCATION = Region.US_WEST2; private static final String RESOURCE_NAME = "loadtest-resource" + RANDOM.nextInt(1000); private static final String QUOTA_BUCKET_NAME = "maxEngineInstancesPerTestRun"; private DefaultAzureCredential credential; private AzureProfile profile; private LoadTestManager loadTestManager; private String resourceGroupName; public void setupCredential() { credential = new DefaultAzureCredentialBuilder().build(); } public void setupProfile() { profile = new AzureProfile(AzureEnvironment.AZURE); } @Test @DoNotRecord(skipInPlayback = true) public void startTest() { prepareTests(); ResourceOperations resourceOperations = new ResourceOperations(LOCATION.toString(), resourceGroupName, RESOURCE_NAME); resourceOperations.create(loadTestManager); resourceOperations.get(loadTestManager); resourceOperations.update(loadTestManager); resourceOperations.delete(loadTestManager); QuotaOperations quotaOperations = new QuotaOperations(LOCATION.toString(), QUOTA_BUCKET_NAME); quotaOperations.listBuckets(loadTestManager); quotaOperations.getBucket(loadTestManager); quotaOperations.checkAvailability(loadTestManager); } }
class TestOrchestrator extends TestBase { private static final Random RANDOM = new Random(); private static final Region LOCATION = Region.US_WEST2; private static final String RESOURCE_NAME = "loadtest-resource" + RANDOM.nextInt(1000); private static final String QUOTA_BUCKET_NAME = "maxEngineInstancesPerTestRun"; private DefaultAzureCredential credential; private AzureProfile profile; private LoadTestManager loadTestManager; private String resourceGroupName; public void setupCredential() { credential = new DefaultAzureCredentialBuilder().build(); } public void setupProfile() { profile = new AzureProfile(AzureEnvironment.AZURE); } @Test @DoNotRecord(skipInPlayback = true) public void startTest() { prepareTests(); ResourceOperations resourceOperations = new ResourceOperations(LOCATION.toString(), resourceGroupName, RESOURCE_NAME); resourceOperations.create(loadTestManager); resourceOperations.get(loadTestManager); resourceOperations.update(loadTestManager); resourceOperations.delete(loadTestManager); QuotaOperations quotaOperations = new QuotaOperations(LOCATION.toString(), QUOTA_BUCKET_NAME); quotaOperations.listBuckets(loadTestManager); quotaOperations.getBucket(loadTestManager); quotaOperations.checkAvailability(loadTestManager); } }
Maybe add assertion that provider is unregistered.
public void testProviderRegistrationPolicy() { final String acrName = generateRandomResourceName("acr", 10); Provider provider = azureResourceManager.providers().getByName("Microsoft.ContainerRegistry"); if (provider != null && "Registered".equalsIgnoreCase(provider.registrationState())) { provider = azureResourceManager.providers().unregister("Microsoft.ContainerRegistry"); ResourceManagerUtils.sleep(Duration.ofMinutes(5)); } Registry registry = azureResourceManager .containerRegistries() .define(acrName) .withRegion(Region.US_WEST_CENTRAL) .withNewResourceGroup(rgName) .withPremiumSku() .withRegistryNameAsAdminUser() .withTag("tag1", "value1") .create(); Assertions.assertNotNull(registry); }
ResourceManagerUtils.sleep(Duration.ofMinutes(5));
public void testProviderRegistrationPolicy() { final String acrName = generateRandomResourceName("acr", 10); final String namespace = "Microsoft.ContainerRegistry"; Provider provider = azureResourceManager.providers().getByName(namespace); if (provider != null && "Registered".equalsIgnoreCase(provider.registrationState())) { provider = azureResourceManager.providers().unregister(namespace); ResourceManagerUtils.sleep(Duration.ofMinutes(5)); provider = azureResourceManager.providers().getByName(namespace); } Assertions.assertEquals("Unregistered", provider.registrationState()); Registry registry = azureResourceManager .containerRegistries() .define(acrName) .withRegion(Region.US_WEST_CENTRAL) .withNewResourceGroup(rgName) .withPremiumSku() .withRegistryNameAsAdminUser() .withTag("tag1", "value1") .create(); Assertions.assertNotNull(registry); }
class ProviderRegistrationPolicyTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; private String rgName; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = AzureResourceManager.authenticate(httpPipeline, profile).withDefaultSubscription(); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("rg", 8); } @Override protected void cleanUpResources() { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } @Test }
class ProviderRegistrationPolicyTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; private String rgName; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = AzureResourceManager.authenticate(httpPipeline, profile).withDefaultSubscription(); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("rg", 8); } @Override protected void cleanUpResources() { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } @Test }
added
public void testProviderRegistrationPolicy() { final String acrName = generateRandomResourceName("acr", 10); Provider provider = azureResourceManager.providers().getByName("Microsoft.ContainerRegistry"); if (provider != null && "Registered".equalsIgnoreCase(provider.registrationState())) { provider = azureResourceManager.providers().unregister("Microsoft.ContainerRegistry"); ResourceManagerUtils.sleep(Duration.ofMinutes(5)); } Registry registry = azureResourceManager .containerRegistries() .define(acrName) .withRegion(Region.US_WEST_CENTRAL) .withNewResourceGroup(rgName) .withPremiumSku() .withRegistryNameAsAdminUser() .withTag("tag1", "value1") .create(); Assertions.assertNotNull(registry); }
ResourceManagerUtils.sleep(Duration.ofMinutes(5));
public void testProviderRegistrationPolicy() { final String acrName = generateRandomResourceName("acr", 10); final String namespace = "Microsoft.ContainerRegistry"; Provider provider = azureResourceManager.providers().getByName(namespace); if (provider != null && "Registered".equalsIgnoreCase(provider.registrationState())) { provider = azureResourceManager.providers().unregister(namespace); ResourceManagerUtils.sleep(Duration.ofMinutes(5)); provider = azureResourceManager.providers().getByName(namespace); } Assertions.assertEquals("Unregistered", provider.registrationState()); Registry registry = azureResourceManager .containerRegistries() .define(acrName) .withRegion(Region.US_WEST_CENTRAL) .withNewResourceGroup(rgName) .withPremiumSku() .withRegistryNameAsAdminUser() .withTag("tag1", "value1") .create(); Assertions.assertNotNull(registry); }
class ProviderRegistrationPolicyTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; private String rgName; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = AzureResourceManager.authenticate(httpPipeline, profile).withDefaultSubscription(); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("rg", 8); } @Override protected void cleanUpResources() { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } @Test }
class ProviderRegistrationPolicyTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; private String rgName; @Override protected HttpPipeline buildHttpPipeline( TokenCredential credential, AzureProfile profile, HttpLogOptions httpLogOptions, List<HttpPipelinePolicy> policies, HttpClient httpClient) { return HttpPipelineProvider.buildHttpPipeline( credential, profile, null, httpLogOptions, null, new RetryPolicy("Retry-After", ChronoUnit.SECONDS), policies, httpClient); } @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode())); ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext(); internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer)); azureResourceManager = AzureResourceManager.authenticate(httpPipeline, profile).withDefaultSubscription(); setInternalContext(internalContext, azureResourceManager); rgName = generateRandomResourceName("rg", 8); } @Override protected void cleanUpResources() { azureResourceManager.resourceGroups().beginDeleteByName(rgName); } @Test }
`ObjectMapper` should be a static class variable, to be shared (it is thread-safe).
private Mono<PollResponse<ValidationStatus>> getValidationStatus(BinaryData fileMono) { String validationStatus; JsonNode file; try { file = new ObjectMapper().readTree(fileMono.toString()); validationStatus = file.get("validationStatus").asText(); } catch (JsonProcessingException e) { return Mono.error(new RuntimeException("Encountered exception while retriving validation status")); } LongRunningOperationStatus lroStatus; ValidationStatus validationStatusEnum; switch (validationStatus) { case "VALIDATION_SUCCESS": lroStatus = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; validationStatusEnum = ValidationStatus.VALIDATION_SUCCESS; break; case "VALIDATION_FAILURE": lroStatus = LongRunningOperationStatus.FAILED; validationStatusEnum = ValidationStatus.VALIDATION_FAILURE; break; case "VALIDATION_INITIATED": lroStatus = LongRunningOperationStatus.IN_PROGRESS; validationStatusEnum = ValidationStatus.VALIDATION_INITIATED; break; case "VALIDATION_NOT_REQUIRED": lroStatus = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; validationStatusEnum = ValidationStatus.VALIDATION_NOT_REQUIRED; break; default: lroStatus = LongRunningOperationStatus.NOT_STARTED; validationStatusEnum = ValidationStatus.NOT_VALIDATED; break; } return Mono.just(new PollResponse<>(lroStatus, validationStatusEnum)); }
file = new ObjectMapper().readTree(fileMono.toString());
new ObjectMapper(); @Generated private final LoadTestAdministrationsImpl serviceClient; /** * Initializes an instance of LoadTestAdministrationAsyncClient class. * * @param serviceClient the service client implementation. */ @Generated LoadTestAdministrationAsyncClient(LoadTestAdministrationsImpl serviceClient) { this.serviceClient = serviceClient; }
class LoadTestAdministrationAsyncClient { @Generated private final LoadTestAdministrationsImpl serviceClient; /** * Initializes an instance of LoadTestAdministrationAsyncClient class. * * @param serviceClient the service client implementation. */ @Generated LoadTestAdministrationAsyncClient(LoadTestAdministrationsImpl serviceClient) { this.serviceClient = serviceClient; } /** * Associate an app component (collection of azure resources) to a test. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * components (Required): { * String (Required): { * resourceId: String (Optional) * resourceName: String (Optional) * resourceType: String (Optional) * displayName: String (Optional) * resourceGroup: String (Optional) * subscriptionId: String (Optional) * kind: String (Optional) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * components (Required): { * String (Required): { * resourceId: String (Optional) * resourceName: String (Optional) * resourceType: String (Optional) * displayName: String (Optional) * resourceGroup: String (Optional) * subscriptionId: String (Optional) * kind: String (Optional) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param body App Component model. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return test app component along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> createOrUpdateAppComponentWithResponse( String testId, BinaryData body, RequestOptions requestOptions) { return this.serviceClient.createOrUpdateAppComponentWithResponseAsync(testId, body, requestOptions); } /** * Get associated app component (collection of azure resources) for the given test. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * components (Required): { * String (Required): { * resourceId: String (Optional) * resourceName: String (Optional) * resourceType: String (Optional) * displayName: String (Optional) * resourceGroup: String (Optional) * subscriptionId: String (Optional) * kind: String (Optional) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return associated app component (collection of azure resources) for the given test along with {@link Response} * on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> getAppComponentsWithResponse(String testId, RequestOptions requestOptions) { return this.serviceClient.getAppComponentsWithResponseAsync(testId, requestOptions); } /** * Configure server metrics for a test. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * metrics (Optional): { * String (Optional): { * id: String (Optional) * resourceId: String (Required) * metricNamespace: String (Required) * displayDescription: String (Optional) * name: String (Required) * aggregation: String (Required) * unit: String (Optional) * resourceType: String (Required) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * metrics (Optional): { * String (Optional): { * id: String (Optional) * resourceId: String (Required) * metricNamespace: String (Required) * displayDescription: String (Optional) * name: String (Required) * aggregation: String (Required) * unit: String (Optional) * resourceType: String (Required) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param body Server metric configuration model. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return test server metric configuration along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> createOrUpdateServerMetricsConfigWithResponse( String testId, BinaryData body, RequestOptions requestOptions) { return this.serviceClient.createOrUpdateServerMetricsConfigWithResponseAsync(testId, body, requestOptions); } /** * Get server metric configuration for the given test. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * metrics (Optional): { * String (Optional): { * id: String (Optional) * resourceId: String (Required) * metricNamespace: String (Required) * displayDescription: String (Optional) * name: String (Required) * aggregation: String (Required) * unit: String (Optional) * resourceType: String (Required) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return server metric configuration for the given test along with {@link Response} on successful completion of * {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> getServerMetricsConfigWithResponse(String testId, RequestOptions requestOptions) { return this.serviceClient.getServerMetricsConfigWithResponseAsync(testId, requestOptions); } /** Validation status of uploaded file */ public enum ValidationStatus { /** Validation not initiated */ NOT_VALIDATED, /** Validation successful */ VALIDATION_SUCCESS, /** Validation failed */ VALIDATION_FAILURE, /** Validation initiated */ VALIDATION_INITIATED, /** Validation not required for file type */ VALIDATION_NOT_REQUIRED } private Mono<PollResponse<ValidationStatus>> getValidationStatus(BinaryData fileMono) { String validationStatus; JsonNode file; try { file = LongRunningOperationStatus lroStatus; ValidationStatus validationStatusEnum; switch (validationStatus) { case "VALIDATION_SUCCESS": lroStatus = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; validationStatusEnum = ValidationStatus.VALIDATION_SUCCESS; break; case "VALIDATION_FAILURE": lroStatus = LongRunningOperationStatus.FAILED; validationStatusEnum = ValidationStatus.VALIDATION_FAILURE; break; case "VALIDATION_INITIATED": lroStatus = LongRunningOperationStatus.IN_PROGRESS; validationStatusEnum = ValidationStatus.VALIDATION_INITIATED; break; case "VALIDATION_NOT_REQUIRED": lroStatus = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; validationStatusEnum = ValidationStatus.VALIDATION_NOT_REQUIRED; break; default: lroStatus = LongRunningOperationStatus.NOT_STARTED; validationStatusEnum = ValidationStatus.NOT_VALIDATED; break; } return Mono.just(new PollResponse<>(lroStatus, validationStatusEnum)); } /** * Uploads file and polls the validation status of the uploaded file. * * @param testId Unique name for load test, must be a valid URL character ^[a-z0-9_-]*$. * @param fileName Unique name for test file with file extension like : App.jmx. * @param body The file content as application/octet-stream. * @param refreshTime The time in seconds to refresh the polling operation. * @param fileUploadRequestOptions The options to configure the file upload HTTP request before HTTP client sends * it. * @throws ResourceNotFoundException when a test with {@code testId} doesn't exist. * @return A {@link PollerFlux} to poll on and retrieve the validation * status(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED). */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public PollerFlux<ValidationStatus, BinaryData> beginUploadAndValidate( String testId, String fileName, BinaryData body, int refreshTime, RequestOptions fileUploadRequestOptions) { return new PollerFlux<>( Duration.ofSeconds(refreshTime), (context) -> { Mono<BinaryData> fileMono = uploadTestFileWithResponse(testId, fileName, body, fileUploadRequestOptions) .flatMap(FluxUtil::toMono); Mono<PollResponse<ValidationStatus>> validationPollRespMono = fileMono.flatMap(fileBinaryData -> getValidationStatus(fileBinaryData)); return validationPollRespMono.flatMap( validationPollResp -> { return Mono.just(validationPollResp.getValue()); }); }, (context) -> { Mono<BinaryData> fileMono = getTestFileWithResponse(testId, fileName, null).flatMap(FluxUtil::toMono); return fileMono.flatMap(fileBinaryData -> getValidationStatus(fileBinaryData)); }, (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), (context) -> getTestFileWithResponse(testId, fileName, null).flatMap(FluxUtil::toMono)); } /** * Get all test files. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>continuationToken</td><td>String</td><td>No</td><td>Continuation token to get the next page of response</td></tr> * </table> * * You can add these to a request with {@link RequestOptions * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * value (Required): [ * (Required){ * url: String (Optional) * filename: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * } * ] * nextLink: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return all test files as paginated response with {@link PagedFlux}. */ @Generated @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<BinaryData> listTestFiles(String testId, RequestOptions requestOptions) { return this.serviceClient.listTestFilesAsync(testId, requestOptions); } /** * Create a new test or update an existing test. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * passFailCriteria (Optional): { * passFailMetrics (Optional): { * String (Optional): { * clientMetric: String(response_time_ms/latency/error/requests/requests_per_sec) (Optional) * aggregate: String(count/percentage/avg/p50/p90/p95/p99/min/max) (Optional) * condition: String (Optional) * requestName: String (Optional) * value: Double (Optional) * action: String(stop/continue) (Optional) * actualValue: Double (Optional) * result: String(passed/undetermined/failed) (Optional) * } * } * } * secrets (Optional): { * String (Optional): { * value: String (Optional) * type: String(AKV_SECRET_URI/SECRET_VALUE) (Optional) * } * } * certificate (Optional): { * value: String (Optional) * type: String(AKV_CERT_URI) (Optional) * name: String (Optional) * } * environmentVariables (Optional): { * String: String (Optional) * } * loadTestConfiguration (Optional): { * engineInstances: Integer (Optional) * splitAllCSVs: Boolean (Optional) * quickStartTest: Boolean (Optional) * optionalLoadTestConfig (Optional): { * endpointUrl: String (Optional) * virtualUsers: Integer (Optional) * rampUpTime: Integer (Optional) * duration: Integer (Optional) * } * } * inputArtifacts (Optional): { * configFileInfo (Optional): { * url: String (Optional) * filename: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * } * testScriptFileInfo (Optional): (recursive schema, see testScriptFileInfo above) * userPropFileInfo (Optional): (recursive schema, see userPropFileInfo above) * inputArtifactsZipFileInfo (Optional): (recursive schema, see inputArtifactsZipFileInfo above) * additionalFileInfo (Optional): [ * (recursive schema, see above) * ] * } * testId: String (Optional) * description: String (Optional) * displayName: String (Optional) * subnetId: String (Optional) * keyvaultReferenceIdentityType: String (Optional) * keyvaultReferenceIdentityId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * passFailCriteria (Optional): { * passFailMetrics (Optional): { * String (Optional): { * clientMetric: String(response_time_ms/latency/error/requests/requests_per_sec) (Optional) * aggregate: String(count/percentage/avg/p50/p90/p95/p99/min/max) (Optional) * condition: String (Optional) * requestName: String (Optional) * value: Double (Optional) * action: String(stop/continue) (Optional) * actualValue: Double (Optional) * result: String(passed/undetermined/failed) (Optional) * } * } * } * secrets (Optional): { * String (Optional): { * value: String (Optional) * type: String(AKV_SECRET_URI/SECRET_VALUE) (Optional) * } * } * certificate (Optional): { * value: String (Optional) * type: String(AKV_CERT_URI) (Optional) * name: String (Optional) * } * environmentVariables (Optional): { * String: String (Optional) * } * loadTestConfiguration (Optional): { * engineInstances: Integer (Optional) * splitAllCSVs: Boolean (Optional) * quickStartTest: Boolean (Optional) * optionalLoadTestConfig (Optional): { * endpointUrl: String (Optional) * virtualUsers: Integer (Optional) * rampUpTime: Integer (Optional) * duration: Integer (Optional) * } * } * inputArtifacts (Optional): { * configFileInfo (Optional): { * url: String (Optional) * filename: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * } * testScriptFileInfo (Optional): (recursive schema, see testScriptFileInfo above) * userPropFileInfo (Optional): (recursive schema, see userPropFileInfo above) * inputArtifactsZipFileInfo (Optional): (recursive schema, see inputArtifactsZipFileInfo above) * additionalFileInfo (Optional): [ * (recursive schema, see above) * ] * } * testId: String (Optional) * description: String (Optional) * displayName: String (Optional) * subnetId: String (Optional) * keyvaultReferenceIdentityType: String (Optional) * keyvaultReferenceIdentityId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param body Load test model. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return load test model along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> createOrUpdateTestWithResponse( String testId, BinaryData body, RequestOptions requestOptions) { return this.serviceClient.createOrUpdateTestWithResponseAsync(testId, body, requestOptions); } /** * Delete a test by its name. * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTestWithResponse(String testId, RequestOptions requestOptions) { return this.serviceClient.deleteTestWithResponseAsync(testId, requestOptions); } /** * Get load test details by test name. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * passFailCriteria (Optional): { * passFailMetrics (Optional): { * String (Optional): { * clientMetric: String(response_time_ms/latency/error/requests/requests_per_sec) (Optional) * aggregate: String(count/percentage/avg/p50/p90/p95/p99/min/max) (Optional) * condition: String (Optional) * requestName: String (Optional) * value: Double (Optional) * action: String(stop/continue) (Optional) * actualValue: Double (Optional) * result: String(passed/undetermined/failed) (Optional) * } * } * } * secrets (Optional): { * String (Optional): { * value: String (Optional) * type: String(AKV_SECRET_URI/SECRET_VALUE) (Optional) * } * } * certificate (Optional): { * value: String (Optional) * type: String(AKV_CERT_URI) (Optional) * name: String (Optional) * } * environmentVariables (Optional): { * String: String (Optional) * } * loadTestConfiguration (Optional): { * engineInstances: Integer (Optional) * splitAllCSVs: Boolean (Optional) * quickStartTest: Boolean (Optional) * optionalLoadTestConfig (Optional): { * endpointUrl: String (Optional) * virtualUsers: Integer (Optional) * rampUpTime: Integer (Optional) * duration: Integer (Optional) * } * } * inputArtifacts (Optional): { * configFileInfo (Optional): { * url: String (Optional) * filename: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * } * testScriptFileInfo (Optional): (recursive schema, see testScriptFileInfo above) * userPropFileInfo (Optional): (recursive schema, see userPropFileInfo above) * inputArtifactsZipFileInfo (Optional): (recursive schema, see inputArtifactsZipFileInfo above) * additionalFileInfo (Optional): [ * (recursive schema, see above) * ] * } * testId: String (Optional) * description: String (Optional) * displayName: String (Optional) * subnetId: String (Optional) * keyvaultReferenceIdentityType: String (Optional) * keyvaultReferenceIdentityId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return load test details by test name along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> getTestWithResponse(String testId, RequestOptions requestOptions) { return this.serviceClient.getTestWithResponseAsync(testId, requestOptions); } /** * Get all load tests by the fully qualified resource Id e.g * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>orderby</td><td>String</td><td>No</td><td>Sort on the supported fields in (field asc/desc) format. eg: lastModifiedDateTime asc. Supported fields - lastModifiedDateTime</td></tr> * <tr><td>search</td><td>String</td><td>No</td><td>Prefix based, case sensitive search on searchable fields - testId, createdBy.</td></tr> * <tr><td>lastModifiedStartTime</td><td>OffsetDateTime</td><td>No</td><td>Start DateTime(ISO 8601 literal format) of the last updated time range to filter tests.</td></tr> * <tr><td>lastModifiedEndTime</td><td>OffsetDateTime</td><td>No</td><td>End DateTime(ISO 8601 literal format) of the last updated time range to filter tests.</td></tr> * <tr><td>continuationToken</td><td>String</td><td>No</td><td>Continuation token to get the next page of response</td></tr> * <tr><td>maxpagesize</td><td>Integer</td><td>No</td><td>Number of results in response.</td></tr> * </table> * * You can add these to a request with {@link RequestOptions * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * value (Required): [ * (Required){ * passFailCriteria (Optional): { * passFailMetrics (Optional): { * String (Optional): { * clientMetric: String(response_time_ms/latency/error/requests/requests_per_sec) (Optional) * aggregate: String(count/percentage/avg/p50/p90/p95/p99/min/max) (Optional) * condition: String (Optional) * requestName: String (Optional) * value: Double (Optional) * action: String(stop/continue) (Optional) * actualValue: Double (Optional) * result: String(passed/undetermined/failed) (Optional) * } * } * } * secrets (Optional): { * String (Optional): { * value: String (Optional) * type: String(AKV_SECRET_URI/SECRET_VALUE) (Optional) * } * } * certificate (Optional): { * value: String (Optional) * type: String(AKV_CERT_URI) (Optional) * name: String (Optional) * } * environmentVariables (Optional): { * String: String (Optional) * } * loadTestConfiguration (Optional): { * engineInstances: Integer (Optional) * splitAllCSVs: Boolean (Optional) * quickStartTest: Boolean (Optional) * optionalLoadTestConfig (Optional): { * endpointUrl: String (Optional) * virtualUsers: Integer (Optional) * rampUpTime: Integer (Optional) * duration: Integer (Optional) * } * } * inputArtifacts (Optional): { * configFileInfo (Optional): { * url: String (Optional) * filename: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * } * testScriptFileInfo (Optional): (recursive schema, see testScriptFileInfo above) * userPropFileInfo (Optional): (recursive schema, see userPropFileInfo above) * inputArtifactsZipFileInfo (Optional): (recursive schema, see inputArtifactsZipFileInfo above) * additionalFileInfo (Optional): [ * (recursive schema, see above) * ] * } * testId: String (Optional) * description: String (Optional) * displayName: String (Optional) * subnetId: String (Optional) * keyvaultReferenceIdentityType: String (Optional) * keyvaultReferenceIdentityId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * ] * nextLink: String (Optional) * } * }</pre> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return all load tests by the fully qualified resource Id e.g * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} as * paginated response with {@link PagedFlux}. */ @Generated @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<BinaryData> listTests(RequestOptions requestOptions) { return this.serviceClient.listTestsAsync(requestOptions); } /** * Upload input file for a given test name. File size can't be more than 50 MB. Existing file with same name for the * given test will be overwritten. File should be provided in the request body as application/octet-stream. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>fileType</td><td>String</td><td>No</td><td>File type. Allowed values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS".</td></tr> * </table> * * You can add these to a request with {@link RequestOptions * * <p><strong>Request Body Schema</strong> * * <pre>{@code * BinaryData * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * url: String (Optional) * filename: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param fileName Unique name for test file with file extension like : App.jmx. * @param body The file content as application/octet-stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return file info along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> uploadTestFileWithResponse( String testId, String fileName, BinaryData body, RequestOptions requestOptions) { return this.serviceClient.uploadTestFileWithResponseAsync(testId, fileName, body, requestOptions); } /** * Get test file by the file name. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * url: String (Optional) * filename: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param fileName File name with file extension like app.jmx. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return test file by the file name along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> getTestFileWithResponse( String testId, String fileName, RequestOptions requestOptions) { return this.serviceClient.getTestFileWithResponseAsync(testId, fileName, requestOptions); } /** * Delete file by the file name for a test. * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param fileName File name with file extension like app.jmx. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTestFileWithResponse( String testId, String fileName, RequestOptions requestOptions) { return this.serviceClient.deleteTestFileWithResponseAsync(testId, fileName, requestOptions); } }
class LoadTestAdministrationAsyncClient { private static final ObjectMapper OBJECT_MAPPER = /** * Configure server metrics for a test. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * metrics (Optional): { * String (Optional): { * id: String (Optional) * resourceId: String (Required) * metricNamespace: String (Required) * displayDescription: String (Optional) * name: String (Required) * aggregation: String (Required) * unit: String (Optional) * resourceType: String (Required) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * metrics (Optional): { * String (Optional): { * id: String (Optional) * resourceId: String (Required) * metricNamespace: String (Required) * displayDescription: String (Optional) * name: String (Required) * aggregation: String (Required) * unit: String (Optional) * resourceType: String (Required) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param body Server metric configuration model. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return test server metrics configuration along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> createOrUpdateServerMetricsConfigWithResponse( String testId, BinaryData body, RequestOptions requestOptions) { return this.serviceClient.createOrUpdateServerMetricsConfigWithResponseAsync(testId, body, requestOptions); } private Mono<PollResponse<BinaryData>> getValidationStatus(BinaryData fileBinary) { String validationStatus, fileType; JsonNode file; try { file = OBJECT_MAPPER.readTree(fileBinary.toString()); validationStatus = file.get("validationStatus").asText(); fileType = file.get("fileType").asText(); } catch (JsonProcessingException e) { return Mono.error(new RuntimeException("Encountered exception while retrieving validation status", e)); } LongRunningOperationStatus lroStatus; switch (validationStatus) { case "VALIDATION_NOT_REQUIRED": case "VALIDATION_SUCCESS": lroStatus = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case "VALIDATION_FAILURE": lroStatus = LongRunningOperationStatus.FAILED; break; case "VALIDATION_INITIATED": lroStatus = LongRunningOperationStatus.IN_PROGRESS; break; case "NOT_VALIDATED": if ("JMX_FILE".equalsIgnoreCase(fileType)) { lroStatus = LongRunningOperationStatus.NOT_STARTED; } else { lroStatus = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; } break; default: lroStatus = LongRunningOperationStatus.NOT_STARTED; break; } return Mono.just(new PollResponse<>(lroStatus, fileBinary)); } /** * Uploads file and polls the validation status of the uploaded file. * * @param testId Unique name for load test, must be a valid URL character ^[a-z0-9_-]*$. * @param fileName Unique name for test file with file extension like : App.jmx. * @param body The file content as application/octet-stream. * @param fileUploadRequestOptions The options to configure the file upload HTTP request before HTTP client sends * it. * @throws ResourceNotFoundException when a test with {@code testId} doesn't exist. * @return A {@link PollerFlux} to poll on and retrieve the file info with validation status. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public PollerFlux<BinaryData, BinaryData> beginUploadTestFile( String testId, String fileName, BinaryData body, RequestOptions fileUploadRequestOptions) { RequestOptions defaultRequestOptions = new RequestOptions(); if (fileUploadRequestOptions != null) { defaultRequestOptions.setContext(fileUploadRequestOptions.getContext()); } return new PollerFlux<>( Duration.ofSeconds(2), (context) -> { Mono<BinaryData> fileMono = uploadTestFileWithResponse(testId, fileName, body, fileUploadRequestOptions) .flatMap(FluxUtil::toMono); Mono<PollResponse<BinaryData>> fileValidationPollRespMono = fileMono.flatMap(fileBinaryData -> getValidationStatus(fileBinaryData)); return fileValidationPollRespMono.flatMap( fileValidationPollResp -> Mono.just(fileValidationPollResp.getValue())); }, (context) -> { Mono<BinaryData> fileMono = getTestFileWithResponse(testId, fileName, defaultRequestOptions).flatMap(FluxUtil::toMono); return fileMono.flatMap(fileBinaryData -> getValidationStatus(fileBinaryData)); }, (activationResponse, context) -> Mono.error(new RuntimeException("Cancellation is not supported")), (context) -> getTestFileWithResponse(testId, fileName, defaultRequestOptions).flatMap(FluxUtil::toMono)); } /** * Get all test files. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>continuationToken</td><td>String</td><td>No</td><td>Continuation token to get the next page of response</td></tr> * </table> * * You can add these to a request with {@link RequestOptions * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * value (Required): [ * (Required){ * url: String (Optional) * fileName: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * validationFailureDetails: String (Optional) * } * ] * nextLink: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return all test files as paginated response with {@link PagedFlux}. */ @Generated @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<BinaryData> listTestFiles(String testId, RequestOptions requestOptions) { return this.serviceClient.listTestFilesAsync(testId, requestOptions); } /** * Create a new test or update an existing test. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * passFailCriteria (Optional): { * passFailMetrics (Optional): { * String (Optional): { * clientMetric: String(response_time_ms/latency/error/requests/requests_per_sec) (Optional) * aggregate: String(count/percentage/avg/p50/p90/p95/p99/min/max) (Optional) * condition: String (Optional) * requestName: String (Optional) * value: Double (Optional) * action: String(continue/stop) (Optional) * actualValue: Double (Optional) * result: String(passed/undetermined/failed) (Optional) * } * } * } * secrets (Optional): { * String (Optional): { * value: String (Optional) * type: String(AKV_SECRET_URI/SECRET_VALUE) (Optional) * } * } * certificate (Optional): { * value: String (Optional) * type: String(AKV_CERT_URI) (Optional) * name: String (Optional) * } * environmentVariables (Optional): { * String: String (Optional) * } * loadTestConfiguration (Optional): { * engineInstances: Integer (Optional) * splitAllCSVs: Boolean (Optional) * quickStartTest: Boolean (Optional) * optionalLoadTestConfig (Optional): { * endpointUrl: String (Optional) * virtualUsers: Integer (Optional) * rampUpTime: Integer (Optional) * duration: Integer (Optional) * } * } * inputArtifacts (Optional): { * configFileInfo (Optional): { * url: String (Optional) * fileName: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * validationFailureDetails: String (Optional) * } * testScriptFileInfo (Optional): (recursive schema, see testScriptFileInfo above) * userPropFileInfo (Optional): (recursive schema, see userPropFileInfo above) * inputArtifactsZipFileInfo (Optional): (recursive schema, see inputArtifactsZipFileInfo above) * additionalFileInfo (Optional): [ * (recursive schema, see above) * ] * } * testId: String (Optional) * description: String (Optional) * displayName: String (Optional) * subnetId: String (Optional) * keyvaultReferenceIdentityType: String (Optional) * keyvaultReferenceIdentityId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * passFailCriteria (Optional): { * passFailMetrics (Optional): { * String (Optional): { * clientMetric: String(response_time_ms/latency/error/requests/requests_per_sec) (Optional) * aggregate: String(count/percentage/avg/p50/p90/p95/p99/min/max) (Optional) * condition: String (Optional) * requestName: String (Optional) * value: Double (Optional) * action: String(continue/stop) (Optional) * actualValue: Double (Optional) * result: String(passed/undetermined/failed) (Optional) * } * } * } * secrets (Optional): { * String (Optional): { * value: String (Optional) * type: String(AKV_SECRET_URI/SECRET_VALUE) (Optional) * } * } * certificate (Optional): { * value: String (Optional) * type: String(AKV_CERT_URI) (Optional) * name: String (Optional) * } * environmentVariables (Optional): { * String: String (Optional) * } * loadTestConfiguration (Optional): { * engineInstances: Integer (Optional) * splitAllCSVs: Boolean (Optional) * quickStartTest: Boolean (Optional) * optionalLoadTestConfig (Optional): { * endpointUrl: String (Optional) * virtualUsers: Integer (Optional) * rampUpTime: Integer (Optional) * duration: Integer (Optional) * } * } * inputArtifacts (Optional): { * configFileInfo (Optional): { * url: String (Optional) * fileName: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * validationFailureDetails: String (Optional) * } * testScriptFileInfo (Optional): (recursive schema, see testScriptFileInfo above) * userPropFileInfo (Optional): (recursive schema, see userPropFileInfo above) * inputArtifactsZipFileInfo (Optional): (recursive schema, see inputArtifactsZipFileInfo above) * additionalFileInfo (Optional): [ * (recursive schema, see above) * ] * } * testId: String (Optional) * description: String (Optional) * displayName: String (Optional) * subnetId: String (Optional) * keyvaultReferenceIdentityType: String (Optional) * keyvaultReferenceIdentityId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param body Load test model. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return load test model along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> createOrUpdateTestWithResponse( String testId, BinaryData body, RequestOptions requestOptions) { return this.serviceClient.createOrUpdateTestWithResponseAsync(testId, body, requestOptions); } /** * Delete a test by its name. * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTestWithResponse(String testId, RequestOptions requestOptions) { return this.serviceClient.deleteTestWithResponseAsync(testId, requestOptions); } /** * Get load test details by test name. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * passFailCriteria (Optional): { * passFailMetrics (Optional): { * String (Optional): { * clientMetric: String(response_time_ms/latency/error/requests/requests_per_sec) (Optional) * aggregate: String(count/percentage/avg/p50/p90/p95/p99/min/max) (Optional) * condition: String (Optional) * requestName: String (Optional) * value: Double (Optional) * action: String(continue/stop) (Optional) * actualValue: Double (Optional) * result: String(passed/undetermined/failed) (Optional) * } * } * } * secrets (Optional): { * String (Optional): { * value: String (Optional) * type: String(AKV_SECRET_URI/SECRET_VALUE) (Optional) * } * } * certificate (Optional): { * value: String (Optional) * type: String(AKV_CERT_URI) (Optional) * name: String (Optional) * } * environmentVariables (Optional): { * String: String (Optional) * } * loadTestConfiguration (Optional): { * engineInstances: Integer (Optional) * splitAllCSVs: Boolean (Optional) * quickStartTest: Boolean (Optional) * optionalLoadTestConfig (Optional): { * endpointUrl: String (Optional) * virtualUsers: Integer (Optional) * rampUpTime: Integer (Optional) * duration: Integer (Optional) * } * } * inputArtifacts (Optional): { * configFileInfo (Optional): { * url: String (Optional) * fileName: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * validationFailureDetails: String (Optional) * } * testScriptFileInfo (Optional): (recursive schema, see testScriptFileInfo above) * userPropFileInfo (Optional): (recursive schema, see userPropFileInfo above) * inputArtifactsZipFileInfo (Optional): (recursive schema, see inputArtifactsZipFileInfo above) * additionalFileInfo (Optional): [ * (recursive schema, see above) * ] * } * testId: String (Optional) * description: String (Optional) * displayName: String (Optional) * subnetId: String (Optional) * keyvaultReferenceIdentityType: String (Optional) * keyvaultReferenceIdentityId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return load test details by test name along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> getTestWithResponse(String testId, RequestOptions requestOptions) { return this.serviceClient.getTestWithResponseAsync(testId, requestOptions); } /** * Get all load tests by the fully qualified resource Id e.g * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>orderby</td><td>String</td><td>No</td><td>Sort on the supported fields in (field asc/desc) format. eg: lastModifiedDateTime asc. Supported fields - lastModifiedDateTime</td></tr> * <tr><td>search</td><td>String</td><td>No</td><td>Prefix based, case sensitive search on searchable fields - displayName, createdBy. For example, to search for a test, with display name is Login Test, the search parameter can be Login.</td></tr> * <tr><td>lastModifiedStartTime</td><td>OffsetDateTime</td><td>No</td><td>Start DateTime(ISO 8601 literal format) of the last updated time range to filter tests.</td></tr> * <tr><td>lastModifiedEndTime</td><td>OffsetDateTime</td><td>No</td><td>End DateTime(ISO 8601 literal format) of the last updated time range to filter tests.</td></tr> * <tr><td>continuationToken</td><td>String</td><td>No</td><td>Continuation token to get the next page of response</td></tr> * <tr><td>maxpagesize</td><td>Integer</td><td>No</td><td>Number of results in response.</td></tr> * </table> * * You can add these to a request with {@link RequestOptions * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * value (Required): [ * (Required){ * passFailCriteria (Optional): { * passFailMetrics (Optional): { * String (Optional): { * clientMetric: String(response_time_ms/latency/error/requests/requests_per_sec) (Optional) * aggregate: String(count/percentage/avg/p50/p90/p95/p99/min/max) (Optional) * condition: String (Optional) * requestName: String (Optional) * value: Double (Optional) * action: String(continue/stop) (Optional) * actualValue: Double (Optional) * result: String(passed/undetermined/failed) (Optional) * } * } * } * secrets (Optional): { * String (Optional): { * value: String (Optional) * type: String(AKV_SECRET_URI/SECRET_VALUE) (Optional) * } * } * certificate (Optional): { * value: String (Optional) * type: String(AKV_CERT_URI) (Optional) * name: String (Optional) * } * environmentVariables (Optional): { * String: String (Optional) * } * loadTestConfiguration (Optional): { * engineInstances: Integer (Optional) * splitAllCSVs: Boolean (Optional) * quickStartTest: Boolean (Optional) * optionalLoadTestConfig (Optional): { * endpointUrl: String (Optional) * virtualUsers: Integer (Optional) * rampUpTime: Integer (Optional) * duration: Integer (Optional) * } * } * inputArtifacts (Optional): { * configFileInfo (Optional): { * url: String (Optional) * fileName: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * validationFailureDetails: String (Optional) * } * testScriptFileInfo (Optional): (recursive schema, see testScriptFileInfo above) * userPropFileInfo (Optional): (recursive schema, see userPropFileInfo above) * inputArtifactsZipFileInfo (Optional): (recursive schema, see inputArtifactsZipFileInfo above) * additionalFileInfo (Optional): [ * (recursive schema, see above) * ] * } * testId: String (Optional) * description: String (Optional) * displayName: String (Optional) * subnetId: String (Optional) * keyvaultReferenceIdentityType: String (Optional) * keyvaultReferenceIdentityId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * ] * nextLink: String (Optional) * } * }</pre> * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return all load tests by the fully qualified resource Id e.g * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} as * paginated response with {@link PagedFlux}. */ @Generated @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<BinaryData> listTests(RequestOptions requestOptions) { return this.serviceClient.listTestsAsync(requestOptions); } /** * Upload input file for a given test name. File size can't be more than 50 MB. Existing file with same name for the * given test will be overwritten. File should be provided in the request body as application/octet-stream. * * <p><strong>Query Parameters</strong> * * <table border="1"> * <caption>Query Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>fileType</td><td>String</td><td>No</td><td>File type. Allowed values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS".</td></tr> * </table> * * You can add these to a request with {@link RequestOptions * * <p><strong>Request Body Schema</strong> * * <pre>{@code * BinaryData * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * url: String (Optional) * fileName: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * validationFailureDetails: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param fileName Unique name for test file with file extension like : App.jmx. * @param body The file content as application/octet-stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return file info along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<BinaryData>> uploadTestFileWithResponse( String testId, String fileName, BinaryData body, RequestOptions requestOptions) { return this.serviceClient.uploadTestFileWithResponseAsync(testId, fileName, body, requestOptions); } /** * Get test file by the file name. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * url: String (Optional) * fileName: String (Optional) * fileType: String(JMX_FILE/USER_PROPERTIES/ADDITIONAL_ARTIFACTS) (Optional) * expireDateTime: OffsetDateTime (Optional) * validationStatus: String(NOT_VALIDATED/VALIDATION_SUCCESS/VALIDATION_FAILURE/VALIDATION_INITIATED/VALIDATION_NOT_REQUIRED) (Optional) * validationFailureDetails: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param fileName File name with file extension like app.jmx. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return test file by the file name along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> getTestFileWithResponse( String testId, String fileName, RequestOptions requestOptions) { return this.serviceClient.getTestFileWithResponseAsync(testId, fileName, requestOptions); } /** * Delete file by the file name for a test. * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param fileName File name with file extension like app.jmx. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteTestFileWithResponse( String testId, String fileName, RequestOptions requestOptions) { return this.serviceClient.deleteTestFileWithResponseAsync(testId, fileName, requestOptions); } /** * Associate an app component (collection of azure resources) to a test. * * <p><strong>Request Body Schema</strong> * * <pre>{@code * { * components (Required): { * String (Required): { * resourceId: String (Optional) * resourceName: String (Optional) * resourceType: String (Optional) * displayName: String (Optional) * resourceGroup: String (Optional) * subscriptionId: String (Optional) * kind: String (Optional) * } * } * testId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * components (Required): { * String (Required): { * resourceId: String (Optional) * resourceName: String (Optional) * resourceType: String (Optional) * displayName: String (Optional) * resourceGroup: String (Optional) * subscriptionId: String (Optional) * kind: String (Optional) * } * } * testId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param body App Component model. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return test app component along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> createOrUpdateAppComponentsWithResponse( String testId, BinaryData body, RequestOptions requestOptions) { return this.serviceClient.createOrUpdateAppComponentsWithResponseAsync(testId, body, requestOptions); } /** * Get associated app component (collection of azure resources) for the given test. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * components (Required): { * String (Required): { * resourceId: String (Optional) * resourceName: String (Optional) * resourceType: String (Optional) * displayName: String (Optional) * resourceGroup: String (Optional) * subscriptionId: String (Optional) * kind: String (Optional) * } * } * testId: String (Optional) * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return associated app component (collection of azure resources) for the given test along with {@link Response} * on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> getAppComponentsWithResponse(String testId, RequestOptions requestOptions) { return this.serviceClient.getAppComponentsWithResponseAsync(testId, requestOptions); } /** * List server metrics configuration for the given test. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * testId: String (Optional) * metrics (Optional): { * String (Optional): { * id: String (Optional) * resourceId: String (Required) * metricNamespace: String (Required) * displayDescription: String (Optional) * name: String (Required) * aggregation: String (Required) * unit: String (Optional) * resourceType: String (Required) * } * } * createdDateTime: OffsetDateTime (Optional) * createdBy: String (Optional) * lastModifiedDateTime: OffsetDateTime (Optional) * lastModifiedBy: String (Optional) * } * }</pre> * * @param testId Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or * hyphen characters. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return test server metrics configuration along with {@link Response} on successful completion of {@link Mono}. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<BinaryData>> getServerMetricsConfigWithResponse(String testId, RequestOptions requestOptions) { return this.serviceClient.getServerMetricsConfigWithResponseAsync(testId, requestOptions); } }
nit, as sample, consider whether use more realistic ID.
public static void main(String[] args) { LoadTestingClientBuilder builder = new LoadTestingClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("<endpoint>"); LoadTestAdministrationClient adminClient = builder.buildLoadTestAdministrationClient(); LoadTestRunClient testRunClient = builder.buildLoadTestRunClient(); final String testId = "11111111-1234-1234-1234-123456789abc"; final String testRunId = "22222222-1234-1234-1234-123456789abc"; final String testFileName = "test-script.jmx"; final String testFilePath = "C:/path/to/file/sample-script.jmx"; /* * BEGIN: Create test */ Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("displayName", "Sample Display Name"); testMap.put("description", "Sample Description"); Map<String, Object> loadTestConfigMap = new HashMap<String, Object>(); loadTestConfigMap.put("engineInstances", 1); testMap.put("loadTestConfiguration", loadTestConfigMap); Map<String, Object> envVarMap = new HashMap<String, Object>(); envVarMap.put("a", "b"); envVarMap.put("x", "y"); testMap.put("environmentVariables", envVarMap); Map<String, Object> secretMap = new HashMap<String, Object>(); Map<String, Object> sampleSecretMap = new HashMap<String, Object>(); sampleSecretMap.put("value", "https: sampleSecretMap.put("type", "AKV_SECRET_URI"); secretMap.put("sampleSecret", sampleSecretMap); testMap.put("secrets", secretMap); Map<String, Object> passFailMap = new HashMap<String, Object>(); Map<String, Object> passFailMetrics = new HashMap<String, Object>(); Map<String, Object> samplePassFailMetric = new HashMap<String, Object>(); samplePassFailMetric.put("clientmetric", "response_time_ms"); samplePassFailMetric.put("aggregate", "percentage"); samplePassFailMetric.put("condition", ">"); samplePassFailMetric.put("value", "20"); samplePassFailMetric.put("action", "continue"); passFailMetrics.put("fefd759d-7fe8-4f83-8b6d-aeebe0f491fe", samplePassFailMetric); passFailMap.put("passFailMetrics", passFailMetrics); testMap.put("passFailCriteria", passFailMap); BinaryData test = BinaryData.fromObject(testMap); Response<BinaryData> testOutResponse = adminClient.createOrUpdateTestWithResponse(testId, test, null); System.out.println(testOutResponse.getValue().toString()); /* * END: Create test */ /* * BEGIN: Upload test file */ BinaryData fileData = BinaryData.fromFile(new File(testFilePath).toPath()); PollResponse<BinaryData> fileUrlOut = adminClient.beginUploadTestFile(testId, testFileName, fileData, null).waitForCompletion(Duration.ofMinutes(2)); System.out.println(fileUrlOut.getValue().toString()); /* * END: Upload test file */ /* * BEGIN: Start test run */ Map<String, Object> testRunMap = new HashMap<String, Object>(); testRunMap.put("testId", testId); testRunMap.put("displayName", "SDK-Created-TestRun"); BinaryData testRun = BinaryData.fromObject(testRunMap); SyncPoller<BinaryData, BinaryData> testRunPoller = testRunClient.beginTestRun(testRunId, testRun, null); System.out.println(testRunPoller.poll().getValue().toString()); /* * END: Start test run */ /* * BEGIN: Stop test run */ try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { } Response<BinaryData> stoppedTestRunOut = testRunClient.stopTestRunWithResponse(testRunId, null); System.out.println(stoppedTestRunOut.getValue().toString()); /* * END: Stop test run */ /* * BEGIN: List metrics */ PollResponse<BinaryData> testRunOut = testRunPoller.poll(); JsonNode testRunJson = null; String testStatus = null, startDateTime = null, endDateTime = null; while (!testRunOut.getStatus().isComplete()) { testRunOut = testRunPoller.poll(); try { testRunJson = new ObjectMapper().readTree(testRunOut.getValue().toString()); testStatus = testRunJson.get("status").asText(); System.out.println("Status of test run: " + testStatus); } catch (JsonProcessingException e) { e.printStackTrace(); } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { } } try { testRunJson = new ObjectMapper().readTree(testRunPoller.getFinalResult().toString()); startDateTime = testRunJson.get("startDateTime").asText(); endDateTime = testRunJson.get("endDateTime").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } Response<BinaryData> metricNamespacesOut = testRunClient.listMetricNamespacesWithResponse(testRunId, null); String metricNamespace = null; try { JsonNode metricNamespacesJson = new ObjectMapper().readTree(metricNamespacesOut.getValue().toString()); metricNamespace = metricNamespacesJson.get("value").get(0).get("metricNamespaceName").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } Response<BinaryData> metricDefinitionsOut = testRunClient.listMetricDefinitionsWithResponse(testRunId, metricNamespace, null); String metricName = null; try { JsonNode metricDefinitionsJson = new ObjectMapper().readTree(metricDefinitionsOut.getValue().toString()); metricName = metricDefinitionsJson.get("value").get(0).get("name").get("value").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } PagedIterable<BinaryData> clientMetricsOut = testRunClient.listMetrics(testRunId, metricName, metricNamespace, startDateTime + '/' + endDateTime, null); clientMetricsOut.forEach((clientMetric) -> { System.out.println(clientMetric.toString()); }); /* * END: List metrics */ }
final String testRunId = "22222222-1234-1234-1234-123456789abc";
public static void main(String[] args) { LoadTestingClientBuilder builder = new LoadTestingClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("<endpoint>"); LoadTestAdministrationClient adminClient = builder.buildLoadTestAdministrationClient(); LoadTestRunClient testRunClient = builder.buildLoadTestRunClient(); final String testId = "6758667a-a57c-47e5-9cef-9b1f1432daca"; final String testRunId = "f758667a-c5ac-269a-dce1-5c1f14f2d142"; final String testFileName = "test-script.jmx"; final String testFilePath = "C:/path/to/file/sample-script.jmx"; /* * BEGIN: Create test */ Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("displayName", "Sample Display Name"); testMap.put("description", "Sample Description"); Map<String, Object> loadTestConfigMap = new HashMap<String, Object>(); loadTestConfigMap.put("engineInstances", 1); testMap.put("loadTestConfiguration", loadTestConfigMap); Map<String, Object> envVarMap = new HashMap<String, Object>(); envVarMap.put("a", "b"); envVarMap.put("x", "y"); testMap.put("environmentVariables", envVarMap); Map<String, Object> secretMap = new HashMap<String, Object>(); Map<String, Object> sampleSecretMap = new HashMap<String, Object>(); sampleSecretMap.put("value", "https: sampleSecretMap.put("type", "AKV_SECRET_URI"); secretMap.put("sampleSecret", sampleSecretMap); testMap.put("secrets", secretMap); Map<String, Object> passFailMap = new HashMap<String, Object>(); Map<String, Object> passFailMetrics = new HashMap<String, Object>(); Map<String, Object> samplePassFailMetric = new HashMap<String, Object>(); samplePassFailMetric.put("clientmetric", "response_time_ms"); samplePassFailMetric.put("aggregate", "percentage"); samplePassFailMetric.put("condition", ">"); samplePassFailMetric.put("value", "20"); samplePassFailMetric.put("action", "continue"); passFailMetrics.put("fefd759d-7fe8-4f83-8b6d-aeebe0f491fe", samplePassFailMetric); passFailMap.put("passFailMetrics", passFailMetrics); testMap.put("passFailCriteria", passFailMap); BinaryData test = BinaryData.fromObject(testMap); Response<BinaryData> testOutResponse = adminClient.createOrUpdateTestWithResponse(testId, test, null); System.out.println(testOutResponse.getValue().toString()); /* * END: Create test */ /* * BEGIN: Upload test file */ BinaryData fileData = BinaryData.fromFile(new File(testFilePath).toPath()); PollResponse<BinaryData> fileUrlOut = adminClient.beginUploadTestFile(testId, testFileName, fileData, null).waitForCompletion(Duration.ofMinutes(2)); System.out.println(fileUrlOut.getValue().toString()); /* * END: Upload test file */ /* * BEGIN: Start test run */ Map<String, Object> testRunMap = new HashMap<String, Object>(); testRunMap.put("testId", testId); testRunMap.put("displayName", "SDK-Created-TestRun"); BinaryData testRun = BinaryData.fromObject(testRunMap); SyncPoller<BinaryData, BinaryData> testRunPoller = testRunClient.beginTestRun(testRunId, testRun, null); System.out.println(testRunPoller.poll().getValue().toString()); /* * END: Start test run */ /* * BEGIN: Stop test run */ try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { } Response<BinaryData> stoppedTestRunOut = testRunClient.stopTestRunWithResponse(testRunId, null); System.out.println(stoppedTestRunOut.getValue().toString()); /* * END: Stop test run */ /* * BEGIN: List metrics */ PollResponse<BinaryData> testRunOut = testRunPoller.poll(); JsonNode testRunJson = null; String testStatus = null, startDateTime = null, endDateTime = null; while (!testRunOut.getStatus().isComplete()) { testRunOut = testRunPoller.poll(); try { testRunJson = new ObjectMapper().readTree(testRunOut.getValue().toString()); testStatus = testRunJson.get("status").asText(); System.out.println("Status of test run: " + testStatus); } catch (JsonProcessingException e) { e.printStackTrace(); } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { } } try { testRunJson = new ObjectMapper().readTree(testRunPoller.getFinalResult().toString()); startDateTime = testRunJson.get("startDateTime").asText(); endDateTime = testRunJson.get("endDateTime").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } Response<BinaryData> metricNamespacesOut = testRunClient.listMetricNamespacesWithResponse(testRunId, null); String metricNamespace = null; try { JsonNode metricNamespacesJson = new ObjectMapper().readTree(metricNamespacesOut.getValue().toString()); metricNamespace = metricNamespacesJson.get("value").get(0).get("metricNamespaceName").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } Response<BinaryData> metricDefinitionsOut = testRunClient.listMetricDefinitionsWithResponse(testRunId, metricNamespace, null); String metricName = null; try { JsonNode metricDefinitionsJson = new ObjectMapper().readTree(metricDefinitionsOut.getValue().toString()); metricName = metricDefinitionsJson.get("value").get(0).get("name").get("value").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } PagedIterable<BinaryData> clientMetricsOut = testRunClient.listMetrics(testRunId, metricName, metricNamespace, startDateTime + '/' + endDateTime, null); clientMetricsOut.forEach((clientMetric) -> { System.out.println(clientMetric.toString()); }); /* * END: List metrics */ }
class HelloWorld { /** * Authenticates with the load testing resource and shows how to list tests, test files and test runs * for a given resource. * * @param args Unused. Arguments to the program. * * @throws ClientAuthenticationException - when the credentials have insufficient permissions for load test resource. * @throws ResourceNotFoundException - when test with `testId` does not exist when listing files. */ }
class HelloWorld { /** * Authenticates with the load testing resource and shows how to list tests, test files and test runs * for a given resource. * * @param args Unused. Arguments to the program. * * @throws ClientAuthenticationException - when the credentials have insufficient permissions for load test resource. * @throws ResourceNotFoundException - when test with `testId` does not exist when listing files. */ }
Changed to random GUIDs
public static void main(String[] args) { LoadTestingClientBuilder builder = new LoadTestingClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("<endpoint>"); LoadTestAdministrationClient adminClient = builder.buildLoadTestAdministrationClient(); LoadTestRunClient testRunClient = builder.buildLoadTestRunClient(); final String testId = "11111111-1234-1234-1234-123456789abc"; final String testRunId = "22222222-1234-1234-1234-123456789abc"; final String testFileName = "test-script.jmx"; final String testFilePath = "C:/path/to/file/sample-script.jmx"; /* * BEGIN: Create test */ Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("displayName", "Sample Display Name"); testMap.put("description", "Sample Description"); Map<String, Object> loadTestConfigMap = new HashMap<String, Object>(); loadTestConfigMap.put("engineInstances", 1); testMap.put("loadTestConfiguration", loadTestConfigMap); Map<String, Object> envVarMap = new HashMap<String, Object>(); envVarMap.put("a", "b"); envVarMap.put("x", "y"); testMap.put("environmentVariables", envVarMap); Map<String, Object> secretMap = new HashMap<String, Object>(); Map<String, Object> sampleSecretMap = new HashMap<String, Object>(); sampleSecretMap.put("value", "https: sampleSecretMap.put("type", "AKV_SECRET_URI"); secretMap.put("sampleSecret", sampleSecretMap); testMap.put("secrets", secretMap); Map<String, Object> passFailMap = new HashMap<String, Object>(); Map<String, Object> passFailMetrics = new HashMap<String, Object>(); Map<String, Object> samplePassFailMetric = new HashMap<String, Object>(); samplePassFailMetric.put("clientmetric", "response_time_ms"); samplePassFailMetric.put("aggregate", "percentage"); samplePassFailMetric.put("condition", ">"); samplePassFailMetric.put("value", "20"); samplePassFailMetric.put("action", "continue"); passFailMetrics.put("fefd759d-7fe8-4f83-8b6d-aeebe0f491fe", samplePassFailMetric); passFailMap.put("passFailMetrics", passFailMetrics); testMap.put("passFailCriteria", passFailMap); BinaryData test = BinaryData.fromObject(testMap); Response<BinaryData> testOutResponse = adminClient.createOrUpdateTestWithResponse(testId, test, null); System.out.println(testOutResponse.getValue().toString()); /* * END: Create test */ /* * BEGIN: Upload test file */ BinaryData fileData = BinaryData.fromFile(new File(testFilePath).toPath()); PollResponse<BinaryData> fileUrlOut = adminClient.beginUploadTestFile(testId, testFileName, fileData, null).waitForCompletion(Duration.ofMinutes(2)); System.out.println(fileUrlOut.getValue().toString()); /* * END: Upload test file */ /* * BEGIN: Start test run */ Map<String, Object> testRunMap = new HashMap<String, Object>(); testRunMap.put("testId", testId); testRunMap.put("displayName", "SDK-Created-TestRun"); BinaryData testRun = BinaryData.fromObject(testRunMap); SyncPoller<BinaryData, BinaryData> testRunPoller = testRunClient.beginTestRun(testRunId, testRun, null); System.out.println(testRunPoller.poll().getValue().toString()); /* * END: Start test run */ /* * BEGIN: Stop test run */ try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { } Response<BinaryData> stoppedTestRunOut = testRunClient.stopTestRunWithResponse(testRunId, null); System.out.println(stoppedTestRunOut.getValue().toString()); /* * END: Stop test run */ /* * BEGIN: List metrics */ PollResponse<BinaryData> testRunOut = testRunPoller.poll(); JsonNode testRunJson = null; String testStatus = null, startDateTime = null, endDateTime = null; while (!testRunOut.getStatus().isComplete()) { testRunOut = testRunPoller.poll(); try { testRunJson = new ObjectMapper().readTree(testRunOut.getValue().toString()); testStatus = testRunJson.get("status").asText(); System.out.println("Status of test run: " + testStatus); } catch (JsonProcessingException e) { e.printStackTrace(); } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { } } try { testRunJson = new ObjectMapper().readTree(testRunPoller.getFinalResult().toString()); startDateTime = testRunJson.get("startDateTime").asText(); endDateTime = testRunJson.get("endDateTime").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } Response<BinaryData> metricNamespacesOut = testRunClient.listMetricNamespacesWithResponse(testRunId, null); String metricNamespace = null; try { JsonNode metricNamespacesJson = new ObjectMapper().readTree(metricNamespacesOut.getValue().toString()); metricNamespace = metricNamespacesJson.get("value").get(0).get("metricNamespaceName").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } Response<BinaryData> metricDefinitionsOut = testRunClient.listMetricDefinitionsWithResponse(testRunId, metricNamespace, null); String metricName = null; try { JsonNode metricDefinitionsJson = new ObjectMapper().readTree(metricDefinitionsOut.getValue().toString()); metricName = metricDefinitionsJson.get("value").get(0).get("name").get("value").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } PagedIterable<BinaryData> clientMetricsOut = testRunClient.listMetrics(testRunId, metricName, metricNamespace, startDateTime + '/' + endDateTime, null); clientMetricsOut.forEach((clientMetric) -> { System.out.println(clientMetric.toString()); }); /* * END: List metrics */ }
final String testRunId = "22222222-1234-1234-1234-123456789abc";
public static void main(String[] args) { LoadTestingClientBuilder builder = new LoadTestingClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint("<endpoint>"); LoadTestAdministrationClient adminClient = builder.buildLoadTestAdministrationClient(); LoadTestRunClient testRunClient = builder.buildLoadTestRunClient(); final String testId = "6758667a-a57c-47e5-9cef-9b1f1432daca"; final String testRunId = "f758667a-c5ac-269a-dce1-5c1f14f2d142"; final String testFileName = "test-script.jmx"; final String testFilePath = "C:/path/to/file/sample-script.jmx"; /* * BEGIN: Create test */ Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("displayName", "Sample Display Name"); testMap.put("description", "Sample Description"); Map<String, Object> loadTestConfigMap = new HashMap<String, Object>(); loadTestConfigMap.put("engineInstances", 1); testMap.put("loadTestConfiguration", loadTestConfigMap); Map<String, Object> envVarMap = new HashMap<String, Object>(); envVarMap.put("a", "b"); envVarMap.put("x", "y"); testMap.put("environmentVariables", envVarMap); Map<String, Object> secretMap = new HashMap<String, Object>(); Map<String, Object> sampleSecretMap = new HashMap<String, Object>(); sampleSecretMap.put("value", "https: sampleSecretMap.put("type", "AKV_SECRET_URI"); secretMap.put("sampleSecret", sampleSecretMap); testMap.put("secrets", secretMap); Map<String, Object> passFailMap = new HashMap<String, Object>(); Map<String, Object> passFailMetrics = new HashMap<String, Object>(); Map<String, Object> samplePassFailMetric = new HashMap<String, Object>(); samplePassFailMetric.put("clientmetric", "response_time_ms"); samplePassFailMetric.put("aggregate", "percentage"); samplePassFailMetric.put("condition", ">"); samplePassFailMetric.put("value", "20"); samplePassFailMetric.put("action", "continue"); passFailMetrics.put("fefd759d-7fe8-4f83-8b6d-aeebe0f491fe", samplePassFailMetric); passFailMap.put("passFailMetrics", passFailMetrics); testMap.put("passFailCriteria", passFailMap); BinaryData test = BinaryData.fromObject(testMap); Response<BinaryData> testOutResponse = adminClient.createOrUpdateTestWithResponse(testId, test, null); System.out.println(testOutResponse.getValue().toString()); /* * END: Create test */ /* * BEGIN: Upload test file */ BinaryData fileData = BinaryData.fromFile(new File(testFilePath).toPath()); PollResponse<BinaryData> fileUrlOut = adminClient.beginUploadTestFile(testId, testFileName, fileData, null).waitForCompletion(Duration.ofMinutes(2)); System.out.println(fileUrlOut.getValue().toString()); /* * END: Upload test file */ /* * BEGIN: Start test run */ Map<String, Object> testRunMap = new HashMap<String, Object>(); testRunMap.put("testId", testId); testRunMap.put("displayName", "SDK-Created-TestRun"); BinaryData testRun = BinaryData.fromObject(testRunMap); SyncPoller<BinaryData, BinaryData> testRunPoller = testRunClient.beginTestRun(testRunId, testRun, null); System.out.println(testRunPoller.poll().getValue().toString()); /* * END: Start test run */ /* * BEGIN: Stop test run */ try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { } Response<BinaryData> stoppedTestRunOut = testRunClient.stopTestRunWithResponse(testRunId, null); System.out.println(stoppedTestRunOut.getValue().toString()); /* * END: Stop test run */ /* * BEGIN: List metrics */ PollResponse<BinaryData> testRunOut = testRunPoller.poll(); JsonNode testRunJson = null; String testStatus = null, startDateTime = null, endDateTime = null; while (!testRunOut.getStatus().isComplete()) { testRunOut = testRunPoller.poll(); try { testRunJson = new ObjectMapper().readTree(testRunOut.getValue().toString()); testStatus = testRunJson.get("status").asText(); System.out.println("Status of test run: " + testStatus); } catch (JsonProcessingException e) { e.printStackTrace(); } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { } } try { testRunJson = new ObjectMapper().readTree(testRunPoller.getFinalResult().toString()); startDateTime = testRunJson.get("startDateTime").asText(); endDateTime = testRunJson.get("endDateTime").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } Response<BinaryData> metricNamespacesOut = testRunClient.listMetricNamespacesWithResponse(testRunId, null); String metricNamespace = null; try { JsonNode metricNamespacesJson = new ObjectMapper().readTree(metricNamespacesOut.getValue().toString()); metricNamespace = metricNamespacesJson.get("value").get(0).get("metricNamespaceName").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } Response<BinaryData> metricDefinitionsOut = testRunClient.listMetricDefinitionsWithResponse(testRunId, metricNamespace, null); String metricName = null; try { JsonNode metricDefinitionsJson = new ObjectMapper().readTree(metricDefinitionsOut.getValue().toString()); metricName = metricDefinitionsJson.get("value").get(0).get("name").get("value").asText(); } catch (JsonProcessingException e) { e.printStackTrace(); } PagedIterable<BinaryData> clientMetricsOut = testRunClient.listMetrics(testRunId, metricName, metricNamespace, startDateTime + '/' + endDateTime, null); clientMetricsOut.forEach((clientMetric) -> { System.out.println(clientMetric.toString()); }); /* * END: List metrics */ }
class HelloWorld { /** * Authenticates with the load testing resource and shows how to list tests, test files and test runs * for a given resource. * * @param args Unused. Arguments to the program. * * @throws ClientAuthenticationException - when the credentials have insufficient permissions for load test resource. * @throws ResourceNotFoundException - when test with `testId` does not exist when listing files. */ }
class HelloWorld { /** * Authenticates with the load testing resource and shows how to list tests, test files and test runs * for a given resource. * * @param args Unused. Arguments to the program. * * @throws ClientAuthenticationException - when the credentials have insufficient permissions for load test resource. * @throws ResourceNotFoundException - when test with `testId` does not exist when listing files. */ }
```suggestion Objects.requireNonNull(streamName, "'streamName' cannot be null."); ```
private Mono<UploadLogsResult> splitAndUpload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { try { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (logs.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'logs' cannot be empty.")); } ObjectSerializer serializer = DEFAULT_SERIALIZER; int concurrency = 1; if (options != null) { if (options.getObjectSerializer() != null) { serializer = options.getObjectSerializer(); } if (options.getMaxConcurrency() != null) { concurrency = options.getMaxConcurrency(); } } List<List<Object>> logBatches = new ArrayList<>(); List<byte[]> requests = createGzipRequests(logs, serializer, logBatches); RequestOptions requestOptions = new RequestOptions() .addHeader(CONTENT_ENCODING, GZIP) .setContext(context); Iterator<List<Object>> logBatchesIterator = logBatches.iterator(); return Flux.fromIterable(requests) .flatMapSequential(bytes -> uploadToService(ruleId, streamName, requestOptions, bytes), concurrency) .map(responseHolder -> mapResult(logBatchesIterator, responseHolder)) .collectList() .map(this::createResponse); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } }
Objects.requireNonNull(ruleId, "'streamName' cannot be null.");
private Mono<UploadLogsResult> splitAndUpload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { try { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(streamName, "'streamName' cannot be null."); Objects.requireNonNull(logs, "'logs' cannot be null."); if (logs.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'logs' cannot be empty.")); } ObjectSerializer serializer = DEFAULT_SERIALIZER; int concurrency = 1; if (options != null) { if (options.getObjectSerializer() != null) { serializer = options.getObjectSerializer(); } if (options.getMaxConcurrency() != null) { concurrency = options.getMaxConcurrency(); } } List<List<Object>> logBatches = new ArrayList<>(); List<byte[]> requests = createGzipRequests(logs, serializer, logBatches); RequestOptions requestOptions = new RequestOptions() .addHeader(CONTENT_ENCODING, GZIP) .setContext(context); Iterator<List<Object>> logBatchesIterator = logBatches.iterator(); return Flux.fromIterable(requests) .flatMapSequential(bytes -> uploadToService(ruleId, streamName, requestOptions, bytes), concurrency) .map(responseHolder -> mapResult(logBatchesIterator, responseHolder)) .collectList() .map(this::createResponse); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } }
class LogsIngestionAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionAsyncClient.class); private static final String CONTENT_ENCODING = "Content-Encoding"; private static final long MAX_REQUEST_PAYLOAD_SIZE = 1024 * 1024; private static final String GZIP = "gzip"; private static final JsonSerializer DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(true); private final IngestionUsingDataCollectionRulesAsyncClient service; LogsIngestionAsyncClient(IngestionUsingDataCollectionRulesAsyncClient service) { this.service = service; } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * <pre> * List&lt;Object&gt; logs = getLogs& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs) { return upload(ruleId, streamName, logs, new UploadLogsOptions()); } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * <pre> * List&lt;Object&gt; logs = getLogs& * UploadLogsOptions uploadLogsOptions = new UploadLogsOptions& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @param options the options to configure the upload request. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options) { return withContext(context -> upload(ruleId, streamName, logs, options, context)); } /** * See error response code and error response message for more detail. * * <p><strong>Header Parameters</strong> * * <table border="1"> * <caption>Header Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>Content-Encoding</td><td>String</td><td>No</td><td>gzip</td></tr> * <tr><td>x-ms-client-request-id</td><td>String</td><td>No</td><td>Client request Id</td></tr> * </table> * * <p><strong>Request Body Schema</strong> * * <pre>{@code * [ * Object * ] * }</pre> * * @param ruleId The immutable Id of the Data Collection Rule resource. * @param streamName The streamDeclaration name as defined in the Data Collection Rule. * @param logs An array of objects matching the schema defined by the provided stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> uploadWithResponse( String ruleId, String streamName, BinaryData logs, RequestOptions requestOptions) { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.addRequestCallback(request -> { HttpHeader httpHeader = request.getHeaders().get(CONTENT_ENCODING); if (httpHeader == null) { BinaryData gzippedRequest = BinaryData.fromBytes(gzipRequest(logs.toBytes())); request.setBody(gzippedRequest); request.setHeader(CONTENT_ENCODING, GZIP); } }); return service.uploadWithResponse(ruleId, streamName, logs, requestOptions); } Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { return Mono.defer(() -> splitAndUpload(ruleId, streamName, logs, options, context)); } private UploadLogsResult mapResult(Iterator<List<Object>> logBatchesIterator, UploadLogsResponseHolder responseHolder) { List<Object> logsBatch = logBatchesIterator.next(); if (responseHolder.getStatus() == UploadLogsStatus.FAILURE) { return new UploadLogsResult(responseHolder.getStatus(), Collections.singletonList(new UploadLogsError(responseHolder.getResponseError(), logsBatch))); } return new UploadLogsResult(UploadLogsStatus.SUCCESS, null); } private Mono<UploadLogsResponseHolder> uploadToService(String ruleId, String streamName, RequestOptions requestOptions, byte[] bytes) { return service.uploadWithResponse(ruleId, streamName, BinaryData.fromBytes(bytes), requestOptions) .map(response -> new UploadLogsResponseHolder(UploadLogsStatus.SUCCESS, null)) .onErrorResume(HttpResponseException.class, ex -> Mono.fromSupplier(() -> new UploadLogsResponseHolder(UploadLogsStatus.FAILURE, mapToResponseError(ex)))); } /** * Method to map the exception to {@link ResponseError}. * @param ex the {@link HttpResponseException}. * @return the mapped {@link ResponseError}. */ private ResponseError mapToResponseError(HttpResponseException ex) { ResponseError responseError = null; if (ex.getValue() instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> errorMap = (LinkedHashMap<String, Object>) ex.getValue(); if (errorMap.containsKey("error")) { Object error = errorMap.get("error"); if (error instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, String> errorDetails = (LinkedHashMap<String, String>) error; if (errorDetails.containsKey("code") && errorDetails.containsKey("message")) { responseError = new ResponseError(errorDetails.get("code"), errorDetails.get("message")); } } } } return responseError; } private UploadLogsResult createResponse(List<UploadLogsResult> results) { int failureCount = 0; List<UploadLogsError> errors = new ArrayList<>(); for (UploadLogsResult result : results) { if (result.getStatus() != UploadLogsStatus.SUCCESS) { failureCount++; errors.addAll(result.getErrors()); } } if (failureCount == 0) { return new UploadLogsResult(UploadLogsStatus.SUCCESS, errors); } if (failureCount < results.size()) { return new UploadLogsResult(UploadLogsStatus.PARTIAL_FAILURE, errors); } return new UploadLogsResult(UploadLogsStatus.FAILURE, errors); } private List<byte[]> createGzipRequests(List<Object> logs, ObjectSerializer serializer, List<List<Object>> logBatches) { try { List<byte[]> requests = new ArrayList<>(); long currentBatchSize = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JsonGenerator generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); List<String> serializedLogs = new ArrayList<>(); int currentBatchStart = 0; for (int i = 0; i < logs.size(); i++) { byte[] bytes = serializer.serializeToBytes(logs.get(i)); int currentLogSize = bytes.length; currentBatchSize += currentLogSize; if (currentBatchSize > MAX_REQUEST_PAYLOAD_SIZE) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); byteArrayOutputStream = new ByteArrayOutputStream(); generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); currentBatchSize = currentLogSize; serializedLogs.clear(); logBatches.add(logs.subList(currentBatchStart, i)); currentBatchStart = i; } serializedLogs.add(new String(bytes, StandardCharsets.UTF_8)); } if (currentBatchSize > 0) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); logBatches.add(logs.subList(currentBatchStart, logs.size())); } return requests; } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } private void writeLogsAndCloseJsonGenerator(JsonGenerator generator, List<String> serializedLogs) throws IOException { generator.writeRaw(serializedLogs.stream() .collect(Collectors.joining(","))); generator.writeEndArray(); generator.close(); } /** * Gzips the input byte array. * @param bytes The input byte array. * @return gzipped byte array. */ private byte[] gzipRequest(byte[] bytes) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (GZIPOutputStream zip = new GZIPOutputStream(byteArrayOutputStream)) { zip.write(bytes); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } return byteArrayOutputStream.toByteArray(); } }
class LogsIngestionAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionAsyncClient.class); private static final String CONTENT_ENCODING = "Content-Encoding"; private static final long MAX_REQUEST_PAYLOAD_SIZE = 1024 * 1024; private static final String GZIP = "gzip"; private static final JsonSerializer DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(true); private final IngestionUsingDataCollectionRulesAsyncClient service; LogsIngestionAsyncClient(IngestionUsingDataCollectionRulesAsyncClient service) { this.service = service; } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * <pre> * List&lt;Object&gt; logs = getLogs& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs) { return upload(ruleId, streamName, logs, new UploadLogsOptions()); } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * <pre> * List&lt;Object&gt; logs = getLogs& * UploadLogsOptions uploadLogsOptions = new UploadLogsOptions& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @param options the options to configure the upload request. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options) { return withContext(context -> upload(ruleId, streamName, logs, options, context)); } /** * See error response code and error response message for more detail. * * <p><strong>Header Parameters</strong> * * <table border="1"> * <caption>Header Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>Content-Encoding</td><td>String</td><td>No</td><td>gzip</td></tr> * <tr><td>x-ms-client-request-id</td><td>String</td><td>No</td><td>Client request Id</td></tr> * </table> * * <p><strong>Request Body Schema</strong> * * <pre>{@code * [ * Object * ] * }</pre> * * @param ruleId The immutable Id of the Data Collection Rule resource. * @param streamName The streamDeclaration name as defined in the Data Collection Rule. * @param logs An array of objects matching the schema defined by the provided stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> uploadWithResponse( String ruleId, String streamName, BinaryData logs, RequestOptions requestOptions) { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.addRequestCallback(request -> { HttpHeader httpHeader = request.getHeaders().get(CONTENT_ENCODING); if (httpHeader == null) { BinaryData gzippedRequest = BinaryData.fromBytes(gzipRequest(logs.toBytes())); request.setBody(gzippedRequest); request.setHeader(CONTENT_ENCODING, GZIP); } }); return service.uploadWithResponse(ruleId, streamName, logs, requestOptions); } Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { return Mono.defer(() -> splitAndUpload(ruleId, streamName, logs, options, context)); } private UploadLogsResult mapResult(Iterator<List<Object>> logBatchesIterator, UploadLogsResponseHolder responseHolder) { List<Object> logsBatch = logBatchesIterator.next(); if (responseHolder.getStatus() == UploadLogsStatus.FAILURE) { return new UploadLogsResult(responseHolder.getStatus(), Collections.singletonList(new UploadLogsError(responseHolder.getResponseError(), logsBatch))); } return new UploadLogsResult(UploadLogsStatus.SUCCESS, null); } private Mono<UploadLogsResponseHolder> uploadToService(String ruleId, String streamName, RequestOptions requestOptions, byte[] bytes) { return service.uploadWithResponse(ruleId, streamName, BinaryData.fromBytes(bytes), requestOptions) .map(response -> new UploadLogsResponseHolder(UploadLogsStatus.SUCCESS, null)) .onErrorResume(HttpResponseException.class, ex -> Mono.fromSupplier(() -> new UploadLogsResponseHolder(UploadLogsStatus.FAILURE, mapToResponseError(ex)))); } /** * Method to map the exception to {@link ResponseError}. * @param ex the {@link HttpResponseException}. * @return the mapped {@link ResponseError}. */ private ResponseError mapToResponseError(HttpResponseException ex) { ResponseError responseError = null; if (ex.getValue() instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> errorMap = (LinkedHashMap<String, Object>) ex.getValue(); if (errorMap.containsKey("error")) { Object error = errorMap.get("error"); if (error instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, String> errorDetails = (LinkedHashMap<String, String>) error; if (errorDetails.containsKey("code") && errorDetails.containsKey("message")) { responseError = new ResponseError(errorDetails.get("code"), errorDetails.get("message")); } } } } return responseError; } private UploadLogsResult createResponse(List<UploadLogsResult> results) { int failureCount = 0; List<UploadLogsError> errors = new ArrayList<>(); for (UploadLogsResult result : results) { if (result.getStatus() != UploadLogsStatus.SUCCESS) { failureCount++; errors.addAll(result.getErrors()); } } if (failureCount == 0) { return new UploadLogsResult(UploadLogsStatus.SUCCESS, errors); } if (failureCount < results.size()) { return new UploadLogsResult(UploadLogsStatus.PARTIAL_FAILURE, errors); } return new UploadLogsResult(UploadLogsStatus.FAILURE, errors); } private List<byte[]> createGzipRequests(List<Object> logs, ObjectSerializer serializer, List<List<Object>> logBatches) { try { List<byte[]> requests = new ArrayList<>(); long currentBatchSize = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JsonGenerator generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); List<String> serializedLogs = new ArrayList<>(); int currentBatchStart = 0; for (int i = 0; i < logs.size(); i++) { byte[] bytes = serializer.serializeToBytes(logs.get(i)); int currentLogSize = bytes.length; currentBatchSize += currentLogSize; if (currentBatchSize > MAX_REQUEST_PAYLOAD_SIZE) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); byteArrayOutputStream = new ByteArrayOutputStream(); generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); currentBatchSize = currentLogSize; serializedLogs.clear(); logBatches.add(logs.subList(currentBatchStart, i)); currentBatchStart = i; } serializedLogs.add(new String(bytes, StandardCharsets.UTF_8)); } if (currentBatchSize > 0) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); logBatches.add(logs.subList(currentBatchStart, logs.size())); } return requests; } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } private void writeLogsAndCloseJsonGenerator(JsonGenerator generator, List<String> serializedLogs) throws IOException { generator.writeRaw(serializedLogs.stream() .collect(Collectors.joining(","))); generator.writeEndArray(); generator.close(); } /** * Gzips the input byte array. * @param bytes The input byte array. * @return gzipped byte array. */ private byte[] gzipRequest(byte[] bytes) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (GZIPOutputStream zip = new GZIPOutputStream(byteArrayOutputStream)) { zip.write(bytes); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } return byteArrayOutputStream.toByteArray(); } }
What would be the type of this case?
Set<String> getRoles(JWTClaimsSet set) { if (set == null) { return Collections.emptySet(); } Object rolesClaim = set.getClaim(AadJwtClaimNames.ROLES); if (rolesClaim == null) { return Collections.emptySet(); } if (rolesClaim instanceof Iterable<?>) { return StreamSupport.stream(((Iterable<?>) rolesClaim).spliterator(), false) .map(Object::toString) .collect(Collectors.toSet()); } return Stream.of(rolesClaim) .map(Object::toString) .collect(Collectors.toSet()); }
.collect(Collectors.toSet());
Set<String> getRoles(JWTClaimsSet set) { if (set == null) { return Collections.emptySet(); } Object rolesClaim = set.getClaim(AadJwtClaimNames.ROLES); if (rolesClaim == null) { return Collections.emptySet(); } if (rolesClaim instanceof Iterable<?>) { return StreamSupport.stream(((Iterable<?>) rolesClaim).spliterator(), false) .map(Object::toString) .collect(Collectors.toSet()); } return Stream.of(rolesClaim) .map(Object::toString) .collect(Collectors.toSet()); }
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private static final String MSG_MALFORMED_AD_KEY_DISCOVERY_URI = "Failed to parse active directory key discovery uri."; private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException(MSG_MALFORMED_AD_KEY_DISCOVERY_URI, e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private static final String MSG_MALFORMED_AD_KEY_DISCOVERY_URI = "Failed to parse active directory key discovery uri."; private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException(MSG_MALFORMED_AD_KEY_DISCOVERY_URI, e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
All other types except `Iterable<?>`.
Set<String> getRoles(JWTClaimsSet set) { if (set == null) { return Collections.emptySet(); } Object rolesClaim = set.getClaim(AadJwtClaimNames.ROLES); if (rolesClaim == null) { return Collections.emptySet(); } if (rolesClaim instanceof Iterable<?>) { return StreamSupport.stream(((Iterable<?>) rolesClaim).spliterator(), false) .map(Object::toString) .collect(Collectors.toSet()); } return Stream.of(rolesClaim) .map(Object::toString) .collect(Collectors.toSet()); }
.collect(Collectors.toSet());
Set<String> getRoles(JWTClaimsSet set) { if (set == null) { return Collections.emptySet(); } Object rolesClaim = set.getClaim(AadJwtClaimNames.ROLES); if (rolesClaim == null) { return Collections.emptySet(); } if (rolesClaim instanceof Iterable<?>) { return StreamSupport.stream(((Iterable<?>) rolesClaim).spliterator(), false) .map(Object::toString) .collect(Collectors.toSet()); } return Stream.of(rolesClaim) .map(Object::toString) .collect(Collectors.toSet()); }
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private static final String MSG_MALFORMED_AD_KEY_DISCOVERY_URI = "Failed to parse active directory key discovery uri."; private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException(MSG_MALFORMED_AD_KEY_DISCOVERY_URI, e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
class UserPrincipalManager { private static final Logger LOGGER = LoggerFactory.getLogger(UserPrincipalManager.class); private static final String LOGIN_MICROSOFT_ONLINE_ISSUER = "https: private static final String STS_WINDOWS_ISSUER = "https: private static final String STS_CHINA_CLOUD_API_ISSUER = "https: private static final String MSG_MALFORMED_AD_KEY_DISCOVERY_URI = "Failed to parse active directory key discovery uri."; private final JWKSource<SecurityContext> keySource; private final AadAuthenticationProperties aadAuthenticationProperties; private final boolean explicitAudienceCheck; private final Set<String> validAudiences = new HashSet<>(); /** * ø Creates a new {@link UserPrincipalManager} with a predefined {@link JWKSource}. * <p> * This is helpful in cases the JWK is not a remote JWKSet or for unit testing. * * @param keySource - {@link JWKSource} containing at least one key */ public UserPrincipalManager(JWKSource<SecurityContext> keySource) { this.keySource = keySource; this.explicitAudienceCheck = false; this.aadAuthenticationProperties = null; } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * * @param endpoints - used to retrieve the JWKS URL * @param aadAuthenticationProperties - used to retrieve the environment. * @param resourceRetriever - configures the {@link RemoteJWKSet} call. * @param explicitAudienceCheck Whether explicitly check the audience. * @throws IllegalArgumentException If AAD key discovery URI is malformed. */ public UserPrincipalManager(AadAuthorizationServerEndpoints endpoints, AadAuthenticationProperties aadAuthenticationProperties, ResourceRetriever resourceRetriever, boolean explicitAudienceCheck) { this.aadAuthenticationProperties = aadAuthenticationProperties; this.explicitAudienceCheck = explicitAudienceCheck; if (explicitAudienceCheck) { this.validAudiences.add(this.aadAuthenticationProperties.getCredential().getClientId()); this.validAudiences.add(this.aadAuthenticationProperties.getAppIdUri()); } try { String jwkSetEndpoint = endpoints.getJwkSetEndpoint(); keySource = new RemoteJWKSet<>(new URL(jwkSetEndpoint), resourceRetriever); } catch (MalformedURLException e) { throw new IllegalArgumentException(MSG_MALFORMED_AD_KEY_DISCOVERY_URI, e); } } /** * Create a new {@link UserPrincipalManager} based of the * {@link AadAuthorizationServerEndpoints * ()}
This should be guten tag, in german. Let's just remove this
public void run() throws InterruptedException { AtomicBoolean sampleSuccessful = new AtomicBoolean(false); CountDownLatch countdownLatch = new CountDownLatch(1); String sessionId = "greetings-id"; ServiceBusClientBuilder builder = new ServiceBusClientBuilder() .connectionString(connectionString); ServiceBusSenderAsyncClient sender = builder .sender() .queueName(queueName) .buildAsyncClient(); List<ServiceBusMessage> messages = Arrays.asList( new ServiceBusMessage(BinaryData.fromBytes("Hello".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Bonjour".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Gluten tag".getBytes(UTF_8))).setSessionId(sessionId) ); sender.sendMessages(messages).subscribe(unused -> System.out.println("Batch sent."), error -> System.err.println("Error occurred while publishing message batch: " + error), () -> { System.out.println("Batch send complete."); sampleSuccessful.set(true); }); countdownLatch.await(10, TimeUnit.SECONDS); sender.close(); Assertions.assertTrue(sampleSuccessful.get()); }
new ServiceBusMessage(BinaryData.fromBytes("Gluten tag".getBytes(UTF_8))).setSessionId(sessionId)
public void run() throws InterruptedException { AtomicBoolean sampleSuccessful = new AtomicBoolean(false); CountDownLatch countdownLatch = new CountDownLatch(1); String sessionId = "greetings-id"; ServiceBusClientBuilder builder = new ServiceBusClientBuilder() .connectionString(connectionString); ServiceBusSenderAsyncClient sender = builder .sender() .queueName(queueName) .buildAsyncClient(); List<ServiceBusMessage> messages = Arrays.asList( new ServiceBusMessage(BinaryData.fromBytes("Hello".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Bonjour".getBytes(UTF_8))).setSessionId(sessionId) ); sender.sendMessages(messages).subscribe(unused -> System.out.println("Batch sent."), error -> System.err.println("Error occurred while publishing message batch: " + error), () -> { System.out.println("Batch send complete."); sampleSuccessful.set(true); }); countdownLatch.await(10, TimeUnit.SECONDS); sender.close(); Assertions.assertTrue(sampleSuccessful.get()); }
class SendSessionMessageAsyncSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); /** * Main method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @param args Unused arguments to the program. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ public static void main(String[] args) throws InterruptedException { SendSessionMessageAsyncSample sample = new SendSessionMessageAsyncSample(); sample.run(); } /** * This method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ @Test }
class SendSessionMessageAsyncSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); /** * Main method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @param args Unused arguments to the program. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ public static void main(String[] args) throws InterruptedException { SendSessionMessageAsyncSample sample = new SendSessionMessageAsyncSample(); sample.run(); } /** * This method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ @Test }
Let's change the wording here to something like : "The cause is completionLock's acquire method is stuck. So we have added a timeout for acquiring the lock, to work around the issue."
public void close() { if (isDisposed.get()) { return; } try { boolean acquired = completionLock.tryAcquire(5, TimeUnit.SECONDS); if (!acquired) { LOGGER.info("Unable to obtain completion lock."); } } catch (InterruptedException e) { LOGGER.info("Unable to obtain completion lock.", e); } if (isDisposed.getAndSet(true)) { return; } LOGGER.info("Removing receiver links."); final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null); if (disposed != null) { disposed.close(); } if (sessionManager != null) { sessionManager.close(); } managementNodeLocks.close(); renewalContainer.close(); if (trackSettlementSequenceNumber != null) { try { trackSettlementSequenceNumber.close(); } catch (Exception e) { LOGGER.info("Unable to close settlement sequence number subscription.", e); } } onClientClose.run(); }
public void close() { if (isDisposed.get()) { return; } try { boolean acquired = completionLock.tryAcquire(5, TimeUnit.SECONDS); if (!acquired) { LOGGER.info("Unable to obtain completion lock."); } } catch (InterruptedException e) { LOGGER.info("Unable to obtain completion lock.", e); } if (isDisposed.getAndSet(true)) { return; } LOGGER.info("Removing receiver links."); final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null); if (disposed != null) { disposed.close(); } if (sessionManager != null) { sessionManager.close(); } managementNodeLocks.close(); renewalContainer.close(); if (trackSettlementSequenceNumber != null) { try { trackSettlementSequenceNumber.close(); } catch (Exception e) { LOGGER.info("Unable to close settlement sequence number subscription.", e); } } onClientClose.run(); }
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private static final String TRANSACTION_LINK_NAME = "coordinator"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final LockContainer<LockRenewalOperation> renewalContainer; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final LockContainer<OffsetDateTime> managementNodeLocks; private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager sessionManager; private final Semaphore completionLock = new Semaphore(1); private final String identifier; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1); private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>(); private final AutoCloseable trackSettlementSequenceNumber; /** * Creates a receiver that listens to a Service Bus resource. * * @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource. * @param entityPath The name of the topic or queue. * @param entityType The type of the Service Bus resource. * @param receiverOptions Options when receiving messages. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param instrumentation ServiceBus tracing and metrics helper * @param messageSerializer Serializes and deserializes Service Bus messages. * @param onClientClose Operation to run when the client completes. */ ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.sessionManager = null; this.identifier = identifier; this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, ServiceBusSessionManager sessionManager) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null."); this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atInfo() .addKeyValue(SESSION_ID_KEY, renewal.getSessionId()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.identifier = sessionManager.getIdentifier(); this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return entityPath; } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return receiverOptions.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}. */ public String getIdentifier() { return identifier; } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus abandon operation completes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, null, null); } /** * Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @return A {@link Mono} that completes when the Service Bus operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.ABANDONED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, null); } /** * Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from * the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, options.getTransactionContext()); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus defer operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, null, null); } /** * Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into * the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @return A {@link Mono} that completes when the defer operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.DEFERRED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(), options.getDeadLetterErrorDescription(), options.getPropertiesToModify(), options.getTransactionContext()); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or an empty Mono if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed. * @throws ServiceBusException if the session state could not be acquired. */ public Mono<byte[]> getSessionState() { return getSessionState(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage() { return peekMessage(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if the receiver is disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek"))); } Mono<ServiceBusReceivedMessage> result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> { final long sequence = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequence) .log("Peek message."); return channel.peek(sequence, sessionId, getLinkName(sessionId)); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)) .handle((message, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, message.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Updating last peeked sequence number."); sink.next(message); }); return tracer.traceManagementReceive("ServiceBus.peekMessage", result, ServiceBusReceivedMessage::getContext); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) { return peekMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt"))); } return tracer.traceManagementReceive("ServiceBus.peekMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)), ServiceBusReceivedMessage::getContext); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return tracer.traceSyncReceive("ServiceBus.peekMessages", peekMessages(maxMessages, receiverOptions.getSessionId())); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> { final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch."); final Flux<ServiceBusReceivedMessage> messages = node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages); final Mono<ServiceBusReceivedMessage> handle = messages .switchIfEmpty(Mono.fromCallable(() -> { ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(BinaryData .fromBytes(new byte[0])); emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get()); return emptyMessage; })) .last() .handle((last, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, last.getSequenceNumber())); LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, current).log("Last peeked sequence number in batch."); sink.complete(); }); return Flux.merge(messages, handle); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return tracer.traceSyncReceive("ServiceBus.peekMessages", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages)) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. */ public Flux<ServiceBusReceivedMessage> receiveMessages() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages"))); } return receiveMessagesNoBackPressure().limitRate(1, 0); } Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() { return receiveMessagesWithContext(0) .handle((serviceBusMessageContext, sink) -> { if (serviceBusMessageContext.hasError()) { sink.error(serviceBusMessageContext.getThrowable()); return; } sink.next(serviceBusMessageContext.getMessage()); }); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. */ Flux<ServiceBusMessageContext> receiveMessagesWithContext() { return receiveMessagesWithContext(1); } Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) { final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null ? sessionManager.receive() : getOrCreateConsumer().receive().map(ServiceBusMessageContext::new); final Flux<ServiceBusMessageContext> messageFluxWithTracing = new FluxTrace(messageFlux, instrumentation); final Flux<ServiceBusMessageContext> withAutoLockRenewal; if (!receiverOptions.isSessionReceiver() && receiverOptions.isAutoLockRenewEnabled()) { withAutoLockRenewal = new FluxAutoLockRenew(messageFluxWithTracing, receiverOptions, renewalContainer, this::renewMessageLock); } else { withAutoLockRenewal = messageFluxWithTracing; } Flux<ServiceBusMessageContext> result; if (receiverOptions.isEnableAutoComplete()) { result = new FluxAutoComplete(withAutoLockRenewal, completionLock, context -> context.getMessage() != null ? complete(context.getMessage()) : Mono.empty(), context -> context.getMessage() != null ? abandon(context.getMessage()) : Mono.empty()); } else { result = withAutoLockRenewal; } if (highTide > 0) { result = result.limitRate(highTide, 0); } return result .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. {@code null} if there is no session. * * @return A deferred message with the matching {@code sequenceNumber}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessage"))); } return tracer.traceManagementReceive("ServiceBus.receiveDeferredMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last()) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)), ServiceBusReceivedMessage::getContext); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) { return tracer.traceSyncReceive("ServiceBus.receiveDeferredMessages", receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId())); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch"))); } if (sequenceNumbers == null) { return fluxError(LOGGER, new NullPointerException("'sequenceNumbers' cannot be null")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), sequenceNumbers)) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Package-private method that releases a message. * * @param message Message to release. * @return Mono that completes when message is successfully released. */ Mono<Void> release(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.RELEASED, null, null, null, null); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the entity creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the * lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } return tracer.traceMonoWithLink("ServiceBus.renewMessageLock", renewMessageLock(message.getLockToken()), message, message.getContext()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. * * @param lockToken to be renewed. * * @return The new expiration time for the message. * @throws IllegalStateException if receiver is already disposed. */ Mono<OffsetDateTime> renewMessageLock(String lockToken) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null))) .map(offsetDateTime -> managementNodeLocks.addOrUpdate(lockToken, offsetDateTime, offsetDateTime)); } /** * Starts the auto lock renewal for a {@link ServiceBusReceivedMessage message}. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * * @return A Mono that completes when the message renewal operation has completed up until * {@code maxLockRenewalDuration}. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message lock cannot be renewed. */ public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException( String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken()))); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return tracer.traceMonoWithLink("ServiceBus.renewMessageLock", operation.getCompletionOperation(), message, message.getContext()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Renews the session lock if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or if receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ public Mono<OffsetDateTime> renewSessionLock() { return renewSessionLock(receiverOptions.getSessionId()); } /** * Starts the auto lock renewal for the session this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session lock. * * @return A lock renewal operation for the message. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. */ public Mono<Void> renewSessionLock(Duration maxLockRenewalDuration) { return this.renewSessionLock(receiverOptions.getSessionId(), maxLockRenewalDuration); } /** * Sets the state of the session this receiver works for. * * @param sessionState State to set on the session. * * @return A Mono that completes when the session is set * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public Mono<Void> setSessionState(byte[] sessionState) { return this.setSessionState(receiverOptions.getSessionId(), sessionState); } /** * Starts a new service side transaction. The {@link ServiceBusTransactionContext transaction context} should be * passed to all operations that needs to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.createTransaction()) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to be commit. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be committed. */ public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to rollback. * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be rolled back. */ public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.rollbackTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override /** * @return receiver options set by user; */ ReceiverOptions getReceiverOptions() { return receiverOptions; } /** * Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are * held by the management node when they are received from the management node or management operations are * performed using that {@code lockToken}. * * @param lockToken Lock token to check for. * * @return {@code true} if the management node contains the lock token and false otherwise. */ private boolean isManagementToken(String lockToken) { return managementNodeLocks.containsUnexpired(lockToken); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue()))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); if (receiverOptions.getReceiveMode() != ServiceBusReceiveMode.PEEK_LOCK) { return Mono.error(LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.isSettled()) { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The message has either been deleted or already settled."))); } else if (message.getLockToken() == null) { final String errorMessage = "This operation is not supported for peeked messages. " + "Only messages received using receiveMessages() in PEEK_LOCK mode can be settled."; return Mono.error( LOGGER.logExceptionAsError(new UnsupportedOperationException(errorMessage)) ); } final String sessionIdToUse; if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) { sessionIdToUse = receiverOptions.getSessionId(); } else { sessionIdToUse = sessionId; } LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(SESSION_ID_KEY, sessionIdToUse) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update started."); final Mono<Void> performOnManagement = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext)) .then(Mono.fromRunnable(() -> { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Management node Update completed."); message.setIsSettled(); managementNodeLocks.remove(lockToken); renewalContainer.remove(lockToken); })); Mono<Void> updateDispositionOperation; if (sessionManager != null) { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .flatMap(isSuccess -> { if (isSuccess) { message.setIsSettled(); renewalContainer.remove(lockToken); return Mono.empty(); } LOGGER.info("Could not perform on session manger. Performing on management node."); return performOnManagement; }); } else { final ServiceBusAsyncConsumer existingConsumer = consumer.get(); if (isManagementToken(lockToken) || existingConsumer == null) { updateDispositionOperation = performOnManagement; } else { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })); } } return instrumentation.instrumentSettlement(updateDispositionOperation, message, message.getContext(), dispositionStatus) .onErrorMap(throwable -> { if (throwable instanceof ServiceBusException) { return throwable; } switch (dispositionStatus) { case COMPLETED: return new ServiceBusException(throwable, ServiceBusErrorSource.COMPLETE); case ABANDONED: return new ServiceBusException(throwable, ServiceBusErrorSource.ABANDON); default: return new ServiceBusException(throwable, ServiceBusErrorSource.UNKNOWN); } }); } private ServiceBusAsyncConsumer getOrCreateConsumer() { final ServiceBusAsyncConsumer existing = consumer.get(); if (existing != null) { return existing; } final String linkName = StringUtil.getRandomString(entityPath); LOGGER.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log("Creating consumer."); final Mono<ServiceBusReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> { if (receiverOptions.isSessionReceiver()) { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier, receiverOptions.getSessionId()); } else { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier); } }).doOnNext(next -> { LOGGER.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .addKeyValue("mode", receiverOptions.getReceiveMode()) .addKeyValue("isSessionEnabled", CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) .addKeyValue(ENTITY_TYPE_KEY, entityType) .log("Created consumer for Service Bus resource."); }); final Mono<ServiceBusReceiveLink> retryableReceiveLinkMono = RetryUtil.withRetry(receiveLinkMono.onErrorMap( RequestResponseChannelClosedException.class, e -> { return new AmqpException(true, e.getMessage(), e, null); }), connectionProcessor.getRetryOptions(), "Failed to create receive link " + linkName, true); final Flux<ServiceBusReceiveLink> receiveLinkFlux = retryableReceiveLinkMono.repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkFlux.subscribeWith( new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy)); final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor, messageSerializer, receiverOptions); if (consumer.compareAndSet(null, newConsumer)) { return newConsumer; } else { newConsumer.close(); return consumer.get(); } } /** * If the receiver has not connected via {@link * through the management node. * * @return The name of the receive link, or null of it has not connected via a receive link. */ private String getLinkName(String sessionId) { if (sessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) { return sessionManager.getLinkName(sessionId); } else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) { return null; } else { final ServiceBusAsyncConsumer existing = consumer.get(); return existing != null ? existing.getLinkName() : null; } } Mono<OffsetDateTime> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } final String linkName = sessionManager != null ? sessionManager.getLinkName(sessionId) : null; return tracer.traceMono("ServiceBus.renewSessionLock", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.renewSessionLock(sessionId, linkName))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException( "Cannot renew session lock on a non-session receiver.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } else if (Objects.isNull(sessionId)) { return monoError(LOGGER, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'sessionId' cannot be empty.")); } final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock); renewalContainer.addOrUpdate(sessionId, OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return tracer.traceMono("ServiceBus.renewSessionLock", operation.getCompletionOperation()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } Mono<Void> setSessionState(String sessionId, byte[] sessionState) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot set session state on a non-session receiver.")); } final String linkName = sessionManager != null ? sessionManager.getLinkName(sessionId) : null; return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot get session state on a non-session receiver.")); } Mono<byte[]> result; if (sessionManager != null) { result = sessionManager.getSessionState(sessionId); } else { result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId))); } return tracer.traceMono("ServiceBus.setSessionState", result) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } ServiceBusReceiverInstrumentation getInstrumentation() { return instrumentation; } /** * Map the error to {@link ServiceBusException} */ private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (!(throwable instanceof ServiceBusException)) { return new ServiceBusException(throwable, errorSource); } return throwable; } boolean isConnectionClosed() { return this.connectionProcessor.isChannelClosed(); } boolean isManagementNodeLocksClosed() { return this.managementNodeLocks.isClosed(); } boolean isRenewalContainerClosed() { return this.renewalContainer.isClosed(); } }
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private static final String TRANSACTION_LINK_NAME = "coordinator"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final LockContainer<LockRenewalOperation> renewalContainer; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final LockContainer<OffsetDateTime> managementNodeLocks; private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager sessionManager; private final Semaphore completionLock = new Semaphore(1); private final String identifier; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1); private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>(); private final AutoCloseable trackSettlementSequenceNumber; /** * Creates a receiver that listens to a Service Bus resource. * * @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource. * @param entityPath The name of the topic or queue. * @param entityType The type of the Service Bus resource. * @param receiverOptions Options when receiving messages. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param instrumentation ServiceBus tracing and metrics helper * @param messageSerializer Serializes and deserializes Service Bus messages. * @param onClientClose Operation to run when the client completes. */ ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.sessionManager = null; this.identifier = identifier; this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, ServiceBusSessionManager sessionManager) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null."); this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atInfo() .addKeyValue(SESSION_ID_KEY, renewal.getSessionId()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.identifier = sessionManager.getIdentifier(); this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return entityPath; } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return receiverOptions.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}. */ public String getIdentifier() { return identifier; } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus abandon operation completes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, null, null); } /** * Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @return A {@link Mono} that completes when the Service Bus operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.ABANDONED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, null); } /** * Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from * the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, options.getTransactionContext()); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus defer operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, null, null); } /** * Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into * the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @return A {@link Mono} that completes when the defer operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.DEFERRED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(), options.getDeadLetterErrorDescription(), options.getPropertiesToModify(), options.getTransactionContext()); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or an empty Mono if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed. * @throws ServiceBusException if the session state could not be acquired. */ public Mono<byte[]> getSessionState() { return getSessionState(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage() { return peekMessage(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if the receiver is disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek"))); } Mono<ServiceBusReceivedMessage> result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> { final long sequence = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequence) .log("Peek message."); return channel.peek(sequence, sessionId, getLinkName(sessionId)); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)) .handle((message, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, message.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Updating last peeked sequence number."); sink.next(message); }); return tracer.traceManagementReceive("ServiceBus.peekMessage", result, ServiceBusReceivedMessage::getContext); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) { return peekMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt"))); } return tracer.traceManagementReceive("ServiceBus.peekMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)), ServiceBusReceivedMessage::getContext); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return tracer.traceSyncReceive("ServiceBus.peekMessages", peekMessages(maxMessages, receiverOptions.getSessionId())); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> { final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch."); final Flux<ServiceBusReceivedMessage> messages = node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages); final Mono<ServiceBusReceivedMessage> handle = messages .switchIfEmpty(Mono.fromCallable(() -> { ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(BinaryData .fromBytes(new byte[0])); emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get()); return emptyMessage; })) .last() .handle((last, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, last.getSequenceNumber())); LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, current).log("Last peeked sequence number in batch."); sink.complete(); }); return Flux.merge(messages, handle); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return tracer.traceSyncReceive("ServiceBus.peekMessages", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages)) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. */ public Flux<ServiceBusReceivedMessage> receiveMessages() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages"))); } return receiveMessagesNoBackPressure().limitRate(1, 0); } Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() { return receiveMessagesWithContext(0) .handle((serviceBusMessageContext, sink) -> { if (serviceBusMessageContext.hasError()) { sink.error(serviceBusMessageContext.getThrowable()); return; } sink.next(serviceBusMessageContext.getMessage()); }); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. */ Flux<ServiceBusMessageContext> receiveMessagesWithContext() { return receiveMessagesWithContext(1); } Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) { final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null ? sessionManager.receive() : getOrCreateConsumer().receive().map(ServiceBusMessageContext::new); final Flux<ServiceBusMessageContext> messageFluxWithTracing = new FluxTrace(messageFlux, instrumentation); final Flux<ServiceBusMessageContext> withAutoLockRenewal; if (!receiverOptions.isSessionReceiver() && receiverOptions.isAutoLockRenewEnabled()) { withAutoLockRenewal = new FluxAutoLockRenew(messageFluxWithTracing, receiverOptions, renewalContainer, this::renewMessageLock); } else { withAutoLockRenewal = messageFluxWithTracing; } Flux<ServiceBusMessageContext> result; if (receiverOptions.isEnableAutoComplete()) { result = new FluxAutoComplete(withAutoLockRenewal, completionLock, context -> context.getMessage() != null ? complete(context.getMessage()) : Mono.empty(), context -> context.getMessage() != null ? abandon(context.getMessage()) : Mono.empty()); } else { result = withAutoLockRenewal; } if (highTide > 0) { result = result.limitRate(highTide, 0); } return result .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. {@code null} if there is no session. * * @return A deferred message with the matching {@code sequenceNumber}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessage"))); } return tracer.traceManagementReceive("ServiceBus.receiveDeferredMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last()) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)), ServiceBusReceivedMessage::getContext); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) { return tracer.traceSyncReceive("ServiceBus.receiveDeferredMessages", receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId())); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch"))); } if (sequenceNumbers == null) { return fluxError(LOGGER, new NullPointerException("'sequenceNumbers' cannot be null")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), sequenceNumbers)) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Package-private method that releases a message. * * @param message Message to release. * @return Mono that completes when message is successfully released. */ Mono<Void> release(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.RELEASED, null, null, null, null); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the entity creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the * lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } return tracer.traceMonoWithLink("ServiceBus.renewMessageLock", renewMessageLock(message.getLockToken()), message, message.getContext()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. * * @param lockToken to be renewed. * * @return The new expiration time for the message. * @throws IllegalStateException if receiver is already disposed. */ Mono<OffsetDateTime> renewMessageLock(String lockToken) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null))) .map(offsetDateTime -> managementNodeLocks.addOrUpdate(lockToken, offsetDateTime, offsetDateTime)); } /** * Starts the auto lock renewal for a {@link ServiceBusReceivedMessage message}. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * * @return A Mono that completes when the message renewal operation has completed up until * {@code maxLockRenewalDuration}. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message lock cannot be renewed. */ public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException( String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken()))); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return tracer.traceMonoWithLink("ServiceBus.renewMessageLock", operation.getCompletionOperation(), message, message.getContext()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Renews the session lock if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or if receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ public Mono<OffsetDateTime> renewSessionLock() { return renewSessionLock(receiverOptions.getSessionId()); } /** * Starts the auto lock renewal for the session this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session lock. * * @return A lock renewal operation for the message. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. */ public Mono<Void> renewSessionLock(Duration maxLockRenewalDuration) { return this.renewSessionLock(receiverOptions.getSessionId(), maxLockRenewalDuration); } /** * Sets the state of the session this receiver works for. * * @param sessionState State to set on the session. * * @return A Mono that completes when the session is set * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public Mono<Void> setSessionState(byte[] sessionState) { return this.setSessionState(receiverOptions.getSessionId(), sessionState); } /** * Starts a new service side transaction. The {@link ServiceBusTransactionContext transaction context} should be * passed to all operations that needs to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.createTransaction()) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to be commit. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be committed. */ public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to rollback. * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be rolled back. */ public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.rollbackTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override /** * @return receiver options set by user; */ ReceiverOptions getReceiverOptions() { return receiverOptions; } /** * Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are * held by the management node when they are received from the management node or management operations are * performed using that {@code lockToken}. * * @param lockToken Lock token to check for. * * @return {@code true} if the management node contains the lock token and false otherwise. */ private boolean isManagementToken(String lockToken) { return managementNodeLocks.containsUnexpired(lockToken); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue()))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); if (receiverOptions.getReceiveMode() != ServiceBusReceiveMode.PEEK_LOCK) { return Mono.error(LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.isSettled()) { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The message has either been deleted or already settled."))); } else if (message.getLockToken() == null) { final String errorMessage = "This operation is not supported for peeked messages. " + "Only messages received using receiveMessages() in PEEK_LOCK mode can be settled."; return Mono.error( LOGGER.logExceptionAsError(new UnsupportedOperationException(errorMessage)) ); } final String sessionIdToUse; if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) { sessionIdToUse = receiverOptions.getSessionId(); } else { sessionIdToUse = sessionId; } LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(SESSION_ID_KEY, sessionIdToUse) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update started."); final Mono<Void> performOnManagement = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext)) .then(Mono.fromRunnable(() -> { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Management node Update completed."); message.setIsSettled(); managementNodeLocks.remove(lockToken); renewalContainer.remove(lockToken); })); Mono<Void> updateDispositionOperation; if (sessionManager != null) { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .flatMap(isSuccess -> { if (isSuccess) { message.setIsSettled(); renewalContainer.remove(lockToken); return Mono.empty(); } LOGGER.info("Could not perform on session manger. Performing on management node."); return performOnManagement; }); } else { final ServiceBusAsyncConsumer existingConsumer = consumer.get(); if (isManagementToken(lockToken) || existingConsumer == null) { updateDispositionOperation = performOnManagement; } else { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })); } } return instrumentation.instrumentSettlement(updateDispositionOperation, message, message.getContext(), dispositionStatus) .onErrorMap(throwable -> { if (throwable instanceof ServiceBusException) { return throwable; } switch (dispositionStatus) { case COMPLETED: return new ServiceBusException(throwable, ServiceBusErrorSource.COMPLETE); case ABANDONED: return new ServiceBusException(throwable, ServiceBusErrorSource.ABANDON); default: return new ServiceBusException(throwable, ServiceBusErrorSource.UNKNOWN); } }); } private ServiceBusAsyncConsumer getOrCreateConsumer() { final ServiceBusAsyncConsumer existing = consumer.get(); if (existing != null) { return existing; } final String linkName = StringUtil.getRandomString(entityPath); LOGGER.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log("Creating consumer."); final Mono<ServiceBusReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> { if (receiverOptions.isSessionReceiver()) { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier, receiverOptions.getSessionId()); } else { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier); } }).doOnNext(next -> { LOGGER.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .addKeyValue("mode", receiverOptions.getReceiveMode()) .addKeyValue("isSessionEnabled", CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) .addKeyValue(ENTITY_TYPE_KEY, entityType) .log("Created consumer for Service Bus resource."); }); final Mono<ServiceBusReceiveLink> retryableReceiveLinkMono = RetryUtil.withRetry(receiveLinkMono.onErrorMap( RequestResponseChannelClosedException.class, e -> { return new AmqpException(true, e.getMessage(), e, null); }), connectionProcessor.getRetryOptions(), "Failed to create receive link " + linkName, true); final Flux<ServiceBusReceiveLink> receiveLinkFlux = retryableReceiveLinkMono.repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkFlux.subscribeWith( new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy)); final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor, messageSerializer, receiverOptions); if (consumer.compareAndSet(null, newConsumer)) { return newConsumer; } else { newConsumer.close(); return consumer.get(); } } /** * If the receiver has not connected via {@link * through the management node. * * @return The name of the receive link, or null of it has not connected via a receive link. */ private String getLinkName(String sessionId) { if (sessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) { return sessionManager.getLinkName(sessionId); } else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) { return null; } else { final ServiceBusAsyncConsumer existing = consumer.get(); return existing != null ? existing.getLinkName() : null; } } Mono<OffsetDateTime> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } final String linkName = sessionManager != null ? sessionManager.getLinkName(sessionId) : null; return tracer.traceMono("ServiceBus.renewSessionLock", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.renewSessionLock(sessionId, linkName))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException( "Cannot renew session lock on a non-session receiver.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } else if (Objects.isNull(sessionId)) { return monoError(LOGGER, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'sessionId' cannot be empty.")); } final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock); renewalContainer.addOrUpdate(sessionId, OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return tracer.traceMono("ServiceBus.renewSessionLock", operation.getCompletionOperation()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } Mono<Void> setSessionState(String sessionId, byte[] sessionState) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot set session state on a non-session receiver.")); } final String linkName = sessionManager != null ? sessionManager.getLinkName(sessionId) : null; return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot get session state on a non-session receiver.")); } Mono<byte[]> result; if (sessionManager != null) { result = sessionManager.getSessionState(sessionId); } else { result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId))); } return tracer.traceMono("ServiceBus.setSessionState", result) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } ServiceBusReceiverInstrumentation getInstrumentation() { return instrumentation; } /** * Map the error to {@link ServiceBusException} */ private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (!(throwable instanceof ServiceBusException)) { return new ServiceBusException(throwable, errorSource); } return throwable; } boolean isConnectionClosed() { return this.connectionProcessor.isChannelClosed(); } boolean isManagementNodeLocksClosed() { return this.managementNodeLocks.isClosed(); } boolean isRenewalContainerClosed() { return this.renewalContainer.isClosed(); } }
```suggestion // The cause is completionLock's acquire method is stuck. So we have added a timeout for acquiring the lock, to work around the issue. ```
public void close() { if (isDisposed.get()) { return; } try { boolean acquired = completionLock.tryAcquire(5, TimeUnit.SECONDS); if (!acquired) { LOGGER.info("Unable to obtain completion lock."); } } catch (InterruptedException e) { LOGGER.info("Unable to obtain completion lock.", e); } if (isDisposed.getAndSet(true)) { return; } LOGGER.info("Removing receiver links."); final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null); if (disposed != null) { disposed.close(); } if (sessionManager != null) { sessionManager.close(); } managementNodeLocks.close(); renewalContainer.close(); if (trackSettlementSequenceNumber != null) { try { trackSettlementSequenceNumber.close(); } catch (Exception e) { LOGGER.info("Unable to close settlement sequence number subscription.", e); } } onClientClose.run(); }
public void close() { if (isDisposed.get()) { return; } try { boolean acquired = completionLock.tryAcquire(5, TimeUnit.SECONDS); if (!acquired) { LOGGER.info("Unable to obtain completion lock."); } } catch (InterruptedException e) { LOGGER.info("Unable to obtain completion lock.", e); } if (isDisposed.getAndSet(true)) { return; } LOGGER.info("Removing receiver links."); final ServiceBusAsyncConsumer disposed = consumer.getAndSet(null); if (disposed != null) { disposed.close(); } if (sessionManager != null) { sessionManager.close(); } managementNodeLocks.close(); renewalContainer.close(); if (trackSettlementSequenceNumber != null) { try { trackSettlementSequenceNumber.close(); } catch (Exception e) { LOGGER.info("Unable to close settlement sequence number subscription.", e); } } onClientClose.run(); }
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private static final String TRANSACTION_LINK_NAME = "coordinator"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final LockContainer<LockRenewalOperation> renewalContainer; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final LockContainer<OffsetDateTime> managementNodeLocks; private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager sessionManager; private final Semaphore completionLock = new Semaphore(1); private final String identifier; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1); private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>(); private final AutoCloseable trackSettlementSequenceNumber; /** * Creates a receiver that listens to a Service Bus resource. * * @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource. * @param entityPath The name of the topic or queue. * @param entityType The type of the Service Bus resource. * @param receiverOptions Options when receiving messages. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param instrumentation ServiceBus tracing and metrics helper * @param messageSerializer Serializes and deserializes Service Bus messages. * @param onClientClose Operation to run when the client completes. */ ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.sessionManager = null; this.identifier = identifier; this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, ServiceBusSessionManager sessionManager) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null."); this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atInfo() .addKeyValue(SESSION_ID_KEY, renewal.getSessionId()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.identifier = sessionManager.getIdentifier(); this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return entityPath; } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return receiverOptions.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}. */ public String getIdentifier() { return identifier; } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus abandon operation completes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, null, null); } /** * Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @return A {@link Mono} that completes when the Service Bus operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.ABANDONED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, null); } /** * Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from * the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, options.getTransactionContext()); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus defer operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, null, null); } /** * Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into * the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @return A {@link Mono} that completes when the defer operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.DEFERRED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(), options.getDeadLetterErrorDescription(), options.getPropertiesToModify(), options.getTransactionContext()); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or an empty Mono if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed. * @throws ServiceBusException if the session state could not be acquired. */ public Mono<byte[]> getSessionState() { return getSessionState(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage() { return peekMessage(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if the receiver is disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek"))); } Mono<ServiceBusReceivedMessage> result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> { final long sequence = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequence) .log("Peek message."); return channel.peek(sequence, sessionId, getLinkName(sessionId)); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)) .handle((message, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, message.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Updating last peeked sequence number."); sink.next(message); }); return tracer.traceManagementReceive("ServiceBus.peekMessage", result, ServiceBusReceivedMessage::getContext); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) { return peekMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt"))); } return tracer.traceManagementReceive("ServiceBus.peekMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)), ServiceBusReceivedMessage::getContext); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return tracer.traceSyncReceive("ServiceBus.peekMessages", peekMessages(maxMessages, receiverOptions.getSessionId())); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> { final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch."); final Flux<ServiceBusReceivedMessage> messages = node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages); final Mono<ServiceBusReceivedMessage> handle = messages .switchIfEmpty(Mono.fromCallable(() -> { ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(BinaryData .fromBytes(new byte[0])); emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get()); return emptyMessage; })) .last() .handle((last, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, last.getSequenceNumber())); LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, current).log("Last peeked sequence number in batch."); sink.complete(); }); return Flux.merge(messages, handle); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return tracer.traceSyncReceive("ServiceBus.peekMessages", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages)) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. */ public Flux<ServiceBusReceivedMessage> receiveMessages() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages"))); } return receiveMessagesNoBackPressure().limitRate(1, 0); } Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() { return receiveMessagesWithContext(0) .handle((serviceBusMessageContext, sink) -> { if (serviceBusMessageContext.hasError()) { sink.error(serviceBusMessageContext.getThrowable()); return; } sink.next(serviceBusMessageContext.getMessage()); }); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. */ Flux<ServiceBusMessageContext> receiveMessagesWithContext() { return receiveMessagesWithContext(1); } Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) { final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null ? sessionManager.receive() : getOrCreateConsumer().receive().map(ServiceBusMessageContext::new); final Flux<ServiceBusMessageContext> messageFluxWithTracing = new FluxTrace(messageFlux, instrumentation); final Flux<ServiceBusMessageContext> withAutoLockRenewal; if (!receiverOptions.isSessionReceiver() && receiverOptions.isAutoLockRenewEnabled()) { withAutoLockRenewal = new FluxAutoLockRenew(messageFluxWithTracing, receiverOptions, renewalContainer, this::renewMessageLock); } else { withAutoLockRenewal = messageFluxWithTracing; } Flux<ServiceBusMessageContext> result; if (receiverOptions.isEnableAutoComplete()) { result = new FluxAutoComplete(withAutoLockRenewal, completionLock, context -> context.getMessage() != null ? complete(context.getMessage()) : Mono.empty(), context -> context.getMessage() != null ? abandon(context.getMessage()) : Mono.empty()); } else { result = withAutoLockRenewal; } if (highTide > 0) { result = result.limitRate(highTide, 0); } return result .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. {@code null} if there is no session. * * @return A deferred message with the matching {@code sequenceNumber}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessage"))); } return tracer.traceManagementReceive("ServiceBus.receiveDeferredMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last()) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)), ServiceBusReceivedMessage::getContext); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) { return tracer.traceSyncReceive("ServiceBus.receiveDeferredMessages", receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId())); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch"))); } if (sequenceNumbers == null) { return fluxError(LOGGER, new NullPointerException("'sequenceNumbers' cannot be null")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), sequenceNumbers)) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Package-private method that releases a message. * * @param message Message to release. * @return Mono that completes when message is successfully released. */ Mono<Void> release(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.RELEASED, null, null, null, null); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the entity creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the * lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } return tracer.traceMonoWithLink("ServiceBus.renewMessageLock", renewMessageLock(message.getLockToken()), message, message.getContext()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. * * @param lockToken to be renewed. * * @return The new expiration time for the message. * @throws IllegalStateException if receiver is already disposed. */ Mono<OffsetDateTime> renewMessageLock(String lockToken) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null))) .map(offsetDateTime -> managementNodeLocks.addOrUpdate(lockToken, offsetDateTime, offsetDateTime)); } /** * Starts the auto lock renewal for a {@link ServiceBusReceivedMessage message}. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * * @return A Mono that completes when the message renewal operation has completed up until * {@code maxLockRenewalDuration}. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message lock cannot be renewed. */ public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException( String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken()))); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return tracer.traceMonoWithLink("ServiceBus.renewMessageLock", operation.getCompletionOperation(), message, message.getContext()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Renews the session lock if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or if receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ public Mono<OffsetDateTime> renewSessionLock() { return renewSessionLock(receiverOptions.getSessionId()); } /** * Starts the auto lock renewal for the session this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session lock. * * @return A lock renewal operation for the message. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. */ public Mono<Void> renewSessionLock(Duration maxLockRenewalDuration) { return this.renewSessionLock(receiverOptions.getSessionId(), maxLockRenewalDuration); } /** * Sets the state of the session this receiver works for. * * @param sessionState State to set on the session. * * @return A Mono that completes when the session is set * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public Mono<Void> setSessionState(byte[] sessionState) { return this.setSessionState(receiverOptions.getSessionId(), sessionState); } /** * Starts a new service side transaction. The {@link ServiceBusTransactionContext transaction context} should be * passed to all operations that needs to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.createTransaction()) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to be commit. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be committed. */ public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to rollback. * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be rolled back. */ public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.rollbackTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override /** * @return receiver options set by user; */ ReceiverOptions getReceiverOptions() { return receiverOptions; } /** * Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are * held by the management node when they are received from the management node or management operations are * performed using that {@code lockToken}. * * @param lockToken Lock token to check for. * * @return {@code true} if the management node contains the lock token and false otherwise. */ private boolean isManagementToken(String lockToken) { return managementNodeLocks.containsUnexpired(lockToken); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue()))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); if (receiverOptions.getReceiveMode() != ServiceBusReceiveMode.PEEK_LOCK) { return Mono.error(LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.isSettled()) { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The message has either been deleted or already settled."))); } else if (message.getLockToken() == null) { final String errorMessage = "This operation is not supported for peeked messages. " + "Only messages received using receiveMessages() in PEEK_LOCK mode can be settled."; return Mono.error( LOGGER.logExceptionAsError(new UnsupportedOperationException(errorMessage)) ); } final String sessionIdToUse; if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) { sessionIdToUse = receiverOptions.getSessionId(); } else { sessionIdToUse = sessionId; } LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(SESSION_ID_KEY, sessionIdToUse) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update started."); final Mono<Void> performOnManagement = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext)) .then(Mono.fromRunnable(() -> { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Management node Update completed."); message.setIsSettled(); managementNodeLocks.remove(lockToken); renewalContainer.remove(lockToken); })); Mono<Void> updateDispositionOperation; if (sessionManager != null) { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .flatMap(isSuccess -> { if (isSuccess) { message.setIsSettled(); renewalContainer.remove(lockToken); return Mono.empty(); } LOGGER.info("Could not perform on session manger. Performing on management node."); return performOnManagement; }); } else { final ServiceBusAsyncConsumer existingConsumer = consumer.get(); if (isManagementToken(lockToken) || existingConsumer == null) { updateDispositionOperation = performOnManagement; } else { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })); } } return instrumentation.instrumentSettlement(updateDispositionOperation, message, message.getContext(), dispositionStatus) .onErrorMap(throwable -> { if (throwable instanceof ServiceBusException) { return throwable; } switch (dispositionStatus) { case COMPLETED: return new ServiceBusException(throwable, ServiceBusErrorSource.COMPLETE); case ABANDONED: return new ServiceBusException(throwable, ServiceBusErrorSource.ABANDON); default: return new ServiceBusException(throwable, ServiceBusErrorSource.UNKNOWN); } }); } private ServiceBusAsyncConsumer getOrCreateConsumer() { final ServiceBusAsyncConsumer existing = consumer.get(); if (existing != null) { return existing; } final String linkName = StringUtil.getRandomString(entityPath); LOGGER.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log("Creating consumer."); final Mono<ServiceBusReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> { if (receiverOptions.isSessionReceiver()) { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier, receiverOptions.getSessionId()); } else { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier); } }).doOnNext(next -> { LOGGER.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .addKeyValue("mode", receiverOptions.getReceiveMode()) .addKeyValue("isSessionEnabled", CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) .addKeyValue(ENTITY_TYPE_KEY, entityType) .log("Created consumer for Service Bus resource."); }); final Mono<ServiceBusReceiveLink> retryableReceiveLinkMono = RetryUtil.withRetry(receiveLinkMono.onErrorMap( RequestResponseChannelClosedException.class, e -> { return new AmqpException(true, e.getMessage(), e, null); }), connectionProcessor.getRetryOptions(), "Failed to create receive link " + linkName, true); final Flux<ServiceBusReceiveLink> receiveLinkFlux = retryableReceiveLinkMono.repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkFlux.subscribeWith( new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy)); final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor, messageSerializer, receiverOptions); if (consumer.compareAndSet(null, newConsumer)) { return newConsumer; } else { newConsumer.close(); return consumer.get(); } } /** * If the receiver has not connected via {@link * through the management node. * * @return The name of the receive link, or null of it has not connected via a receive link. */ private String getLinkName(String sessionId) { if (sessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) { return sessionManager.getLinkName(sessionId); } else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) { return null; } else { final ServiceBusAsyncConsumer existing = consumer.get(); return existing != null ? existing.getLinkName() : null; } } Mono<OffsetDateTime> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } final String linkName = sessionManager != null ? sessionManager.getLinkName(sessionId) : null; return tracer.traceMono("ServiceBus.renewSessionLock", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.renewSessionLock(sessionId, linkName))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException( "Cannot renew session lock on a non-session receiver.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } else if (Objects.isNull(sessionId)) { return monoError(LOGGER, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'sessionId' cannot be empty.")); } final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock); renewalContainer.addOrUpdate(sessionId, OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return tracer.traceMono("ServiceBus.renewSessionLock", operation.getCompletionOperation()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } Mono<Void> setSessionState(String sessionId, byte[] sessionState) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot set session state on a non-session receiver.")); } final String linkName = sessionManager != null ? sessionManager.getLinkName(sessionId) : null; return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot get session state on a non-session receiver.")); } Mono<byte[]> result; if (sessionManager != null) { result = sessionManager.getSessionState(sessionId); } else { result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId))); } return tracer.traceMono("ServiceBus.setSessionState", result) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } ServiceBusReceiverInstrumentation getInstrumentation() { return instrumentation; } /** * Map the error to {@link ServiceBusException} */ private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (!(throwable instanceof ServiceBusException)) { return new ServiceBusException(throwable, errorSource); } return throwable; } boolean isConnectionClosed() { return this.connectionProcessor.isChannelClosed(); } boolean isManagementNodeLocksClosed() { return this.managementNodeLocks.isClosed(); } boolean isRenewalContainerClosed() { return this.renewalContainer.isClosed(); } }
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private static final String TRANSACTION_LINK_NAME = "coordinator"; private static final ClientLogger LOGGER = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final LockContainer<LockRenewalOperation> renewalContainer; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final LockContainer<OffsetDateTime> managementNodeLocks; private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final ReceiverOptions receiverOptions; private final ServiceBusConnectionProcessor connectionProcessor; private final ServiceBusReceiverInstrumentation instrumentation; private final ServiceBusTracer tracer; private final MessageSerializer messageSerializer; private final Runnable onClientClose; private final ServiceBusSessionManager sessionManager; private final Semaphore completionLock = new Semaphore(1); private final String identifier; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(-1); private final AtomicReference<ServiceBusAsyncConsumer> consumer = new AtomicReference<>(); private final AutoCloseable trackSettlementSequenceNumber; /** * Creates a receiver that listens to a Service Bus resource. * * @param fullyQualifiedNamespace The fully qualified domain name for the Service Bus resource. * @param entityPath The name of the topic or queue. * @param entityType The type of the Service Bus resource. * @param receiverOptions Options when receiving messages. * @param connectionProcessor The AMQP connection to the Service Bus resource. * @param instrumentation ServiceBus tracing and metrics helper * @param messageSerializer Serializes and deserializes Service Bus messages. * @param onClientClose Operation to run when the client completes. */ ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, String identifier) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, renewal.getLockToken()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.sessionManager = null; this.identifier = identifier; this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, ReceiverOptions receiverOptions, ServiceBusConnectionProcessor connectionProcessor, Duration cleanupInterval, ServiceBusReceiverInstrumentation instrumentation, MessageSerializer messageSerializer, Runnable onClientClose, ServiceBusSessionManager sessionManager) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.entityType = Objects.requireNonNull(entityType, "'entityType' cannot be null."); this.receiverOptions = Objects.requireNonNull(receiverOptions, "'receiveOptions cannot be null.'"); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.instrumentation = Objects.requireNonNull(instrumentation, "'tracer' cannot be null"); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.onClientClose = Objects.requireNonNull(onClientClose, "'onClientClose' cannot be null."); this.sessionManager = Objects.requireNonNull(sessionManager, "'sessionManager' cannot be null."); this.managementNodeLocks = new LockContainer<>(cleanupInterval); this.renewalContainer = new LockContainer<>(Duration.ofMinutes(2), renewal -> { LOGGER.atInfo() .addKeyValue(SESSION_ID_KEY, renewal.getSessionId()) .addKeyValue("status", renewal.getStatus()) .log("Closing expired renewal operation.", renewal.getThrowable()); renewal.close(); }); this.identifier = sessionManager.getIdentifier(); this.tracer = instrumentation.getTracer(); this.trackSettlementSequenceNumber = instrumentation.startTrackingSettlementSequenceNumber(); } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getEntityPath() { return entityPath; } /** * Gets the SessionId of the session if this receiver is a session receiver. * * @return The SessionId or null if this is not a session receiver. */ public String getSessionId() { return receiverOptions.getSessionId(); } /** * Gets the identifier of the instance of {@link ServiceBusReceiverAsyncClient}. * * @return The identifier that can identify the instance of {@link ServiceBusReceiverAsyncClient}. */ public String getIdentifier() { return identifier; } /** * Abandons a {@link ServiceBusReceivedMessage message}. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus abandon operation completes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, null, null); } /** * Abandons a {@link ServiceBusReceivedMessage message} updates the message's properties. This will make the * message available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options The options to set while abandoning the message. * * @return A {@link Mono} that completes when the Service Bus operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be abandoned. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, AbandonOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'settlementOptions' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.ABANDONED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Completes a {@link ServiceBusReceivedMessage message}. This will delete the message from the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, null); } /** * Completes a {@link ServiceBusReceivedMessage message} with the given options. This will delete the message from * the service. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to complete the message. * * @return A {@link Mono} that finishes when the message is completed on Service Bus. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be completed. * @throws IllegalArgumentException if the message has either been deleted or already settled. */ public Mono<Void> complete(ServiceBusReceivedMessage message, CompleteOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null, options.getTransactionContext()); } /** * Defers a {@link ServiceBusReceivedMessage message}. This will move message into the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the Service Bus defer operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, null, null); } /** * Defers a {@link ServiceBusReceivedMessage message} with the options set. This will move message into * the deferred sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to defer the message. * * @return A {@link Mono} that completes when the defer operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be deferred. * @throws IllegalArgumentException if the message has either been deleted or already settled. * @see <a href="https: */ public Mono<Void> defer(ServiceBusReceivedMessage message, DeferOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.DEFERRED, null, null, options.getPropertiesToModify(), options.getTransactionContext()); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, DEFAULT_DEAD_LETTER_OPTIONS); } /** * Moves a {@link ServiceBusReceivedMessage message} to the dead-letter sub-queue with the given options. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param options Options used to dead-letter the message. * * @return A {@link Mono} that completes when the dead letter operation finishes. * * @throws NullPointerException if {@code message} or {@code options} is null. Also if * {@code transactionContext.transactionId} is null when {@code options.transactionContext} is specified. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * {@link ServiceBusReceiverAsyncClient * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the message could not be dead-lettered. * @throws IllegalArgumentException if the message has either been deleted or already settled. * * @see <a href="https: * queues</a> */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions options) { if (Objects.isNull(options)) { return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); } else if (!Objects.isNull(options.getTransactionContext()) && Objects.isNull(options.getTransactionContext().getTransactionId())) { return monoError(LOGGER, new NullPointerException( "'options.transactionContext.transactionId' cannot be null.")); } return updateDisposition(message, DispositionStatus.SUSPENDED, options.getDeadLetterReason(), options.getDeadLetterErrorDescription(), options.getPropertiesToModify(), options.getTransactionContext()); } /** * Gets the state of the session if this receiver is a session receiver. * * @return The session state or an empty Mono if there is no state set for the session. * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already closed. * @throws ServiceBusException if the session state could not be acquired. */ public Mono<byte[]> getSessionState() { return getSessionState(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage() { return peekMessage(receiverOptions.getSessionId()); } /** * Reads the next active message without changing the state of the receiver or the message source. The first call to * {@code peek()} fetches the first active message for this receiver. Each subsequent call fetches the subsequent * message in the entity. * * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if the receiver is disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peek"))); } Mono<ServiceBusReceivedMessage> result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> { final long sequence = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, sequence) .log("Peek message."); return channel.peek(sequence, sessionId, getLinkName(sessionId)); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)) .handle((message, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, message.getSequenceNumber())); LOGGER.atVerbose() .addKeyValue(SEQUENCE_NUMBER_KEY, current) .log("Updating last peeked sequence number."); sink.next(message); }); return tracer.traceManagementReceive("ServiceBus.peekMessage", result, ServiceBusReceivedMessage::getContext); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * * @return A peeked {@link ServiceBusReceivedMessage}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ public Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber) { return peekMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads next the active message without changing the state of the receiver * or the message source. * * @param sequenceNumber The sequence number from where to read the message. * @param sessionId Session id of the message to peek from. {@code null} if there is no session. * * @return A peeked {@link ServiceBusReceivedMessage}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at the message. * @see <a href="https: */ Mono<ServiceBusReceivedMessage> peekMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekAt"))); } return tracer.traceManagementReceive("ServiceBus.peekMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)), ServiceBusReceivedMessage::getContext); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} that are peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages) { return tracer.traceSyncReceive("ServiceBus.peekMessages", peekMessages(maxMessages, receiverOptions.getSessionId())); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage messages} that are peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatch"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> { final long nextSequenceNumber = lastPeekedSequenceNumber.get() + 1; LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, nextSequenceNumber).log("Peek batch."); final Flux<ServiceBusReceivedMessage> messages = node.peek(nextSequenceNumber, sessionId, getLinkName(sessionId), maxMessages); final Mono<ServiceBusReceivedMessage> handle = messages .switchIfEmpty(Mono.fromCallable(() -> { ServiceBusReceivedMessage emptyMessage = new ServiceBusReceivedMessage(BinaryData .fromBytes(new byte[0])); emptyMessage.setSequenceNumber(lastPeekedSequenceNumber.get()); return emptyMessage; })) .last() .handle((last, sink) -> { final long current = lastPeekedSequenceNumber .updateAndGet(value -> Math.max(value, last.getSequenceNumber())); LOGGER.atVerbose().addKeyValue(SEQUENCE_NUMBER_KEY, current).log("Last peeked sequence number in batch."); sink.complete(); }); return Flux.merge(messages, handle); }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * * @return A {@link Flux} of {@link ServiceBusReceivedMessage messages} peeked. * * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ public Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber) { return peekMessages(maxMessages, sequenceNumber, receiverOptions.getSessionId()); } /** * Starting from the given sequence number, reads the next batch of active messages without changing the state of * the receiver or the message source. * * @param maxMessages The number of messages. * @param sequenceNumber The sequence number from where to start reading messages. * @param sessionId Session id of the messages to peek from. {@code null} if there is no session. * * @return An {@link IterableStream} of {@link ServiceBusReceivedMessage} peeked. * @throws IllegalArgumentException if {@code maxMessages} is not a positive integer. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while peeking at messages. * @see <a href="https: */ Flux<ServiceBusReceivedMessage> peekMessages(int maxMessages, long sequenceNumber, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "peekBatchAt"))); } if (maxMessages <= 0) { return fluxError(LOGGER, new IllegalArgumentException("'maxMessages' is not positive.")); } return tracer.traceSyncReceive("ServiceBus.peekMessages", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peek(sequenceNumber, sessionId, getLinkName(sessionId), maxMessages)) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE))); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if an error occurs while receiving messages. */ public Flux<ServiceBusReceivedMessage> receiveMessages() { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveMessages"))); } return receiveMessagesNoBackPressure().limitRate(1, 0); } Flux<ServiceBusReceivedMessage> receiveMessagesNoBackPressure() { return receiveMessagesWithContext(0) .handle((serviceBusMessageContext, sink) -> { if (serviceBusMessageContext.hasError()) { sink.error(serviceBusMessageContext.getThrowable()); return; } sink.next(serviceBusMessageContext.getMessage()); }); } /** * Receives an <b>infinite</b> stream of {@link ServiceBusReceivedMessage messages} from the Service Bus entity. * This Flux continuously receives messages from a Service Bus entity until either: * * <ul> * <li>The receiver is closed.</li> * <li>The subscription to the Flux is disposed.</li> * <li>A terminal signal from a downstream subscriber is propagated upstream (ie. {@link Flux * {@link Flux * <li>An {@link AmqpException} occurs that causes the receive link to stop.</li> * </ul> * * @return An <b>infinite</b> stream of messages from the Service Bus entity. */ Flux<ServiceBusMessageContext> receiveMessagesWithContext() { return receiveMessagesWithContext(1); } Flux<ServiceBusMessageContext> receiveMessagesWithContext(int highTide) { final Flux<ServiceBusMessageContext> messageFlux = sessionManager != null ? sessionManager.receive() : getOrCreateConsumer().receive().map(ServiceBusMessageContext::new); final Flux<ServiceBusMessageContext> messageFluxWithTracing = new FluxTrace(messageFlux, instrumentation); final Flux<ServiceBusMessageContext> withAutoLockRenewal; if (!receiverOptions.isSessionReceiver() && receiverOptions.isAutoLockRenewEnabled()) { withAutoLockRenewal = new FluxAutoLockRenew(messageFluxWithTracing, receiverOptions, renewalContainer, this::renewMessageLock); } else { withAutoLockRenewal = messageFluxWithTracing; } Flux<ServiceBusMessageContext> result; if (receiverOptions.isEnableAutoComplete()) { result = new FluxAutoComplete(withAutoLockRenewal, completionLock, context -> context.getMessage() != null ? complete(context.getMessage()) : Mono.empty(), context -> context.getMessage() != null ? abandon(context.getMessage()) : Mono.empty()); } else { result = withAutoLockRenewal; } if (highTide > 0) { result = result.limitRate(highTide, 0); } return result .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * * @return A deferred message with the matching {@code sequenceNumber}. * * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return receiveDeferredMessage(sequenceNumber, receiverOptions.getSessionId()); } /** * Receives a deferred {@link ServiceBusReceivedMessage message}. Deferred messages can only be received by using * sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * message. * @param sessionId Session id of the deferred message. {@code null} if there is no session. * * @return A deferred message with the matching {@code sequenceNumber}. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred message cannot be received. */ Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber, String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessage"))); } return tracer.traceManagementReceive("ServiceBus.receiveDeferredMessage", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), Collections.singleton(sequenceNumber)).last()) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)), ServiceBusReceivedMessage::getContext); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * * @return A {@link Flux} of deferred {@link ServiceBusReceivedMessage messages}. * * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if deferred messages cannot be received. */ public Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers) { return tracer.traceSyncReceive("ServiceBus.receiveDeferredMessages", receiveDeferredMessages(sequenceNumbers, receiverOptions.getSessionId())); } /** * Receives a batch of deferred {@link ServiceBusReceivedMessage messages}. Deferred messages can only be received * by using sequence number. * * @param sequenceNumbers The sequence numbers of the deferred messages. * @param sessionId Session id of the deferred messages. {@code null} if there is no session. * * @return An {@link IterableStream} of deferred {@link ServiceBusReceivedMessage messages}. * @throws IllegalStateException if receiver is already disposed. * @throws NullPointerException if {@code sequenceNumbers} is null. * @throws ServiceBusException if deferred message cannot be received. */ Flux<ServiceBusReceivedMessage> receiveDeferredMessages(Iterable<Long> sequenceNumbers, String sessionId) { if (isDisposed.get()) { return fluxError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "receiveDeferredMessageBatch"))); } if (sequenceNumbers == null) { return fluxError(LOGGER, new NullPointerException("'sequenceNumbers' cannot be null")); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.receiveDeferredMessages(receiverOptions.getReceiveMode(), sessionId, getLinkName(sessionId), sequenceNumbers)) .map(receivedMessage -> { if (CoreUtils.isNullOrEmpty(receivedMessage.getLockToken())) { return receivedMessage; } if (receiverOptions.getReceiveMode() == ServiceBusReceiveMode.PEEK_LOCK) { receivedMessage.setLockedUntil(managementNodeLocks.addOrUpdate(receivedMessage.getLockToken(), receivedMessage.getLockedUntil(), receivedMessage.getLockedUntil())); } return receivedMessage; }) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Package-private method that releases a message. * * @param message Message to release. * @return Mono that completes when message is successfully released. */ Mono<Void> release(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.RELEASED, null, null, null, null); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. When a message is received in {@link ServiceBusReceiveMode * server for this receiver instance for a duration as specified during the entity creation (LockDuration). If * processing of the message requires longer than this duration, the lock needs to be renewed. For each renewal, the * lock is reset to the entity's LockDuration value. * * @param message The {@link ServiceBusReceivedMessage} to perform auto-lock renewal. * * @return The new expiration time for the message. * * @throws NullPointerException if {@code message} or {@code message.getLockToken()} is null. * @throws UnsupportedOperationException if the receiver was opened in * {@link ServiceBusReceiveMode * @throws IllegalStateException if the receiver is a session receiver or receiver is already disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. */ public Mono<OffsetDateTime> renewMessageLock(ServiceBusReceivedMessage message) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { final String errorMessage = "Renewing message lock is an invalid operation when working with sessions."; return monoError(LOGGER, new IllegalStateException(errorMessage)); } return tracer.traceMonoWithLink("ServiceBus.renewMessageLock", renewMessageLock(message.getLockToken()), message, message.getContext()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Asynchronously renews the lock on the message. The lock will be renewed based on the setting specified on the * entity. * * @param lockToken to be renewed. * * @return The new expiration time for the message. * @throws IllegalStateException if receiver is already disposed. */ Mono<OffsetDateTime> renewMessageLock(String lockToken) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewMessageLock"))); } return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode.renewMessageLock(lockToken, getLinkName(null))) .map(offsetDateTime -> managementNodeLocks.addOrUpdate(lockToken, offsetDateTime, offsetDateTime)); } /** * Starts the auto lock renewal for a {@link ServiceBusReceivedMessage message}. * * @param message The {@link ServiceBusReceivedMessage} to perform this operation. * @param maxLockRenewalDuration Maximum duration to keep renewing the lock token. * * @return A Mono that completes when the message renewal operation has completed up until * {@code maxLockRenewalDuration}. * * @throws NullPointerException if {@code message}, {@code message.getLockToken()}, or * {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a session receiver or the receiver is disposed. * @throws IllegalArgumentException if {@code message.getLockToken()} is an empty value. * @throws ServiceBusException If the message lock cannot be renewed. */ public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(LOGGER, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException( String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken()))); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return tracer.traceMonoWithLink("ServiceBus.renewMessageLock", operation.getCompletionOperation(), message, message.getContext()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } /** * Renews the session lock if this receiver is a session receiver. * * @return The next expiration time for the session lock. * @throws IllegalStateException if the receiver is a non-session receiver or if receiver is already disposed. * @throws ServiceBusException if the session lock cannot be renewed. */ public Mono<OffsetDateTime> renewSessionLock() { return renewSessionLock(receiverOptions.getSessionId()); } /** * Starts the auto lock renewal for the session this receiver works for. * * @param maxLockRenewalDuration Maximum duration to keep renewing the session lock. * * @return A lock renewal operation for the message. * * @throws NullPointerException if {@code sessionId} or {@code maxLockRenewalDuration} is null. * @throws IllegalStateException if the receiver is a non-session receiver or the receiver is disposed. * @throws ServiceBusException if the session lock renewal operation cannot be started. * @throws IllegalArgumentException if {@code sessionId} is an empty string or {@code maxLockRenewalDuration} is negative. */ public Mono<Void> renewSessionLock(Duration maxLockRenewalDuration) { return this.renewSessionLock(receiverOptions.getSessionId(), maxLockRenewalDuration); } /** * Sets the state of the session this receiver works for. * * @param sessionState State to set on the session. * * @return A Mono that completes when the session is set * @throws IllegalStateException if the receiver is a non-session receiver or receiver is already disposed. * @throws ServiceBusException if the session state cannot be set. */ public Mono<Void> setSessionState(byte[] sessionState) { return this.setSessionState(receiverOptions.getSessionId(), sessionState); } /** * Starts a new service side transaction. The {@link ServiceBusTransactionContext transaction context} should be * passed to all operations that needs to be in this transaction. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if a transaction cannot be created. */ public Mono<ServiceBusTransactionContext> createTransaction() { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "createTransaction"))); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.createTransaction()) .map(transaction -> new ServiceBusTransactionContext(transaction.getTransactionId()))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Commits the transaction and all the operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to be commit. * * @return The {@link Mono} that finishes this operation on service bus resource. * * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be committed. */ public Mono<Void> commitTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "commitTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.commitTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.commitTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Rollbacks the transaction given and all operations associated with it. * * <p><strong>Creating and using a transaction</strong></p> * <!-- src_embed com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * <pre> * & * & * & * Mono&lt;ServiceBusTransactionContext&gt; transactionContext = receiver.createTransaction& * .cache& * error -&gt; Duration.ZERO, * & * * transactionContext.flatMap& * & * Mono&lt;Void&gt; operations = Mono.when& * receiver.receiveDeferredMessage& * receiver.complete& * receiver.abandon& * * & * return operations.flatMap& * & * </pre> * <!-- end com.azure.messaging.servicebus.servicebusreceiverasyncclient.committransaction * * @param transactionContext The transaction to rollback. * * @return The {@link Mono} that finishes this operation on service bus resource. * @throws NullPointerException if {@code transactionContext} or {@code transactionContext.transactionId} is null. * @throws IllegalStateException if receiver is already disposed. * @throws ServiceBusException if the transaction could not be rolled back. */ public Mono<Void> rollbackTransaction(ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "rollbackTransaction"))); } if (Objects.isNull(transactionContext)) { return monoError(LOGGER, new NullPointerException("'transactionContext' cannot be null.")); } else if (Objects.isNull(transactionContext.getTransactionId())) { return monoError(LOGGER, new NullPointerException("'transactionContext.transactionId' cannot be null.")); } return tracer.traceMono("ServiceBus.rollbackTransaction", connectionProcessor .flatMap(connection -> connection.createSession(TRANSACTION_LINK_NAME)) .flatMap(transactionSession -> transactionSession.rollbackTransaction(new AmqpTransaction( transactionContext.getTransactionId())))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RECEIVE)); } /** * Disposes of the consumer by closing the underlying links to the service. */ @Override /** * @return receiver options set by user; */ ReceiverOptions getReceiverOptions() { return receiverOptions; } /** * Gets whether or not the management node contains the message lock token and it has not expired. Lock tokens are * held by the management node when they are received from the management node or management operations are * performed using that {@code lockToken}. * * @param lockToken Lock token to check for. * * @return {@code true} if the management node contains the lock token and false otherwise. */ private boolean isManagementToken(String lockToken) { return managementNodeLocks.containsUnexpired(lockToken); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, ServiceBusTransactionContext transactionContext) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, dispositionStatus.getValue()))); } else if (Objects.isNull(message)) { return monoError(LOGGER, new NullPointerException("'message' cannot be null.")); } final String lockToken = message.getLockToken(); final String sessionId = message.getSessionId(); if (receiverOptions.getReceiveMode() != ServiceBusReceiveMode.PEEK_LOCK) { return Mono.error(LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.isSettled()) { return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The message has either been deleted or already settled."))); } else if (message.getLockToken() == null) { final String errorMessage = "This operation is not supported for peeked messages. " + "Only messages received using receiveMessages() in PEEK_LOCK mode can be settled."; return Mono.error( LOGGER.logExceptionAsError(new UnsupportedOperationException(errorMessage)) ); } final String sessionIdToUse; if (sessionId == null && !CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) { sessionIdToUse = receiverOptions.getSessionId(); } else { sessionIdToUse = sessionId; } LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(SESSION_ID_KEY, sessionIdToUse) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update started."); final Mono<Void> performOnManagement = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, sessionId, getLinkName(sessionId), transactionContext)) .then(Mono.fromRunnable(() -> { LOGGER.atInfo() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Management node Update completed."); message.setIsSettled(); managementNodeLocks.remove(lockToken); renewalContainer.remove(lockToken); })); Mono<Void> updateDispositionOperation; if (sessionManager != null) { updateDispositionOperation = sessionManager.updateDisposition(lockToken, sessionId, dispositionStatus, propertiesToModify, deadLetterReason, deadLetterErrorDescription, transactionContext) .flatMap(isSuccess -> { if (isSuccess) { message.setIsSettled(); renewalContainer.remove(lockToken); return Mono.empty(); } LOGGER.info("Could not perform on session manger. Performing on management node."); return performOnManagement; }); } else { final ServiceBusAsyncConsumer existingConsumer = consumer.get(); if (isManagementToken(lockToken) || existingConsumer == null) { updateDispositionOperation = performOnManagement; } else { updateDispositionOperation = existingConsumer.updateDisposition(lockToken, dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify, transactionContext) .then(Mono.fromRunnable(() -> { LOGGER.atVerbose() .addKeyValue(LOCK_TOKEN_KEY, lockToken) .addKeyValue(ENTITY_PATH_KEY, entityPath) .addKeyValue(DISPOSITION_STATUS_KEY, dispositionStatus) .log("Update completed."); message.setIsSettled(); renewalContainer.remove(lockToken); })); } } return instrumentation.instrumentSettlement(updateDispositionOperation, message, message.getContext(), dispositionStatus) .onErrorMap(throwable -> { if (throwable instanceof ServiceBusException) { return throwable; } switch (dispositionStatus) { case COMPLETED: return new ServiceBusException(throwable, ServiceBusErrorSource.COMPLETE); case ABANDONED: return new ServiceBusException(throwable, ServiceBusErrorSource.ABANDON); default: return new ServiceBusException(throwable, ServiceBusErrorSource.UNKNOWN); } }); } private ServiceBusAsyncConsumer getOrCreateConsumer() { final ServiceBusAsyncConsumer existing = consumer.get(); if (existing != null) { return existing; } final String linkName = StringUtil.getRandomString(entityPath); LOGGER.atInfo() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, entityPath) .log("Creating consumer."); final Mono<ServiceBusReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> { if (receiverOptions.isSessionReceiver()) { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier, receiverOptions.getSessionId()); } else { return connection.createReceiveLink(linkName, entityPath, receiverOptions.getReceiveMode(), null, entityType, identifier); } }).doOnNext(next -> { LOGGER.atVerbose() .addKeyValue(LINK_NAME_KEY, linkName) .addKeyValue(ENTITY_PATH_KEY, next.getEntityPath()) .addKeyValue("mode", receiverOptions.getReceiveMode()) .addKeyValue("isSessionEnabled", CoreUtils.isNullOrEmpty(receiverOptions.getSessionId())) .addKeyValue(ENTITY_TYPE_KEY, entityType) .log("Created consumer for Service Bus resource."); }); final Mono<ServiceBusReceiveLink> retryableReceiveLinkMono = RetryUtil.withRetry(receiveLinkMono.onErrorMap( RequestResponseChannelClosedException.class, e -> { return new AmqpException(true, e.getMessage(), e, null); }), connectionProcessor.getRetryOptions(), "Failed to create receive link " + linkName, true); final Flux<ServiceBusReceiveLink> receiveLinkFlux = retryableReceiveLinkMono.repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkFlux.subscribeWith( new ServiceBusReceiveLinkProcessor(receiverOptions.getPrefetchCount(), retryPolicy)); final ServiceBusAsyncConsumer newConsumer = new ServiceBusAsyncConsumer(linkName, linkMessageProcessor, messageSerializer, receiverOptions); if (consumer.compareAndSet(null, newConsumer)) { return newConsumer; } else { newConsumer.close(); return consumer.get(); } } /** * If the receiver has not connected via {@link * through the management node. * * @return The name of the receive link, or null of it has not connected via a receive link. */ private String getLinkName(String sessionId) { if (sessionManager != null && !CoreUtils.isNullOrEmpty(sessionId)) { return sessionManager.getLinkName(sessionId); } else if (!CoreUtils.isNullOrEmpty(sessionId) && !receiverOptions.isSessionReceiver()) { return null; } else { final ServiceBusAsyncConsumer existing = consumer.get(); return existing != null ? existing.getLinkName() : null; } } Mono<OffsetDateTime> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } final String linkName = sessionManager != null ? sessionManager.getLinkName(sessionId) : null; return tracer.traceMono("ServiceBus.renewSessionLock", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.renewSessionLock(sessionId, linkName))) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } Mono<Void> renewSessionLock(String sessionId, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException( "Cannot renew session lock on a non-session receiver.")); } else if (maxLockRenewalDuration == null) { return monoError(LOGGER, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(LOGGER, new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } else if (Objects.isNull(sessionId)) { return monoError(LOGGER, new NullPointerException("'sessionId' cannot be null.")); } else if (sessionId.isEmpty()) { return monoError(LOGGER, new IllegalArgumentException("'sessionId' cannot be empty.")); } final LockRenewalOperation operation = new LockRenewalOperation(sessionId, maxLockRenewalDuration, true, this::renewSessionLock); renewalContainer.addOrUpdate(sessionId, OffsetDateTime.now().plus(maxLockRenewalDuration), operation); return tracer.traceMono("ServiceBus.renewSessionLock", operation.getCompletionOperation()) .onErrorMap(throwable -> mapError(throwable, ServiceBusErrorSource.RENEW_LOCK)); } Mono<Void> setSessionState(String sessionId, byte[] sessionState) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "setSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot set session state on a non-session receiver.")); } final String linkName = sessionManager != null ? sessionManager.getLinkName(sessionId) : null; return tracer.traceMono("ServiceBus.setSessionState", connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.setSessionState(sessionId, sessionState, linkName))) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(LOGGER, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(LOGGER, new IllegalStateException("Cannot get session state on a non-session receiver.")); } Mono<byte[]> result; if (sessionManager != null) { result = sessionManager.getSessionState(sessionId); } else { result = connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId))); } return tracer.traceMono("ServiceBus.setSessionState", result) .onErrorMap((err) -> mapError(err, ServiceBusErrorSource.RECEIVE)); } ServiceBusReceiverInstrumentation getInstrumentation() { return instrumentation; } /** * Map the error to {@link ServiceBusException} */ private Throwable mapError(Throwable throwable, ServiceBusErrorSource errorSource) { if (!(throwable instanceof ServiceBusException)) { return new ServiceBusException(throwable, errorSource); } return throwable; } boolean isConnectionClosed() { return this.connectionProcessor.isChannelClosed(); } boolean isManagementNodeLocksClosed() { return this.managementNodeLocks.isClosed(); } boolean isRenewalContainerClosed() { return this.renewalContainer.isClosed(); } }
```suggestion ```
public void run() throws InterruptedException { AtomicBoolean sampleSuccessful = new AtomicBoolean(false); CountDownLatch countdownLatch = new CountDownLatch(1); String sessionId = "greetings-id"; ServiceBusClientBuilder builder = new ServiceBusClientBuilder() .connectionString(connectionString); ServiceBusSenderAsyncClient sender = builder .sender() .queueName(queueName) .buildAsyncClient(); List<ServiceBusMessage> messages = Arrays.asList( new ServiceBusMessage(BinaryData.fromBytes("Hello".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Bonjour".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Gluten tag".getBytes(UTF_8))).setSessionId(sessionId) ); sender.sendMessages(messages).subscribe(unused -> System.out.println("Batch sent."), error -> System.err.println("Error occurred while publishing message batch: " + error), () -> { System.out.println("Batch send complete."); sampleSuccessful.set(true); }); countdownLatch.await(10, TimeUnit.SECONDS); sender.close(); Assertions.assertTrue(sampleSuccessful.get()); }
new ServiceBusMessage(BinaryData.fromBytes("Gluten tag".getBytes(UTF_8))).setSessionId(sessionId)
public void run() throws InterruptedException { AtomicBoolean sampleSuccessful = new AtomicBoolean(false); CountDownLatch countdownLatch = new CountDownLatch(1); String sessionId = "greetings-id"; ServiceBusClientBuilder builder = new ServiceBusClientBuilder() .connectionString(connectionString); ServiceBusSenderAsyncClient sender = builder .sender() .queueName(queueName) .buildAsyncClient(); List<ServiceBusMessage> messages = Arrays.asList( new ServiceBusMessage(BinaryData.fromBytes("Hello".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Bonjour".getBytes(UTF_8))).setSessionId(sessionId) ); sender.sendMessages(messages).subscribe(unused -> System.out.println("Batch sent."), error -> System.err.println("Error occurred while publishing message batch: " + error), () -> { System.out.println("Batch send complete."); sampleSuccessful.set(true); }); countdownLatch.await(10, TimeUnit.SECONDS); sender.close(); Assertions.assertTrue(sampleSuccessful.get()); }
class SendSessionMessageAsyncSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); /** * Main method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @param args Unused arguments to the program. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ public static void main(String[] args) throws InterruptedException { SendSessionMessageAsyncSample sample = new SendSessionMessageAsyncSample(); sample.run(); } /** * This method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ @Test }
class SendSessionMessageAsyncSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); /** * Main method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @param args Unused arguments to the program. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ public static void main(String[] args) throws InterruptedException { SendSessionMessageAsyncSample sample = new SendSessionMessageAsyncSample(); sample.run(); } /** * This method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ @Test }
```suggestion new ServiceBusMessage(BinaryData.fromBytes("Bonjour".getBytes(UTF_8))).setSessionId(sessionId) ```
public void run() throws InterruptedException { AtomicBoolean sampleSuccessful = new AtomicBoolean(false); CountDownLatch countdownLatch = new CountDownLatch(1); String sessionId = "greetings-id"; ServiceBusClientBuilder builder = new ServiceBusClientBuilder() .connectionString(connectionString); ServiceBusSenderAsyncClient sender = builder .sender() .queueName(queueName) .buildAsyncClient(); List<ServiceBusMessage> messages = Arrays.asList( new ServiceBusMessage(BinaryData.fromBytes("Hello".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Bonjour".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Gluten tag".getBytes(UTF_8))).setSessionId(sessionId) ); sender.sendMessages(messages).subscribe(unused -> System.out.println("Batch sent."), error -> System.err.println("Error occurred while publishing message batch: " + error), () -> { System.out.println("Batch send complete."); sampleSuccessful.set(true); }); countdownLatch.await(10, TimeUnit.SECONDS); sender.close(); Assertions.assertTrue(sampleSuccessful.get()); }
new ServiceBusMessage(BinaryData.fromBytes("Bonjour".getBytes(UTF_8))).setSessionId(sessionId),
public void run() throws InterruptedException { AtomicBoolean sampleSuccessful = new AtomicBoolean(false); CountDownLatch countdownLatch = new CountDownLatch(1); String sessionId = "greetings-id"; ServiceBusClientBuilder builder = new ServiceBusClientBuilder() .connectionString(connectionString); ServiceBusSenderAsyncClient sender = builder .sender() .queueName(queueName) .buildAsyncClient(); List<ServiceBusMessage> messages = Arrays.asList( new ServiceBusMessage(BinaryData.fromBytes("Hello".getBytes(UTF_8))).setSessionId(sessionId), new ServiceBusMessage(BinaryData.fromBytes("Bonjour".getBytes(UTF_8))).setSessionId(sessionId) ); sender.sendMessages(messages).subscribe(unused -> System.out.println("Batch sent."), error -> System.err.println("Error occurred while publishing message batch: " + error), () -> { System.out.println("Batch send complete."); sampleSuccessful.set(true); }); countdownLatch.await(10, TimeUnit.SECONDS); sender.close(); Assertions.assertTrue(sampleSuccessful.get()); }
class SendSessionMessageAsyncSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); /** * Main method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @param args Unused arguments to the program. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ public static void main(String[] args) throws InterruptedException { SendSessionMessageAsyncSample sample = new SendSessionMessageAsyncSample(); sample.run(); } /** * This method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ @Test }
class SendSessionMessageAsyncSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); /** * Main method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @param args Unused arguments to the program. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ public static void main(String[] args) throws InterruptedException { SendSessionMessageAsyncSample sample = new SendSessionMessageAsyncSample(); sample.run(); } /** * This method to invoke this demo on how to send and receive a {@link ServiceBusMessage} to and from a * session-enabled Azure Service Bus queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the operations to complete. */ @Test }
This had a fun issue where `Double.NaN` being added resulted in the value being `Double.NaN`.
private static long getCompletedOperations(PerfTestBase<?>[] tests) { long completedOperations = 0; for (PerfTestBase<?> test : tests) { completedOperations += test.getCompletedOperations(); } return completedOperations; }
return completedOperations;
private static long getCompletedOperations(PerfTestBase<?>[] tests) { long completedOperations = 0; for (PerfTestBase<?> test : tests) { completedOperations += test.getCompletedOperations(); } return completedOperations; }
class PerfStressProgram { private static final int NANOSECONDS_PER_SECOND = 1_000_000_000; private static double getOperationsPerSecond(PerfTestBase<?>[] tests) { double operationsPerSecond = 0.0D; for (PerfTestBase<?> test : tests) { double temp = test.getCompletedOperations() / (((double) test.lastCompletionNanoTime) / NANOSECONDS_PER_SECOND); if (!Double.isNaN(temp)) { operationsPerSecond += temp; } } return operationsPerSecond; } /** * Runs the performance tests passed to be executed. * * @param classes the performance test classes to execute. * @param args the command line arguments ro run performance tests with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?>[] classes, String[] args) { List<Class<?>> classList = new ArrayList<>(Arrays.asList(classes)); try { classList.add(Class.forName("com.azure.perf.test.core.NoOpTest")); classList.add(Class.forName("com.azure.perf.test.core.MockEventProcessorTest")); classList.add(Class.forName("com.azure.perf.test.core.ExceptionTest")); classList.add(Class.forName("com.azure.perf.test.core.SleepTest")); classList.add(Class.forName("com.azure.perf.test.core.HttpPipelineTest")); classList.add(Class.forName("com.azure.perf.test.core.MockBatchReceiverTest")); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } String[] commands = classList.stream().map(c -> getCommandName(c.getSimpleName())) .toArray(i -> new String[i]); PerfStressOptions[] options = classList.stream().map(c -> { try { return c.getConstructors()[0].getParameterTypes()[0].getConstructors()[0].newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { throw new RuntimeException(e); } }).toArray(i -> new PerfStressOptions[i]); JCommander jc = new JCommander(); for (int i = 0; i < commands.length; i++) { jc.addCommand(commands[i], options[i]); } jc.parse(args); String parsedCommand = jc.getParsedCommand(); if (parsedCommand == null || parsedCommand.isEmpty()) { jc.usage(); } else { int index = Arrays.asList(commands).indexOf(parsedCommand); run(classList.get(index), options[index]); } } private static String getCommandName(String testName) { String lower = testName.toLowerCase(); return lower.endsWith("test") ? lower.substring(0, lower.length() - 4) : lower; } /** * Run the performance test passed to be executed. * * @param testClass the performance test class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } } /** * Runs the performance tests passed to be executed. * * @param tests the performance tests to be executed. * @param sync indicate if synchronous test should be run. * @param parallel the number of parallel threads to run the performance test on. * @param durationSeconds the duration for which performance test should be run on. * @param title the title of the performance tests. * * @throws RuntimeException if the execution fails. * @throws IllegalStateException if zero operations completed of the performance test. */ public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); } private static Disposable printStatus(String header, Supplier<Object> status, boolean newLine, boolean printFinalStatus) { System.out.println(header); boolean[] needsExtraNewline = new boolean[]{false}; return Flux.interval(Duration.ofSeconds(1)).doFinally(s -> { if (printFinalStatus) { printStatusHelper(status, newLine, needsExtraNewline); } if (needsExtraNewline[0]) { System.out.println(); } System.out.println(); }).subscribe(i -> { printStatusHelper(status, newLine, needsExtraNewline); }); } private static void printStatusHelper(Supplier<Object> status, boolean newLine, boolean[] needsExtraNewline) { Object obj = status.get(); if (newLine) { System.out.println(obj); } else { System.out.print(obj); needsExtraNewline[0] = true; } } }
class PerfStressProgram { private static final int NANOSECONDS_PER_SECOND = 1_000_000_000; private static double getOperationsPerSecond(PerfTestBase<?>[] tests) { double operationsPerSecond = 0.0D; for (PerfTestBase<?> test : tests) { double temp = test.getCompletedOperations() / (((double) test.lastCompletionNanoTime) / NANOSECONDS_PER_SECOND); if (!Double.isNaN(temp)) { operationsPerSecond += temp; } } return operationsPerSecond; } /** * Runs the performance tests passed to be executed. * * @param classes the performance test classes to execute. * @param args the command line arguments ro run performance tests with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?>[] classes, String[] args) { List<Class<?>> classList = new ArrayList<>(Arrays.asList(classes)); try { classList.add(Class.forName("com.azure.perf.test.core.NoOpTest")); classList.add(Class.forName("com.azure.perf.test.core.MockEventProcessorTest")); classList.add(Class.forName("com.azure.perf.test.core.ExceptionTest")); classList.add(Class.forName("com.azure.perf.test.core.SleepTest")); classList.add(Class.forName("com.azure.perf.test.core.HttpPipelineTest")); classList.add(Class.forName("com.azure.perf.test.core.MockBatchReceiverTest")); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } String[] commands = classList.stream().map(c -> getCommandName(c.getSimpleName())) .toArray(i -> new String[i]); PerfStressOptions[] options = classList.stream().map(c -> { try { return c.getConstructors()[0].getParameterTypes()[0].getConstructors()[0].newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { throw new RuntimeException(e); } }).toArray(i -> new PerfStressOptions[i]); JCommander jc = new JCommander(); for (int i = 0; i < commands.length; i++) { jc.addCommand(commands[i], options[i]); } jc.parse(args); String parsedCommand = jc.getParsedCommand(); if (parsedCommand == null || parsedCommand.isEmpty()) { jc.usage(); } else { int index = Arrays.asList(commands).indexOf(parsedCommand); run(classList.get(index), options[index]); } } private static String getCommandName(String testName) { String lower = testName.toLowerCase(); return lower.endsWith("test") ? lower.substring(0, lower.length() - 4) : lower; } /** * Run the performance test passed to be executed. * * @param testClass the performance test class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } } /** * Runs the performance tests passed to be executed. * * @param tests the performance tests to be executed. * @param sync indicate if synchronous test should be run. * @param parallel the number of parallel threads to run the performance test on. * @param durationSeconds the duration for which performance test should be run on. * @param title the title of the performance tests. * * @throws RuntimeException if the execution fails. * @throws IllegalStateException if zero operations completed of the performance test. */ public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); } private static Disposable printStatus(String header, Supplier<Object> status, boolean newLine, boolean printFinalStatus) { System.out.println(header); boolean[] needsExtraNewline = new boolean[]{false}; return Flux.interval(Duration.ofSeconds(1)).doFinally(s -> { if (printFinalStatus) { printStatusHelper(status, newLine, needsExtraNewline); } if (needsExtraNewline[0]) { System.out.println(); } System.out.println(); }).subscribe(i -> { printStatusHelper(status, newLine, needsExtraNewline); }); } private static void printStatusHelper(Supplier<Object> status, boolean newLine, boolean[] needsExtraNewline) { Object obj = status.get(); if (newLine) { System.out.println(obj); } else { System.out.print(obj); needsExtraNewline[0] = true; } } }
Why do we need to check if the timer expired twice? The timer is approximate so running one extra operation should be fine. Returning a result of "0" won't increase completedOperations, but it will update lastCompletionNanoTime, which seems wrong.
public Mono<Void> runAllAsync(long endNanoTime) { completedOperations = 0; lastCompletionNanoTime = 0; long startNanoTime = System.nanoTime(); return Flux.generate(sink -> { if (System.nanoTime() < endNanoTime) { sink.next(1); } else { sink.complete(); } }) .flatMap(ignored -> { if (System.nanoTime() < endNanoTime) { return runTestAsync(); } else { return Mono.just(0); } }, 1) .doOnNext(result -> { completedOperations += result; lastCompletionNanoTime = System.nanoTime() - startNanoTime; }) .then(); }
.flatMap(ignored -> {
public Mono<Void> runAllAsync(long endNanoTime) { completedOperations = 0; lastCompletionNanoTime = 0; long startNanoTime = System.nanoTime(); return Flux.generate(sink -> { if (System.nanoTime() < endNanoTime) { sink.next(1); } else { sink.complete(); } }) .flatMap(ignored -> { if (System.nanoTime() < endNanoTime) { return runTestAsync(); } else { return Mono.just(0); } }, 1) .doOnNext(result -> { completedOperations += result; lastCompletionNanoTime = System.nanoTime() - startNanoTime; }) .then(); }
class ApiPerfTestBase<TOptions extends PerfStressOptions> extends PerfTestBase<TOptions> { private final reactor.netty.http.client.HttpClient recordPlaybackHttpClient; private final URI testProxy; private final TestProxyPolicy testProxyPolicy; private String recordingId; private long completedOperations; protected final HttpClient httpClient; protected final Iterable<HttpPipelinePolicy> policies; /** * Creates an instance of the Http Based Performance test. * * @param options the performance test options to use while running the test. * @throws IllegalStateException if an errors is encountered with building ssl context. */ public ApiPerfTestBase(TOptions options) { super(options); httpClient = createHttpClient(options); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { recordPlaybackHttpClient = createRecordPlaybackClient(options); testProxy = options.getTestProxies().get(parallelIndex % options.getTestProxies().size()); testProxyPolicy = new TestProxyPolicy(testProxy); policies = Collections.singletonList(testProxyPolicy); } else { recordPlaybackHttpClient = null; testProxy = null; testProxyPolicy = null; policies = null; } } private static HttpClient createHttpClient(PerfStressOptions options) { PerfStressOptions.HttpClientType httpClientType = options.getHttpClient(); switch (httpClientType) { case NETTY: if (options.isInsecure()) { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); reactor.netty.http.client.HttpClient nettyHttpClient = reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); return new NettyAsyncHttpClientBuilder(nettyHttpClient).build(); } catch (SSLException e) { throw new IllegalStateException(e); } } else { return new NettyAsyncHttpClientProvider().createInstance(); } case OKHTTP: if (options.isInsecure()) { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init( null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), new SecureRandom()); OkHttpClient okHttpClient = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0]) .build(); return new OkHttpAsyncHttpClientBuilder(okHttpClient).build(); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new IllegalStateException(e); } } else { return new OkHttpAsyncClientProvider().createInstance(); } default: throw new IllegalArgumentException("Unsupported http client " + httpClientType); } } private static reactor.netty.http.client.HttpClient createRecordPlaybackClient(PerfStressOptions options) { if (options.isInsecure()) { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); return reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException e) { throw new IllegalStateException(e); } } else { return reactor.netty.http.client.HttpClient.create(); } } /** * Attempts to configure a ClientBuilder using reflection. If a ClientBuilder does not follow the standard * convention, it can be configured manually using the "httpClient" and "policies" fields. * * @param clientBuilder The client builder. * @throws IllegalStateException If reflective access to get httpClient or addPolicy methods fail. */ protected void configureClientBuilder(HttpTrait<?> clientBuilder) { if (httpClient != null) { clientBuilder.httpClient(httpClient); } if (policies != null) { for (HttpPipelinePolicy policy : policies) { clientBuilder.addPolicy(policy); } } } @Override public void runAll(long endNanoTime) { completedOperations = 0; lastCompletionNanoTime = 0; long startNanoTime = System.nanoTime(); while (System.nanoTime() < endNanoTime) { completedOperations += runTest(); lastCompletionNanoTime = System.nanoTime() - startNanoTime; } } @Override /** * Indicates how many operations were completed in a single run of the test. Good to be used for batch operations. * * @return the number of successful operations completed. */ abstract int runTest(); /** * Indicates how many operations were completed in a single run of the async test. Good to be used for batch * operations. * * @return the number of successful operations completed. */ abstract Mono<Integer> runTestAsync(); /** * Stops playback tests. * * @return An empty {@link Mono}. */ public Mono<Void> stopPlaybackAsync() { return recordPlaybackHttpClient .headers(h -> { h.set("x-recording-id", recordingId); h.set("x-purge-inmemory-recording", Boolean.toString(true)); }) .post() .uri(testProxy.resolve("/playback/stop")) .response() .doOnSuccess(response -> { testProxyPolicy.setMode(null); testProxyPolicy.setRecordingId(null); }) .then(); } private Mono<Void> startRecordingAsync() { return Mono.defer(() -> recordPlaybackHttpClient .post() .uri(testProxy.resolve("/record/start")) .response() .doOnNext(response -> { recordingId = response.responseHeaders().get("x-recording-id"); }).then()); } private Mono<Void> stopRecordingAsync() { return Mono.defer(() -> recordPlaybackHttpClient .headers(h -> h.set("x-recording-id", recordingId)) .post() .uri(testProxy.resolve("/record/stop")) .response() .then()); } private Mono<Void> startPlaybackAsync() { return Mono.defer(() -> recordPlaybackHttpClient .headers(h -> h.set("x-recording-id", recordingId)) .post() .uri(testProxy.resolve("/playback/start")) .response() .doOnNext(response -> { recordingId = response.responseHeaders().get("x-recording-id"); }).then()); } /** * Records responses and starts tests in playback mode. * * @return */ @Override Mono<Void> postSetupAsync() { if (testProxyPolicy != null) { return runSyncOrAsync() .then(startRecordingAsync()) .then(Mono.defer(() -> { testProxyPolicy.setRecordingId(recordingId); testProxyPolicy.setMode("record"); return Mono.empty(); })) .then(runSyncOrAsync()) .then(stopRecordingAsync()) .then(startPlaybackAsync()) .then(Mono.defer(() -> { testProxyPolicy.setRecordingId(recordingId); testProxyPolicy.setMode("playback"); return Mono.empty(); })); } return Mono.empty(); } private Mono<Void> runSyncOrAsync() { return Mono.defer(() -> { if (options.isSync()) { return Mono.fromFuture(CompletableFuture.supplyAsync(() -> runTest())).then(); } else { return runTestAsync().then(); } }); } @Override public long getCompletedOperations() { return completedOperations; } }
class ApiPerfTestBase<TOptions extends PerfStressOptions> extends PerfTestBase<TOptions> { private final reactor.netty.http.client.HttpClient recordPlaybackHttpClient; private final URI testProxy; private final TestProxyPolicy testProxyPolicy; private String recordingId; private long completedOperations; protected final HttpClient httpClient; protected final Iterable<HttpPipelinePolicy> policies; /** * Creates an instance of the Http Based Performance test. * * @param options the performance test options to use while running the test. * @throws IllegalStateException if an errors is encountered with building ssl context. */ public ApiPerfTestBase(TOptions options) { super(options); httpClient = createHttpClient(options); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { recordPlaybackHttpClient = createRecordPlaybackClient(options); testProxy = options.getTestProxies().get(parallelIndex % options.getTestProxies().size()); testProxyPolicy = new TestProxyPolicy(testProxy); policies = Collections.singletonList(testProxyPolicy); } else { recordPlaybackHttpClient = null; testProxy = null; testProxyPolicy = null; policies = null; } } private static HttpClient createHttpClient(PerfStressOptions options) { PerfStressOptions.HttpClientType httpClientType = options.getHttpClient(); switch (httpClientType) { case NETTY: if (options.isInsecure()) { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); reactor.netty.http.client.HttpClient nettyHttpClient = reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); return new NettyAsyncHttpClientBuilder(nettyHttpClient).build(); } catch (SSLException e) { throw new IllegalStateException(e); } } else { return new NettyAsyncHttpClientProvider().createInstance(); } case OKHTTP: if (options.isInsecure()) { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init( null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), new SecureRandom()); OkHttpClient okHttpClient = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0]) .build(); return new OkHttpAsyncHttpClientBuilder(okHttpClient).build(); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new IllegalStateException(e); } } else { return new OkHttpAsyncClientProvider().createInstance(); } default: throw new IllegalArgumentException("Unsupported http client " + httpClientType); } } private static reactor.netty.http.client.HttpClient createRecordPlaybackClient(PerfStressOptions options) { if (options.isInsecure()) { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); return reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException e) { throw new IllegalStateException(e); } } else { return reactor.netty.http.client.HttpClient.create(); } } /** * Attempts to configure a ClientBuilder using reflection. If a ClientBuilder does not follow the standard * convention, it can be configured manually using the "httpClient" and "policies" fields. * * @param clientBuilder The client builder. * @throws IllegalStateException If reflective access to get httpClient or addPolicy methods fail. */ protected void configureClientBuilder(HttpTrait<?> clientBuilder) { if (httpClient != null) { clientBuilder.httpClient(httpClient); } if (policies != null) { for (HttpPipelinePolicy policy : policies) { clientBuilder.addPolicy(policy); } } } @Override public void runAll(long endNanoTime) { completedOperations = 0; lastCompletionNanoTime = 0; long startNanoTime = System.nanoTime(); while (System.nanoTime() < endNanoTime) { completedOperations += runTest(); lastCompletionNanoTime = System.nanoTime() - startNanoTime; } } @Override /** * Indicates how many operations were completed in a single run of the test. Good to be used for batch operations. * * @return the number of successful operations completed. */ abstract int runTest(); /** * Indicates how many operations were completed in a single run of the async test. Good to be used for batch * operations. * * @return the number of successful operations completed. */ abstract Mono<Integer> runTestAsync(); /** * Stops playback tests. * * @return An empty {@link Mono}. */ public Mono<Void> stopPlaybackAsync() { return recordPlaybackHttpClient .headers(h -> { h.set("x-recording-id", recordingId); h.set("x-purge-inmemory-recording", Boolean.toString(true)); }) .post() .uri(testProxy.resolve("/playback/stop")) .response() .doOnSuccess(response -> { testProxyPolicy.setMode(null); testProxyPolicy.setRecordingId(null); }) .then(); } private Mono<Void> startRecordingAsync() { return Mono.defer(() -> recordPlaybackHttpClient .post() .uri(testProxy.resolve("/record/start")) .response() .doOnNext(response -> { recordingId = response.responseHeaders().get("x-recording-id"); }).then()); } private Mono<Void> stopRecordingAsync() { return Mono.defer(() -> recordPlaybackHttpClient .headers(h -> h.set("x-recording-id", recordingId)) .post() .uri(testProxy.resolve("/record/stop")) .response() .then()); } private Mono<Void> startPlaybackAsync() { return Mono.defer(() -> recordPlaybackHttpClient .headers(h -> h.set("x-recording-id", recordingId)) .post() .uri(testProxy.resolve("/playback/start")) .response() .doOnNext(response -> { recordingId = response.responseHeaders().get("x-recording-id"); }).then()); } /** * Records responses and starts tests in playback mode. * * @return */ @Override Mono<Void> postSetupAsync() { if (testProxyPolicy != null) { return runSyncOrAsync() .then(startRecordingAsync()) .then(Mono.defer(() -> { testProxyPolicy.setRecordingId(recordingId); testProxyPolicy.setMode("record"); return Mono.empty(); })) .then(runSyncOrAsync()) .then(stopRecordingAsync()) .then(startPlaybackAsync()) .then(Mono.defer(() -> { testProxyPolicy.setRecordingId(recordingId); testProxyPolicy.setMode("playback"); return Mono.empty(); })); } return Mono.empty(); } private Mono<Void> runSyncOrAsync() { return Mono.defer(() -> { if (options.isSync()) { return Mono.fromFuture(CompletableFuture.supplyAsync(() -> runTest())).then(); } else { return runTestAsync().then(); } }); } @Override public long getCompletedOperations() { return completedOperations; } }
Why was this changed? To avoid using Reactor?
private static long getCompletedOperations(PerfTestBase<?>[] tests) { long completedOperations = 0; for (PerfTestBase<?> test : tests) { completedOperations += test.getCompletedOperations(); } return completedOperations; }
}
private static long getCompletedOperations(PerfTestBase<?>[] tests) { long completedOperations = 0; for (PerfTestBase<?> test : tests) { completedOperations += test.getCompletedOperations(); } return completedOperations; }
class PerfStressProgram { private static final int NANOSECONDS_PER_SECOND = 1_000_000_000; private static double getOperationsPerSecond(PerfTestBase<?>[] tests) { double operationsPerSecond = 0.0D; for (PerfTestBase<?> test : tests) { double temp = test.getCompletedOperations() / (((double) test.lastCompletionNanoTime) / NANOSECONDS_PER_SECOND); if (!Double.isNaN(temp)) { operationsPerSecond += temp; } } return operationsPerSecond; } /** * Runs the performance tests passed to be executed. * * @param classes the performance test classes to execute. * @param args the command line arguments ro run performance tests with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?>[] classes, String[] args) { List<Class<?>> classList = new ArrayList<>(Arrays.asList(classes)); try { classList.add(Class.forName("com.azure.perf.test.core.NoOpTest")); classList.add(Class.forName("com.azure.perf.test.core.MockEventProcessorTest")); classList.add(Class.forName("com.azure.perf.test.core.ExceptionTest")); classList.add(Class.forName("com.azure.perf.test.core.SleepTest")); classList.add(Class.forName("com.azure.perf.test.core.HttpPipelineTest")); classList.add(Class.forName("com.azure.perf.test.core.MockBatchReceiverTest")); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } String[] commands = classList.stream().map(c -> getCommandName(c.getSimpleName())) .toArray(i -> new String[i]); PerfStressOptions[] options = classList.stream().map(c -> { try { return c.getConstructors()[0].getParameterTypes()[0].getConstructors()[0].newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { throw new RuntimeException(e); } }).toArray(i -> new PerfStressOptions[i]); JCommander jc = new JCommander(); for (int i = 0; i < commands.length; i++) { jc.addCommand(commands[i], options[i]); } jc.parse(args); String parsedCommand = jc.getParsedCommand(); if (parsedCommand == null || parsedCommand.isEmpty()) { jc.usage(); } else { int index = Arrays.asList(commands).indexOf(parsedCommand); run(classList.get(index), options[index]); } } private static String getCommandName(String testName) { String lower = testName.toLowerCase(); return lower.endsWith("test") ? lower.substring(0, lower.length() - 4) : lower; } /** * Run the performance test passed to be executed. * * @param testClass the performance test class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } } /** * Runs the performance tests passed to be executed. * * @param tests the performance tests to be executed. * @param sync indicate if synchronous test should be run. * @param parallel the number of parallel threads to run the performance test on. * @param durationSeconds the duration for which performance test should be run on. * @param title the title of the performance tests. * * @throws RuntimeException if the execution fails. * @throws IllegalStateException if zero operations completed of the performance test. */ public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); } private static Disposable printStatus(String header, Supplier<Object> status, boolean newLine, boolean printFinalStatus) { System.out.println(header); boolean[] needsExtraNewline = new boolean[]{false}; return Flux.interval(Duration.ofSeconds(1)).doFinally(s -> { if (printFinalStatus) { printStatusHelper(status, newLine, needsExtraNewline); } if (needsExtraNewline[0]) { System.out.println(); } System.out.println(); }).subscribe(i -> { printStatusHelper(status, newLine, needsExtraNewline); }); } private static void printStatusHelper(Supplier<Object> status, boolean newLine, boolean[] needsExtraNewline) { Object obj = status.get(); if (newLine) { System.out.println(obj); } else { System.out.print(obj); needsExtraNewline[0] = true; } } }
class PerfStressProgram { private static final int NANOSECONDS_PER_SECOND = 1_000_000_000; private static double getOperationsPerSecond(PerfTestBase<?>[] tests) { double operationsPerSecond = 0.0D; for (PerfTestBase<?> test : tests) { double temp = test.getCompletedOperations() / (((double) test.lastCompletionNanoTime) / NANOSECONDS_PER_SECOND); if (!Double.isNaN(temp)) { operationsPerSecond += temp; } } return operationsPerSecond; } /** * Runs the performance tests passed to be executed. * * @param classes the performance test classes to execute. * @param args the command line arguments ro run performance tests with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?>[] classes, String[] args) { List<Class<?>> classList = new ArrayList<>(Arrays.asList(classes)); try { classList.add(Class.forName("com.azure.perf.test.core.NoOpTest")); classList.add(Class.forName("com.azure.perf.test.core.MockEventProcessorTest")); classList.add(Class.forName("com.azure.perf.test.core.ExceptionTest")); classList.add(Class.forName("com.azure.perf.test.core.SleepTest")); classList.add(Class.forName("com.azure.perf.test.core.HttpPipelineTest")); classList.add(Class.forName("com.azure.perf.test.core.MockBatchReceiverTest")); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } String[] commands = classList.stream().map(c -> getCommandName(c.getSimpleName())) .toArray(i -> new String[i]); PerfStressOptions[] options = classList.stream().map(c -> { try { return c.getConstructors()[0].getParameterTypes()[0].getConstructors()[0].newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { throw new RuntimeException(e); } }).toArray(i -> new PerfStressOptions[i]); JCommander jc = new JCommander(); for (int i = 0; i < commands.length; i++) { jc.addCommand(commands[i], options[i]); } jc.parse(args); String parsedCommand = jc.getParsedCommand(); if (parsedCommand == null || parsedCommand.isEmpty()) { jc.usage(); } else { int index = Arrays.asList(commands).indexOf(parsedCommand); run(classList.get(index), options[index]); } } private static String getCommandName(String testName) { String lower = testName.toLowerCase(); return lower.endsWith("test") ? lower.substring(0, lower.length() - 4) : lower; } /** * Run the performance test passed to be executed. * * @param testClass the performance test class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } } /** * Runs the performance tests passed to be executed. * * @param tests the performance tests to be executed. * @param sync indicate if synchronous test should be run. * @param parallel the number of parallel threads to run the performance test on. * @param durationSeconds the duration for which performance test should be run on. * @param title the title of the performance tests. * * @throws RuntimeException if the execution fails. * @throws IllegalStateException if zero operations completed of the performance test. */ public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); } private static Disposable printStatus(String header, Supplier<Object> status, boolean newLine, boolean printFinalStatus) { System.out.println(header); boolean[] needsExtraNewline = new boolean[]{false}; return Flux.interval(Duration.ofSeconds(1)).doFinally(s -> { if (printFinalStatus) { printStatusHelper(status, newLine, needsExtraNewline); } if (needsExtraNewline[0]) { System.out.println(); } System.out.println(); }).subscribe(i -> { printStatusHelper(status, newLine, needsExtraNewline); }); } private static void printStatusHelper(Supplier<Object> status, boolean newLine, boolean[] needsExtraNewline) { Object obj = status.get(); if (newLine) { System.out.println(obj); } else { System.out.print(obj); needsExtraNewline[0] = true; } } }
Why was this changed?
public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); }
List<Callable<Integer>> operations = new ArrayList<>(parallel);
public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); }
class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } }
class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } }
I think the `Math.min(parallel, 1000 / parallel)` might be incorrect.
public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); }
.flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1)
public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); }
class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } }
class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } }
This will be removed in #32020
public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); }
.flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1)
public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); }
class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } }
class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } }
This was changed as the previous implementation didn't behave as expected. What it did before was create a single task that then ran whatever limit `.parallel()` had for parallelization. It now runs `parallel` tasks concurrently as expected.
public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); }
List<Callable<Integer>> operations = new ArrayList<>(parallel);
public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); }
class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } }
class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } }
This was using Java Streams before but wasn't needed and just a simplification of logic.
private static long getCompletedOperations(PerfTestBase<?>[] tests) { long completedOperations = 0; for (PerfTestBase<?> test : tests) { completedOperations += test.getCompletedOperations(); } return completedOperations; }
}
private static long getCompletedOperations(PerfTestBase<?>[] tests) { long completedOperations = 0; for (PerfTestBase<?> test : tests) { completedOperations += test.getCompletedOperations(); } return completedOperations; }
class PerfStressProgram { private static final int NANOSECONDS_PER_SECOND = 1_000_000_000; private static double getOperationsPerSecond(PerfTestBase<?>[] tests) { double operationsPerSecond = 0.0D; for (PerfTestBase<?> test : tests) { double temp = test.getCompletedOperations() / (((double) test.lastCompletionNanoTime) / NANOSECONDS_PER_SECOND); if (!Double.isNaN(temp)) { operationsPerSecond += temp; } } return operationsPerSecond; } /** * Runs the performance tests passed to be executed. * * @param classes the performance test classes to execute. * @param args the command line arguments ro run performance tests with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?>[] classes, String[] args) { List<Class<?>> classList = new ArrayList<>(Arrays.asList(classes)); try { classList.add(Class.forName("com.azure.perf.test.core.NoOpTest")); classList.add(Class.forName("com.azure.perf.test.core.MockEventProcessorTest")); classList.add(Class.forName("com.azure.perf.test.core.ExceptionTest")); classList.add(Class.forName("com.azure.perf.test.core.SleepTest")); classList.add(Class.forName("com.azure.perf.test.core.HttpPipelineTest")); classList.add(Class.forName("com.azure.perf.test.core.MockBatchReceiverTest")); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } String[] commands = classList.stream().map(c -> getCommandName(c.getSimpleName())) .toArray(i -> new String[i]); PerfStressOptions[] options = classList.stream().map(c -> { try { return c.getConstructors()[0].getParameterTypes()[0].getConstructors()[0].newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { throw new RuntimeException(e); } }).toArray(i -> new PerfStressOptions[i]); JCommander jc = new JCommander(); for (int i = 0; i < commands.length; i++) { jc.addCommand(commands[i], options[i]); } jc.parse(args); String parsedCommand = jc.getParsedCommand(); if (parsedCommand == null || parsedCommand.isEmpty()) { jc.usage(); } else { int index = Arrays.asList(commands).indexOf(parsedCommand); run(classList.get(index), options[index]); } } private static String getCommandName(String testName) { String lower = testName.toLowerCase(); return lower.endsWith("test") ? lower.substring(0, lower.length() - 4) : lower; } /** * Run the performance test passed to be executed. * * @param testClass the performance test class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } } /** * Runs the performance tests passed to be executed. * * @param tests the performance tests to be executed. * @param sync indicate if synchronous test should be run. * @param parallel the number of parallel threads to run the performance test on. * @param durationSeconds the duration for which performance test should be run on. * @param title the title of the performance tests. * * @throws RuntimeException if the execution fails. * @throws IllegalStateException if zero operations completed of the performance test. */ public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); } private static Disposable printStatus(String header, Supplier<Object> status, boolean newLine, boolean printFinalStatus) { System.out.println(header); boolean[] needsExtraNewline = new boolean[]{false}; return Flux.interval(Duration.ofSeconds(1)).doFinally(s -> { if (printFinalStatus) { printStatusHelper(status, newLine, needsExtraNewline); } if (needsExtraNewline[0]) { System.out.println(); } System.out.println(); }).subscribe(i -> { printStatusHelper(status, newLine, needsExtraNewline); }); } private static void printStatusHelper(Supplier<Object> status, boolean newLine, boolean[] needsExtraNewline) { Object obj = status.get(); if (newLine) { System.out.println(obj); } else { System.out.print(obj); needsExtraNewline[0] = true; } } }
class PerfStressProgram { private static final int NANOSECONDS_PER_SECOND = 1_000_000_000; private static double getOperationsPerSecond(PerfTestBase<?>[] tests) { double operationsPerSecond = 0.0D; for (PerfTestBase<?> test : tests) { double temp = test.getCompletedOperations() / (((double) test.lastCompletionNanoTime) / NANOSECONDS_PER_SECOND); if (!Double.isNaN(temp)) { operationsPerSecond += temp; } } return operationsPerSecond; } /** * Runs the performance tests passed to be executed. * * @param classes the performance test classes to execute. * @param args the command line arguments ro run performance tests with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?>[] classes, String[] args) { List<Class<?>> classList = new ArrayList<>(Arrays.asList(classes)); try { classList.add(Class.forName("com.azure.perf.test.core.NoOpTest")); classList.add(Class.forName("com.azure.perf.test.core.MockEventProcessorTest")); classList.add(Class.forName("com.azure.perf.test.core.ExceptionTest")); classList.add(Class.forName("com.azure.perf.test.core.SleepTest")); classList.add(Class.forName("com.azure.perf.test.core.HttpPipelineTest")); classList.add(Class.forName("com.azure.perf.test.core.MockBatchReceiverTest")); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } String[] commands = classList.stream().map(c -> getCommandName(c.getSimpleName())) .toArray(i -> new String[i]); PerfStressOptions[] options = classList.stream().map(c -> { try { return c.getConstructors()[0].getParameterTypes()[0].getConstructors()[0].newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { throw new RuntimeException(e); } }).toArray(i -> new PerfStressOptions[i]); JCommander jc = new JCommander(); for (int i = 0; i < commands.length; i++) { jc.addCommand(commands[i], options[i]); } jc.parse(args); String parsedCommand = jc.getParsedCommand(); if (parsedCommand == null || parsedCommand.isEmpty()) { jc.usage(); } else { int index = Arrays.asList(commands).indexOf(parsedCommand); run(classList.get(index), options[index]); } } private static String getCommandName(String testName) { String lower = testName.toLowerCase(); return lower.endsWith("test") ? lower.substring(0, lower.length() - 4) : lower; } /** * Run the performance test passed to be executed. * * @param testClass the performance test class to execute. * @param options the configuration ro run performance test with. * * @throws RuntimeException if the execution fails. */ public static void run(Class<?> testClass, PerfStressOptions options) { System.out.println("=== Options ==="); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.writeValue(System.out, options); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(); System.out.println(); Disposable setupStatus = printStatus("=== Setup ===", () -> ".", false, false); Disposable cleanupStatus = null; PerfTestBase<?>[] tests = new PerfTestBase<?>[options.getParallel()]; for (int i = 0; i < options.getParallel(); i++) { try { tests[i] = (PerfTestBase<?>) testClass.getConstructor(options.getClass()).newInstance(options); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException | NoSuchMethodException e) { throw new RuntimeException(e); } } try { tests[0].globalSetupAsync().block(); boolean startedPlayback = false; try { Flux.just(tests).flatMap(PerfTestBase::setupAsync).blockLast(); setupStatus.dispose(); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { Disposable recordStatus = printStatus("=== Record and Start Playback ===", () -> ".", false, false); try { ForkJoinPool forkJoinPool = new ForkJoinPool(tests.length); forkJoinPool.submit(() -> { IntStream.range(0, tests.length).parallel().forEach(i -> tests[i].postSetupAsync().block()); }).get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } startedPlayback = true; recordStatus.dispose(); } if (options.getWarmup() > 0) { runTests(tests, options.isSync(), options.getParallel(), options.getWarmup(), "Warmup"); } for (int i = 0; i < options.getIterations(); i++) { String title = "Test"; if (options.getIterations() > 1) { title += " " + (i + 1); } runTests(tests, options.isSync(), options.getParallel(), options.getDuration(), title); } } finally { try { if (startedPlayback) { Disposable playbackStatus = printStatus("=== Stop Playback ===", () -> ".", false, false); Flux.just(tests).flatMap(perfTestBase -> { if (perfTestBase instanceof ApiPerfTestBase) { return ((ApiPerfTestBase<?>) perfTestBase).stopPlaybackAsync(); } else { return Mono.error(new IllegalStateException("Test Proxy not supported.")); } }).blockLast(); playbackStatus.dispose(); } } finally { if (!options.isNoCleanup()) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); Flux.just(tests).flatMap(PerfTestBase::cleanupAsync).blockLast(); } } } } finally { if (!options.isNoCleanup()) { if (cleanupStatus == null) { cleanupStatus = printStatus("=== Cleanup ===", () -> ".", false, false); } tests[0].globalCleanupAsync().block(); } } if (cleanupStatus != null) { cleanupStatus.dispose(); } } /** * Runs the performance tests passed to be executed. * * @param tests the performance tests to be executed. * @param sync indicate if synchronous test should be run. * @param parallel the number of parallel threads to run the performance test on. * @param durationSeconds the duration for which performance test should be run on. * @param title the title of the performance tests. * * @throws RuntimeException if the execution fails. * @throws IllegalStateException if zero operations completed of the performance test. */ public static void runTests(PerfTestBase<?>[] tests, boolean sync, int parallel, int durationSeconds, String title) { long endNanoTime = System.nanoTime() + ((long) durationSeconds * 1000000000); long[] lastCompleted = new long[]{0}; Disposable progressStatus = printStatus( "=== " + title + " ===" + System.lineSeparator() + "Current\t\tTotal\t\tAverage", () -> { long totalCompleted = getCompletedOperations(tests); long currentCompleted = totalCompleted - lastCompleted[0]; double averageCompleted = getOperationsPerSecond(tests); lastCompleted[0] = totalCompleted; return String.format("%d\t\t%d\t\t%.2f", currentCompleted, totalCompleted, averageCompleted); }, true, true); try { if (sync) { ForkJoinPool forkJoinPool = new ForkJoinPool(parallel); List<Callable<Integer>> operations = new ArrayList<>(parallel); for (PerfTestBase<?> test : tests) { operations.add(() -> { test.runAll(endNanoTime); return 1; }); } forkJoinPool.invokeAll(operations, (durationSeconds * 1000L) + 100L, TimeUnit.MILLISECONDS); forkJoinPool.shutdown(); } else { Schedulers.onHandleError((t, e) -> { System.err.print(t + " threw exception: "); e.printStackTrace(); System.exit(1); }); Flux.range(0, parallel) .parallel(parallel) .runOn(Schedulers.parallel()) .flatMap(i -> tests[i].runAllAsync(endNanoTime), false, Math.min(parallel, 1000 / parallel), 1) .then() .block(); } } catch (InterruptedException e) { System.err.println("Error occurred when submitting jobs to ForkJoinPool. " + System.lineSeparator() + e); e.printStackTrace(System.err); throw new RuntimeException(e); } catch (Exception e) { System.err.println("Error occurred running tests: " + System.lineSeparator() + e); e.printStackTrace(System.err); } finally { progressStatus.dispose(); } System.out.println("=== Results ==="); long totalOperations = getCompletedOperations(tests); if (totalOperations == 0) { throw new IllegalStateException("Zero operations has been completed"); } double operationsPerSecond = getOperationsPerSecond(tests); double secondsPerOperation = 1 / operationsPerSecond; double weightedAverageSeconds = totalOperations / operationsPerSecond; System.out.printf("Completed %,d operations in a weighted-average of %ss (%s ops/s, %s s/op)%n", totalOperations, NumberFormatter.Format(weightedAverageSeconds, 4), NumberFormatter.Format(operationsPerSecond, 4), NumberFormatter.Format(secondsPerOperation, 4)); System.out.println(); } private static Disposable printStatus(String header, Supplier<Object> status, boolean newLine, boolean printFinalStatus) { System.out.println(header); boolean[] needsExtraNewline = new boolean[]{false}; return Flux.interval(Duration.ofSeconds(1)).doFinally(s -> { if (printFinalStatus) { printStatusHelper(status, newLine, needsExtraNewline); } if (needsExtraNewline[0]) { System.out.println(); } System.out.println(); }).subscribe(i -> { printStatusHelper(status, newLine, needsExtraNewline); }); } private static void printStatusHelper(Supplier<Object> status, boolean newLine, boolean[] needsExtraNewline) { Object obj = status.get(); if (newLine) { System.out.println(obj); } else { System.out.print(obj); needsExtraNewline[0] = true; } } }
I'll revert this in #32020
public Mono<Void> runAllAsync(long endNanoTime) { completedOperations = 0; lastCompletionNanoTime = 0; long startNanoTime = System.nanoTime(); return Flux.generate(sink -> { if (System.nanoTime() < endNanoTime) { sink.next(1); } else { sink.complete(); } }) .flatMap(ignored -> { if (System.nanoTime() < endNanoTime) { return runTestAsync(); } else { return Mono.just(0); } }, 1) .doOnNext(result -> { completedOperations += result; lastCompletionNanoTime = System.nanoTime() - startNanoTime; }) .then(); }
.flatMap(ignored -> {
public Mono<Void> runAllAsync(long endNanoTime) { completedOperations = 0; lastCompletionNanoTime = 0; long startNanoTime = System.nanoTime(); return Flux.generate(sink -> { if (System.nanoTime() < endNanoTime) { sink.next(1); } else { sink.complete(); } }) .flatMap(ignored -> { if (System.nanoTime() < endNanoTime) { return runTestAsync(); } else { return Mono.just(0); } }, 1) .doOnNext(result -> { completedOperations += result; lastCompletionNanoTime = System.nanoTime() - startNanoTime; }) .then(); }
class ApiPerfTestBase<TOptions extends PerfStressOptions> extends PerfTestBase<TOptions> { private final reactor.netty.http.client.HttpClient recordPlaybackHttpClient; private final URI testProxy; private final TestProxyPolicy testProxyPolicy; private String recordingId; private long completedOperations; protected final HttpClient httpClient; protected final Iterable<HttpPipelinePolicy> policies; /** * Creates an instance of the Http Based Performance test. * * @param options the performance test options to use while running the test. * @throws IllegalStateException if an errors is encountered with building ssl context. */ public ApiPerfTestBase(TOptions options) { super(options); httpClient = createHttpClient(options); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { recordPlaybackHttpClient = createRecordPlaybackClient(options); testProxy = options.getTestProxies().get(parallelIndex % options.getTestProxies().size()); testProxyPolicy = new TestProxyPolicy(testProxy); policies = Collections.singletonList(testProxyPolicy); } else { recordPlaybackHttpClient = null; testProxy = null; testProxyPolicy = null; policies = null; } } private static HttpClient createHttpClient(PerfStressOptions options) { PerfStressOptions.HttpClientType httpClientType = options.getHttpClient(); switch (httpClientType) { case NETTY: if (options.isInsecure()) { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); reactor.netty.http.client.HttpClient nettyHttpClient = reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); return new NettyAsyncHttpClientBuilder(nettyHttpClient).build(); } catch (SSLException e) { throw new IllegalStateException(e); } } else { return new NettyAsyncHttpClientProvider().createInstance(); } case OKHTTP: if (options.isInsecure()) { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init( null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), new SecureRandom()); OkHttpClient okHttpClient = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0]) .build(); return new OkHttpAsyncHttpClientBuilder(okHttpClient).build(); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new IllegalStateException(e); } } else { return new OkHttpAsyncClientProvider().createInstance(); } default: throw new IllegalArgumentException("Unsupported http client " + httpClientType); } } private static reactor.netty.http.client.HttpClient createRecordPlaybackClient(PerfStressOptions options) { if (options.isInsecure()) { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); return reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException e) { throw new IllegalStateException(e); } } else { return reactor.netty.http.client.HttpClient.create(); } } /** * Attempts to configure a ClientBuilder using reflection. If a ClientBuilder does not follow the standard * convention, it can be configured manually using the "httpClient" and "policies" fields. * * @param clientBuilder The client builder. * @throws IllegalStateException If reflective access to get httpClient or addPolicy methods fail. */ protected void configureClientBuilder(HttpTrait<?> clientBuilder) { if (httpClient != null) { clientBuilder.httpClient(httpClient); } if (policies != null) { for (HttpPipelinePolicy policy : policies) { clientBuilder.addPolicy(policy); } } } @Override public void runAll(long endNanoTime) { completedOperations = 0; lastCompletionNanoTime = 0; long startNanoTime = System.nanoTime(); while (System.nanoTime() < endNanoTime) { completedOperations += runTest(); lastCompletionNanoTime = System.nanoTime() - startNanoTime; } } @Override /** * Indicates how many operations were completed in a single run of the test. Good to be used for batch operations. * * @return the number of successful operations completed. */ abstract int runTest(); /** * Indicates how many operations were completed in a single run of the async test. Good to be used for batch * operations. * * @return the number of successful operations completed. */ abstract Mono<Integer> runTestAsync(); /** * Stops playback tests. * * @return An empty {@link Mono}. */ public Mono<Void> stopPlaybackAsync() { return recordPlaybackHttpClient .headers(h -> { h.set("x-recording-id", recordingId); h.set("x-purge-inmemory-recording", Boolean.toString(true)); }) .post() .uri(testProxy.resolve("/playback/stop")) .response() .doOnSuccess(response -> { testProxyPolicy.setMode(null); testProxyPolicy.setRecordingId(null); }) .then(); } private Mono<Void> startRecordingAsync() { return Mono.defer(() -> recordPlaybackHttpClient .post() .uri(testProxy.resolve("/record/start")) .response() .doOnNext(response -> { recordingId = response.responseHeaders().get("x-recording-id"); }).then()); } private Mono<Void> stopRecordingAsync() { return Mono.defer(() -> recordPlaybackHttpClient .headers(h -> h.set("x-recording-id", recordingId)) .post() .uri(testProxy.resolve("/record/stop")) .response() .then()); } private Mono<Void> startPlaybackAsync() { return Mono.defer(() -> recordPlaybackHttpClient .headers(h -> h.set("x-recording-id", recordingId)) .post() .uri(testProxy.resolve("/playback/start")) .response() .doOnNext(response -> { recordingId = response.responseHeaders().get("x-recording-id"); }).then()); } /** * Records responses and starts tests in playback mode. * * @return */ @Override Mono<Void> postSetupAsync() { if (testProxyPolicy != null) { return runSyncOrAsync() .then(startRecordingAsync()) .then(Mono.defer(() -> { testProxyPolicy.setRecordingId(recordingId); testProxyPolicy.setMode("record"); return Mono.empty(); })) .then(runSyncOrAsync()) .then(stopRecordingAsync()) .then(startPlaybackAsync()) .then(Mono.defer(() -> { testProxyPolicy.setRecordingId(recordingId); testProxyPolicy.setMode("playback"); return Mono.empty(); })); } return Mono.empty(); } private Mono<Void> runSyncOrAsync() { return Mono.defer(() -> { if (options.isSync()) { return Mono.fromFuture(CompletableFuture.supplyAsync(() -> runTest())).then(); } else { return runTestAsync().then(); } }); } @Override public long getCompletedOperations() { return completedOperations; } }
class ApiPerfTestBase<TOptions extends PerfStressOptions> extends PerfTestBase<TOptions> { private final reactor.netty.http.client.HttpClient recordPlaybackHttpClient; private final URI testProxy; private final TestProxyPolicy testProxyPolicy; private String recordingId; private long completedOperations; protected final HttpClient httpClient; protected final Iterable<HttpPipelinePolicy> policies; /** * Creates an instance of the Http Based Performance test. * * @param options the performance test options to use while running the test. * @throws IllegalStateException if an errors is encountered with building ssl context. */ public ApiPerfTestBase(TOptions options) { super(options); httpClient = createHttpClient(options); if (options.getTestProxies() != null && !options.getTestProxies().isEmpty()) { recordPlaybackHttpClient = createRecordPlaybackClient(options); testProxy = options.getTestProxies().get(parallelIndex % options.getTestProxies().size()); testProxyPolicy = new TestProxyPolicy(testProxy); policies = Collections.singletonList(testProxyPolicy); } else { recordPlaybackHttpClient = null; testProxy = null; testProxyPolicy = null; policies = null; } } private static HttpClient createHttpClient(PerfStressOptions options) { PerfStressOptions.HttpClientType httpClientType = options.getHttpClient(); switch (httpClientType) { case NETTY: if (options.isInsecure()) { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); reactor.netty.http.client.HttpClient nettyHttpClient = reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); return new NettyAsyncHttpClientBuilder(nettyHttpClient).build(); } catch (SSLException e) { throw new IllegalStateException(e); } } else { return new NettyAsyncHttpClientProvider().createInstance(); } case OKHTTP: if (options.isInsecure()) { try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init( null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), new SecureRandom()); OkHttpClient okHttpClient = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0]) .build(); return new OkHttpAsyncHttpClientBuilder(okHttpClient).build(); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new IllegalStateException(e); } } else { return new OkHttpAsyncClientProvider().createInstance(); } default: throw new IllegalArgumentException("Unsupported http client " + httpClientType); } } private static reactor.netty.http.client.HttpClient createRecordPlaybackClient(PerfStressOptions options) { if (options.isInsecure()) { try { SslContext sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); return reactor.netty.http.client.HttpClient.create() .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext)); } catch (SSLException e) { throw new IllegalStateException(e); } } else { return reactor.netty.http.client.HttpClient.create(); } } /** * Attempts to configure a ClientBuilder using reflection. If a ClientBuilder does not follow the standard * convention, it can be configured manually using the "httpClient" and "policies" fields. * * @param clientBuilder The client builder. * @throws IllegalStateException If reflective access to get httpClient or addPolicy methods fail. */ protected void configureClientBuilder(HttpTrait<?> clientBuilder) { if (httpClient != null) { clientBuilder.httpClient(httpClient); } if (policies != null) { for (HttpPipelinePolicy policy : policies) { clientBuilder.addPolicy(policy); } } } @Override public void runAll(long endNanoTime) { completedOperations = 0; lastCompletionNanoTime = 0; long startNanoTime = System.nanoTime(); while (System.nanoTime() < endNanoTime) { completedOperations += runTest(); lastCompletionNanoTime = System.nanoTime() - startNanoTime; } } @Override /** * Indicates how many operations were completed in a single run of the test. Good to be used for batch operations. * * @return the number of successful operations completed. */ abstract int runTest(); /** * Indicates how many operations were completed in a single run of the async test. Good to be used for batch * operations. * * @return the number of successful operations completed. */ abstract Mono<Integer> runTestAsync(); /** * Stops playback tests. * * @return An empty {@link Mono}. */ public Mono<Void> stopPlaybackAsync() { return recordPlaybackHttpClient .headers(h -> { h.set("x-recording-id", recordingId); h.set("x-purge-inmemory-recording", Boolean.toString(true)); }) .post() .uri(testProxy.resolve("/playback/stop")) .response() .doOnSuccess(response -> { testProxyPolicy.setMode(null); testProxyPolicy.setRecordingId(null); }) .then(); } private Mono<Void> startRecordingAsync() { return Mono.defer(() -> recordPlaybackHttpClient .post() .uri(testProxy.resolve("/record/start")) .response() .doOnNext(response -> { recordingId = response.responseHeaders().get("x-recording-id"); }).then()); } private Mono<Void> stopRecordingAsync() { return Mono.defer(() -> recordPlaybackHttpClient .headers(h -> h.set("x-recording-id", recordingId)) .post() .uri(testProxy.resolve("/record/stop")) .response() .then()); } private Mono<Void> startPlaybackAsync() { return Mono.defer(() -> recordPlaybackHttpClient .headers(h -> h.set("x-recording-id", recordingId)) .post() .uri(testProxy.resolve("/playback/start")) .response() .doOnNext(response -> { recordingId = response.responseHeaders().get("x-recording-id"); }).then()); } /** * Records responses and starts tests in playback mode. * * @return */ @Override Mono<Void> postSetupAsync() { if (testProxyPolicy != null) { return runSyncOrAsync() .then(startRecordingAsync()) .then(Mono.defer(() -> { testProxyPolicy.setRecordingId(recordingId); testProxyPolicy.setMode("record"); return Mono.empty(); })) .then(runSyncOrAsync()) .then(stopRecordingAsync()) .then(startPlaybackAsync()) .then(Mono.defer(() -> { testProxyPolicy.setRecordingId(recordingId); testProxyPolicy.setMode("playback"); return Mono.empty(); })); } return Mono.empty(); } private Mono<Void> runSyncOrAsync() { return Mono.defer(() -> { if (options.isSync()) { return Mono.fromFuture(CompletableFuture.supplyAsync(() -> runTest())).then(); } else { return runTestAsync().then(); } }); } @Override public long getCompletedOperations() { return completedOperations; } }
Not related to this PR, but let's begin a list of changes that should be made with Autorest transforms, and this can be the first. `RoleScope` and `KeyVaultRoleScope` are the same class, where `RoleScope` is code generated and `KeyVaultRoleScope` is written by hand. We can use a Swagger transform rename on `RoleScope` to make it `KeyVaultRoleScope` and remove the need for this transformation.
static KeyVaultRoleDefinition roleDefinitionToKeyVaultRoleDefinition(RoleDefinition roleDefinition) { List<KeyVaultPermission> keyVaultPermissions = new ArrayList<>(); for (Permission permission : roleDefinition.getPermissions()) { keyVaultPermissions.add( new KeyVaultPermission(permission.getActions(), permission.getNotActions(), permission.getDataActions().stream() .map(dataAction -> KeyVaultDataAction.fromString(dataAction.toString())) .collect(Collectors.toList()), permission.getNotDataActions().stream() .map(notDataAction -> KeyVaultDataAction.fromString(notDataAction.toString())) .collect(Collectors.toList()))); } return new KeyVaultRoleDefinition(roleDefinition.getId(), roleDefinition.getName(), KeyVaultRoleDefinitionType.fromString(roleDefinition.getType().toString()), roleDefinition.getRoleName(), roleDefinition.getDescription(), KeyVaultRoleType.fromString(roleDefinition.getRoleType().toString()), keyVaultPermissions, roleDefinition.getAssignableScopes().stream() .map(roleScope -> KeyVaultRoleScope.fromString(roleScope.toString())) .collect(Collectors.toList())); }
.map(roleScope -> KeyVaultRoleScope.fromString(roleScope.toString()))
static KeyVaultRoleDefinition roleDefinitionToKeyVaultRoleDefinition(RoleDefinition roleDefinition) { List<KeyVaultPermission> keyVaultPermissions = new ArrayList<>(); for (Permission permission : roleDefinition.getPermissions()) { keyVaultPermissions.add( new KeyVaultPermission(permission.getActions(), permission.getNotActions(), permission.getDataActions().stream() .map(dataAction -> KeyVaultDataAction.fromString(dataAction.toString())) .collect(Collectors.toList()), permission.getNotDataActions().stream() .map(notDataAction -> KeyVaultDataAction.fromString(notDataAction.toString())) .collect(Collectors.toList()))); } return new KeyVaultRoleDefinition(roleDefinition.getId(), roleDefinition.getName(), KeyVaultRoleDefinitionType.fromString(roleDefinition.getType().toString()), roleDefinition.getRoleName(), roleDefinition.getDescription(), KeyVaultRoleType.fromString(roleDefinition.getRoleType().toString()), keyVaultPermissions, roleDefinition.getAssignableScopes().stream() .map(roleScope -> KeyVaultRoleScope.fromString(roleScope.toString())) .collect(Collectors.toList())); }
class of the exception to swallow. * * @return the deserialized response. */ static <E extends HttpResponseException> Response<Void> swallowExceptionForStatusCodeSync(int statusCode, E httpResponseException, ClientLogger logger) { HttpResponse httpResponse = httpResponseException.getResponse(); if (httpResponse.getStatusCode() == statusCode) { return new SimpleResponse<>(httpResponse.getRequest(), httpResponse.getStatusCode(), httpResponse.getHeaders(), null); } throw logger.logExceptionAsError(httpResponseException); }
class of the exception to swallow. * * @return the deserialized response. */ static <E extends HttpResponseException> Response<Void> swallowExceptionForStatusCodeSync(int statusCode, E httpResponseException, ClientLogger logger) { HttpResponse httpResponse = httpResponseException.getResponse(); if (httpResponse.getStatusCode() == statusCode) { return new SimpleResponse<>(httpResponse.getRequest(), httpResponse.getStatusCode(), httpResponse.getHeaders(), null); } throw logger.logExceptionAsError(httpResponseException); }
```suggestion Objects.requireNonNull(logs, "'logs' cannot be null."); ```
private Mono<UploadLogsResult> splitAndUpload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { try { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (logs.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'logs' cannot be empty.")); } ObjectSerializer serializer = DEFAULT_SERIALIZER; int concurrency = 1; if (options != null) { if (options.getObjectSerializer() != null) { serializer = options.getObjectSerializer(); } if (options.getMaxConcurrency() != null) { concurrency = options.getMaxConcurrency(); } } List<List<Object>> logBatches = new ArrayList<>(); List<byte[]> requests = createGzipRequests(logs, serializer, logBatches); RequestOptions requestOptions = new RequestOptions() .addHeader(CONTENT_ENCODING, GZIP) .setContext(context); Iterator<List<Object>> logBatchesIterator = logBatches.iterator(); return Flux.fromIterable(requests) .flatMapSequential(bytes -> uploadToService(ruleId, streamName, requestOptions, bytes), concurrency) .map(responseHolder -> mapResult(logBatchesIterator, responseHolder)) .collectList() .map(this::createResponse); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } }
Objects.requireNonNull(ruleId, "'logs' cannot be null.");
private Mono<UploadLogsResult> splitAndUpload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { try { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(streamName, "'streamName' cannot be null."); Objects.requireNonNull(logs, "'logs' cannot be null."); if (logs.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'logs' cannot be empty.")); } ObjectSerializer serializer = DEFAULT_SERIALIZER; int concurrency = 1; if (options != null) { if (options.getObjectSerializer() != null) { serializer = options.getObjectSerializer(); } if (options.getMaxConcurrency() != null) { concurrency = options.getMaxConcurrency(); } } List<List<Object>> logBatches = new ArrayList<>(); List<byte[]> requests = createGzipRequests(logs, serializer, logBatches); RequestOptions requestOptions = new RequestOptions() .addHeader(CONTENT_ENCODING, GZIP) .setContext(context); Iterator<List<Object>> logBatchesIterator = logBatches.iterator(); return Flux.fromIterable(requests) .flatMapSequential(bytes -> uploadToService(ruleId, streamName, requestOptions, bytes), concurrency) .map(responseHolder -> mapResult(logBatchesIterator, responseHolder)) .collectList() .map(this::createResponse); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } }
class LogsIngestionAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionAsyncClient.class); private static final String CONTENT_ENCODING = "Content-Encoding"; private static final long MAX_REQUEST_PAYLOAD_SIZE = 1024 * 1024; private static final String GZIP = "gzip"; private static final JsonSerializer DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(true); private final IngestionUsingDataCollectionRulesAsyncClient service; LogsIngestionAsyncClient(IngestionUsingDataCollectionRulesAsyncClient service) { this.service = service; } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * <pre> * List&lt;Object&gt; logs = getLogs& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs) { return upload(ruleId, streamName, logs, new UploadLogsOptions()); } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * <pre> * List&lt;Object&gt; logs = getLogs& * UploadLogsOptions uploadLogsOptions = new UploadLogsOptions& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @param options the options to configure the upload request. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options) { return withContext(context -> upload(ruleId, streamName, logs, options, context)); } /** * See error response code and error response message for more detail. * * <p><strong>Header Parameters</strong> * * <table border="1"> * <caption>Header Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>Content-Encoding</td><td>String</td><td>No</td><td>gzip</td></tr> * <tr><td>x-ms-client-request-id</td><td>String</td><td>No</td><td>Client request Id</td></tr> * </table> * * <p><strong>Request Body Schema</strong> * * <pre>{@code * [ * Object * ] * }</pre> * * @param ruleId The immutable Id of the Data Collection Rule resource. * @param streamName The streamDeclaration name as defined in the Data Collection Rule. * @param logs An array of objects matching the schema defined by the provided stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> uploadWithResponse( String ruleId, String streamName, BinaryData logs, RequestOptions requestOptions) { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.addRequestCallback(request -> { HttpHeader httpHeader = request.getHeaders().get(CONTENT_ENCODING); if (httpHeader == null) { BinaryData gzippedRequest = BinaryData.fromBytes(gzipRequest(logs.toBytes())); request.setBody(gzippedRequest); request.setHeader(CONTENT_ENCODING, GZIP); } }); return service.uploadWithResponse(ruleId, streamName, logs, requestOptions); } Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { return Mono.defer(() -> splitAndUpload(ruleId, streamName, logs, options, context)); } private UploadLogsResult mapResult(Iterator<List<Object>> logBatchesIterator, UploadLogsResponseHolder responseHolder) { List<Object> logsBatch = logBatchesIterator.next(); if (responseHolder.getStatus() == UploadLogsStatus.FAILURE) { return new UploadLogsResult(responseHolder.getStatus(), Collections.singletonList(new UploadLogsError(responseHolder.getResponseError(), logsBatch))); } return new UploadLogsResult(UploadLogsStatus.SUCCESS, null); } private Mono<UploadLogsResponseHolder> uploadToService(String ruleId, String streamName, RequestOptions requestOptions, byte[] bytes) { return service.uploadWithResponse(ruleId, streamName, BinaryData.fromBytes(bytes), requestOptions) .map(response -> new UploadLogsResponseHolder(UploadLogsStatus.SUCCESS, null)) .onErrorResume(HttpResponseException.class, ex -> Mono.fromSupplier(() -> new UploadLogsResponseHolder(UploadLogsStatus.FAILURE, mapToResponseError(ex)))); } /** * Method to map the exception to {@link ResponseError}. * @param ex the {@link HttpResponseException}. * @return the mapped {@link ResponseError}. */ private ResponseError mapToResponseError(HttpResponseException ex) { ResponseError responseError = null; if (ex.getValue() instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> errorMap = (LinkedHashMap<String, Object>) ex.getValue(); if (errorMap.containsKey("error")) { Object error = errorMap.get("error"); if (error instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, String> errorDetails = (LinkedHashMap<String, String>) error; if (errorDetails.containsKey("code") && errorDetails.containsKey("message")) { responseError = new ResponseError(errorDetails.get("code"), errorDetails.get("message")); } } } } return responseError; } private UploadLogsResult createResponse(List<UploadLogsResult> results) { int failureCount = 0; List<UploadLogsError> errors = new ArrayList<>(); for (UploadLogsResult result : results) { if (result.getStatus() != UploadLogsStatus.SUCCESS) { failureCount++; errors.addAll(result.getErrors()); } } if (failureCount == 0) { return new UploadLogsResult(UploadLogsStatus.SUCCESS, errors); } if (failureCount < results.size()) { return new UploadLogsResult(UploadLogsStatus.PARTIAL_FAILURE, errors); } return new UploadLogsResult(UploadLogsStatus.FAILURE, errors); } private List<byte[]> createGzipRequests(List<Object> logs, ObjectSerializer serializer, List<List<Object>> logBatches) { try { List<byte[]> requests = new ArrayList<>(); long currentBatchSize = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JsonGenerator generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); List<String> serializedLogs = new ArrayList<>(); int currentBatchStart = 0; for (int i = 0; i < logs.size(); i++) { byte[] bytes = serializer.serializeToBytes(logs.get(i)); int currentLogSize = bytes.length; currentBatchSize += currentLogSize; if (currentBatchSize > MAX_REQUEST_PAYLOAD_SIZE) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); byteArrayOutputStream = new ByteArrayOutputStream(); generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); currentBatchSize = currentLogSize; serializedLogs.clear(); logBatches.add(logs.subList(currentBatchStart, i)); currentBatchStart = i; } serializedLogs.add(new String(bytes, StandardCharsets.UTF_8)); } if (currentBatchSize > 0) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); logBatches.add(logs.subList(currentBatchStart, logs.size())); } return requests; } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } private void writeLogsAndCloseJsonGenerator(JsonGenerator generator, List<String> serializedLogs) throws IOException { generator.writeRaw(serializedLogs.stream() .collect(Collectors.joining(","))); generator.writeEndArray(); generator.close(); } /** * Gzips the input byte array. * @param bytes The input byte array. * @return gzipped byte array. */ private byte[] gzipRequest(byte[] bytes) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (GZIPOutputStream zip = new GZIPOutputStream(byteArrayOutputStream)) { zip.write(bytes); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } return byteArrayOutputStream.toByteArray(); } }
class LogsIngestionAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionAsyncClient.class); private static final String CONTENT_ENCODING = "Content-Encoding"; private static final long MAX_REQUEST_PAYLOAD_SIZE = 1024 * 1024; private static final String GZIP = "gzip"; private static final JsonSerializer DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(true); private final IngestionUsingDataCollectionRulesAsyncClient service; LogsIngestionAsyncClient(IngestionUsingDataCollectionRulesAsyncClient service) { this.service = service; } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * <pre> * List&lt;Object&gt; logs = getLogs& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs) { return upload(ruleId, streamName, logs, new UploadLogsOptions()); } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * <pre> * List&lt;Object&gt; logs = getLogs& * UploadLogsOptions uploadLogsOptions = new UploadLogsOptions& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @param options the options to configure the upload request. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options) { return withContext(context -> upload(ruleId, streamName, logs, options, context)); } /** * See error response code and error response message for more detail. * * <p><strong>Header Parameters</strong> * * <table border="1"> * <caption>Header Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>Content-Encoding</td><td>String</td><td>No</td><td>gzip</td></tr> * <tr><td>x-ms-client-request-id</td><td>String</td><td>No</td><td>Client request Id</td></tr> * </table> * * <p><strong>Request Body Schema</strong> * * <pre>{@code * [ * Object * ] * }</pre> * * @param ruleId The immutable Id of the Data Collection Rule resource. * @param streamName The streamDeclaration name as defined in the Data Collection Rule. * @param logs An array of objects matching the schema defined by the provided stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> uploadWithResponse( String ruleId, String streamName, BinaryData logs, RequestOptions requestOptions) { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.addRequestCallback(request -> { HttpHeader httpHeader = request.getHeaders().get(CONTENT_ENCODING); if (httpHeader == null) { BinaryData gzippedRequest = BinaryData.fromBytes(gzipRequest(logs.toBytes())); request.setBody(gzippedRequest); request.setHeader(CONTENT_ENCODING, GZIP); } }); return service.uploadWithResponse(ruleId, streamName, logs, requestOptions); } Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { return Mono.defer(() -> splitAndUpload(ruleId, streamName, logs, options, context)); } private UploadLogsResult mapResult(Iterator<List<Object>> logBatchesIterator, UploadLogsResponseHolder responseHolder) { List<Object> logsBatch = logBatchesIterator.next(); if (responseHolder.getStatus() == UploadLogsStatus.FAILURE) { return new UploadLogsResult(responseHolder.getStatus(), Collections.singletonList(new UploadLogsError(responseHolder.getResponseError(), logsBatch))); } return new UploadLogsResult(UploadLogsStatus.SUCCESS, null); } private Mono<UploadLogsResponseHolder> uploadToService(String ruleId, String streamName, RequestOptions requestOptions, byte[] bytes) { return service.uploadWithResponse(ruleId, streamName, BinaryData.fromBytes(bytes), requestOptions) .map(response -> new UploadLogsResponseHolder(UploadLogsStatus.SUCCESS, null)) .onErrorResume(HttpResponseException.class, ex -> Mono.fromSupplier(() -> new UploadLogsResponseHolder(UploadLogsStatus.FAILURE, mapToResponseError(ex)))); } /** * Method to map the exception to {@link ResponseError}. * @param ex the {@link HttpResponseException}. * @return the mapped {@link ResponseError}. */ private ResponseError mapToResponseError(HttpResponseException ex) { ResponseError responseError = null; if (ex.getValue() instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> errorMap = (LinkedHashMap<String, Object>) ex.getValue(); if (errorMap.containsKey("error")) { Object error = errorMap.get("error"); if (error instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, String> errorDetails = (LinkedHashMap<String, String>) error; if (errorDetails.containsKey("code") && errorDetails.containsKey("message")) { responseError = new ResponseError(errorDetails.get("code"), errorDetails.get("message")); } } } } return responseError; } private UploadLogsResult createResponse(List<UploadLogsResult> results) { int failureCount = 0; List<UploadLogsError> errors = new ArrayList<>(); for (UploadLogsResult result : results) { if (result.getStatus() != UploadLogsStatus.SUCCESS) { failureCount++; errors.addAll(result.getErrors()); } } if (failureCount == 0) { return new UploadLogsResult(UploadLogsStatus.SUCCESS, errors); } if (failureCount < results.size()) { return new UploadLogsResult(UploadLogsStatus.PARTIAL_FAILURE, errors); } return new UploadLogsResult(UploadLogsStatus.FAILURE, errors); } private List<byte[]> createGzipRequests(List<Object> logs, ObjectSerializer serializer, List<List<Object>> logBatches) { try { List<byte[]> requests = new ArrayList<>(); long currentBatchSize = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JsonGenerator generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); List<String> serializedLogs = new ArrayList<>(); int currentBatchStart = 0; for (int i = 0; i < logs.size(); i++) { byte[] bytes = serializer.serializeToBytes(logs.get(i)); int currentLogSize = bytes.length; currentBatchSize += currentLogSize; if (currentBatchSize > MAX_REQUEST_PAYLOAD_SIZE) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); byteArrayOutputStream = new ByteArrayOutputStream(); generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); currentBatchSize = currentLogSize; serializedLogs.clear(); logBatches.add(logs.subList(currentBatchStart, i)); currentBatchStart = i; } serializedLogs.add(new String(bytes, StandardCharsets.UTF_8)); } if (currentBatchSize > 0) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); logBatches.add(logs.subList(currentBatchStart, logs.size())); } return requests; } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } private void writeLogsAndCloseJsonGenerator(JsonGenerator generator, List<String> serializedLogs) throws IOException { generator.writeRaw(serializedLogs.stream() .collect(Collectors.joining(","))); generator.writeEndArray(); generator.close(); } /** * Gzips the input byte array. * @param bytes The input byte array. * @return gzipped byte array. */ private byte[] gzipRequest(byte[] bytes) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (GZIPOutputStream zip = new GZIPOutputStream(byteArrayOutputStream)) { zip.write(bytes); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } return byteArrayOutputStream.toByteArray(); } }
We should use `subscribe` instead of `block` to actually make this an async sample. We can then add a wait below the async sample with a comment to indicate that wait is required as the async call is non-blocking and the program terminates without it.
public static void main(String[] args) { LogsIngestionAsyncClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient(); List<Object> dataList = getLogs(); try { Mono<UploadLogsResult> resultMono = client.upload("<data-collection-rule-id>", "<stream-name>", dataList); UploadLogsResult result = resultMono.block(TIMEOUT); if (result == null) { throw new RuntimeException(); } System.out.println(result.getStatus()); } catch (RuntimeException runtimeException) { } }
UploadLogsResult result = resultMono.block(TIMEOUT);
public static void main(String[] args) throws InterruptedException { UploadLogsAsyncClientSample sample = new UploadLogsAsyncClientSample(); sample.run(); }
class UploadLogsAsyncClientSample { private static final Duration TIMEOUT = Duration.ofSeconds(10); /** * Main method to run the sample. * @param args ignore args. */ private static List<Object> getLogs() { List<Object> logs = new ArrayList<>(); for (int i = 0; i < 10; i++) { CustomLogData e = new CustomLogData() .setTime(OffsetDateTime.now()) .setExtendedColumn("extend column data" + i); logs.add(e); } return logs; } }
class UploadLogsAsyncClientSample { private static final Duration TIMEOUT = Duration.ofSeconds(10); /** * Main method to run the sample. * @param args ignore args. */ private void run() throws InterruptedException { LogsIngestionAsyncClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient(); CountDownLatch countdownLatch = new CountDownLatch(1); List<Object> dataList = getLogs(); try { Mono<UploadLogsResult> resultMono = client.upload("<data-collection-rule-id>", "<stream-name>", dataList); Disposable subscription = resultMono.subscribe( uploadLogsResult -> { if (uploadLogsResult == null) { throw new RuntimeException(); } System.out.println(uploadLogsResult.getStatus()); }, error -> { throw new RuntimeException("Unexpected error calling upload.", error); }); countdownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); subscription.dispose(); } catch (RuntimeException runtimeException) { } } private static List<Object> getLogs() { List<Object> logs = new ArrayList<>(); for (int i = 0; i < 10; i++) { CustomLogData e = new CustomLogData() .setTime(OffsetDateTime.now()) .setExtendedColumn("extend column data" + i); logs.add(e); } return logs; } }
done
private Mono<UploadLogsResult> splitAndUpload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { try { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (logs.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'logs' cannot be empty.")); } ObjectSerializer serializer = DEFAULT_SERIALIZER; int concurrency = 1; if (options != null) { if (options.getObjectSerializer() != null) { serializer = options.getObjectSerializer(); } if (options.getMaxConcurrency() != null) { concurrency = options.getMaxConcurrency(); } } List<List<Object>> logBatches = new ArrayList<>(); List<byte[]> requests = createGzipRequests(logs, serializer, logBatches); RequestOptions requestOptions = new RequestOptions() .addHeader(CONTENT_ENCODING, GZIP) .setContext(context); Iterator<List<Object>> logBatchesIterator = logBatches.iterator(); return Flux.fromIterable(requests) .flatMapSequential(bytes -> uploadToService(ruleId, streamName, requestOptions, bytes), concurrency) .map(responseHolder -> mapResult(logBatchesIterator, responseHolder)) .collectList() .map(this::createResponse); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } }
Objects.requireNonNull(ruleId, "'streamName' cannot be null.");
private Mono<UploadLogsResult> splitAndUpload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { try { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(streamName, "'streamName' cannot be null."); Objects.requireNonNull(logs, "'logs' cannot be null."); if (logs.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'logs' cannot be empty.")); } ObjectSerializer serializer = DEFAULT_SERIALIZER; int concurrency = 1; if (options != null) { if (options.getObjectSerializer() != null) { serializer = options.getObjectSerializer(); } if (options.getMaxConcurrency() != null) { concurrency = options.getMaxConcurrency(); } } List<List<Object>> logBatches = new ArrayList<>(); List<byte[]> requests = createGzipRequests(logs, serializer, logBatches); RequestOptions requestOptions = new RequestOptions() .addHeader(CONTENT_ENCODING, GZIP) .setContext(context); Iterator<List<Object>> logBatchesIterator = logBatches.iterator(); return Flux.fromIterable(requests) .flatMapSequential(bytes -> uploadToService(ruleId, streamName, requestOptions, bytes), concurrency) .map(responseHolder -> mapResult(logBatchesIterator, responseHolder)) .collectList() .map(this::createResponse); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } }
class LogsIngestionAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionAsyncClient.class); private static final String CONTENT_ENCODING = "Content-Encoding"; private static final long MAX_REQUEST_PAYLOAD_SIZE = 1024 * 1024; private static final String GZIP = "gzip"; private static final JsonSerializer DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(true); private final IngestionUsingDataCollectionRulesAsyncClient service; LogsIngestionAsyncClient(IngestionUsingDataCollectionRulesAsyncClient service) { this.service = service; } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * <pre> * List&lt;Object&gt; logs = getLogs& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs) { return upload(ruleId, streamName, logs, new UploadLogsOptions()); } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * <pre> * List&lt;Object&gt; logs = getLogs& * UploadLogsOptions uploadLogsOptions = new UploadLogsOptions& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @param options the options to configure the upload request. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options) { return withContext(context -> upload(ruleId, streamName, logs, options, context)); } /** * See error response code and error response message for more detail. * * <p><strong>Header Parameters</strong> * * <table border="1"> * <caption>Header Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>Content-Encoding</td><td>String</td><td>No</td><td>gzip</td></tr> * <tr><td>x-ms-client-request-id</td><td>String</td><td>No</td><td>Client request Id</td></tr> * </table> * * <p><strong>Request Body Schema</strong> * * <pre>{@code * [ * Object * ] * }</pre> * * @param ruleId The immutable Id of the Data Collection Rule resource. * @param streamName The streamDeclaration name as defined in the Data Collection Rule. * @param logs An array of objects matching the schema defined by the provided stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> uploadWithResponse( String ruleId, String streamName, BinaryData logs, RequestOptions requestOptions) { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.addRequestCallback(request -> { HttpHeader httpHeader = request.getHeaders().get(CONTENT_ENCODING); if (httpHeader == null) { BinaryData gzippedRequest = BinaryData.fromBytes(gzipRequest(logs.toBytes())); request.setBody(gzippedRequest); request.setHeader(CONTENT_ENCODING, GZIP); } }); return service.uploadWithResponse(ruleId, streamName, logs, requestOptions); } Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { return Mono.defer(() -> splitAndUpload(ruleId, streamName, logs, options, context)); } private UploadLogsResult mapResult(Iterator<List<Object>> logBatchesIterator, UploadLogsResponseHolder responseHolder) { List<Object> logsBatch = logBatchesIterator.next(); if (responseHolder.getStatus() == UploadLogsStatus.FAILURE) { return new UploadLogsResult(responseHolder.getStatus(), Collections.singletonList(new UploadLogsError(responseHolder.getResponseError(), logsBatch))); } return new UploadLogsResult(UploadLogsStatus.SUCCESS, null); } private Mono<UploadLogsResponseHolder> uploadToService(String ruleId, String streamName, RequestOptions requestOptions, byte[] bytes) { return service.uploadWithResponse(ruleId, streamName, BinaryData.fromBytes(bytes), requestOptions) .map(response -> new UploadLogsResponseHolder(UploadLogsStatus.SUCCESS, null)) .onErrorResume(HttpResponseException.class, ex -> Mono.fromSupplier(() -> new UploadLogsResponseHolder(UploadLogsStatus.FAILURE, mapToResponseError(ex)))); } /** * Method to map the exception to {@link ResponseError}. * @param ex the {@link HttpResponseException}. * @return the mapped {@link ResponseError}. */ private ResponseError mapToResponseError(HttpResponseException ex) { ResponseError responseError = null; if (ex.getValue() instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> errorMap = (LinkedHashMap<String, Object>) ex.getValue(); if (errorMap.containsKey("error")) { Object error = errorMap.get("error"); if (error instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, String> errorDetails = (LinkedHashMap<String, String>) error; if (errorDetails.containsKey("code") && errorDetails.containsKey("message")) { responseError = new ResponseError(errorDetails.get("code"), errorDetails.get("message")); } } } } return responseError; } private UploadLogsResult createResponse(List<UploadLogsResult> results) { int failureCount = 0; List<UploadLogsError> errors = new ArrayList<>(); for (UploadLogsResult result : results) { if (result.getStatus() != UploadLogsStatus.SUCCESS) { failureCount++; errors.addAll(result.getErrors()); } } if (failureCount == 0) { return new UploadLogsResult(UploadLogsStatus.SUCCESS, errors); } if (failureCount < results.size()) { return new UploadLogsResult(UploadLogsStatus.PARTIAL_FAILURE, errors); } return new UploadLogsResult(UploadLogsStatus.FAILURE, errors); } private List<byte[]> createGzipRequests(List<Object> logs, ObjectSerializer serializer, List<List<Object>> logBatches) { try { List<byte[]> requests = new ArrayList<>(); long currentBatchSize = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JsonGenerator generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); List<String> serializedLogs = new ArrayList<>(); int currentBatchStart = 0; for (int i = 0; i < logs.size(); i++) { byte[] bytes = serializer.serializeToBytes(logs.get(i)); int currentLogSize = bytes.length; currentBatchSize += currentLogSize; if (currentBatchSize > MAX_REQUEST_PAYLOAD_SIZE) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); byteArrayOutputStream = new ByteArrayOutputStream(); generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); currentBatchSize = currentLogSize; serializedLogs.clear(); logBatches.add(logs.subList(currentBatchStart, i)); currentBatchStart = i; } serializedLogs.add(new String(bytes, StandardCharsets.UTF_8)); } if (currentBatchSize > 0) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); logBatches.add(logs.subList(currentBatchStart, logs.size())); } return requests; } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } private void writeLogsAndCloseJsonGenerator(JsonGenerator generator, List<String> serializedLogs) throws IOException { generator.writeRaw(serializedLogs.stream() .collect(Collectors.joining(","))); generator.writeEndArray(); generator.close(); } /** * Gzips the input byte array. * @param bytes The input byte array. * @return gzipped byte array. */ private byte[] gzipRequest(byte[] bytes) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (GZIPOutputStream zip = new GZIPOutputStream(byteArrayOutputStream)) { zip.write(bytes); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } return byteArrayOutputStream.toByteArray(); } }
class LogsIngestionAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionAsyncClient.class); private static final String CONTENT_ENCODING = "Content-Encoding"; private static final long MAX_REQUEST_PAYLOAD_SIZE = 1024 * 1024; private static final String GZIP = "gzip"; private static final JsonSerializer DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(true); private final IngestionUsingDataCollectionRulesAsyncClient service; LogsIngestionAsyncClient(IngestionUsingDataCollectionRulesAsyncClient service) { this.service = service; } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * <pre> * List&lt;Object&gt; logs = getLogs& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs) { return upload(ruleId, streamName, logs, new UploadLogsOptions()); } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * <pre> * List&lt;Object&gt; logs = getLogs& * UploadLogsOptions uploadLogsOptions = new UploadLogsOptions& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @param options the options to configure the upload request. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options) { return withContext(context -> upload(ruleId, streamName, logs, options, context)); } /** * See error response code and error response message for more detail. * * <p><strong>Header Parameters</strong> * * <table border="1"> * <caption>Header Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>Content-Encoding</td><td>String</td><td>No</td><td>gzip</td></tr> * <tr><td>x-ms-client-request-id</td><td>String</td><td>No</td><td>Client request Id</td></tr> * </table> * * <p><strong>Request Body Schema</strong> * * <pre>{@code * [ * Object * ] * }</pre> * * @param ruleId The immutable Id of the Data Collection Rule resource. * @param streamName The streamDeclaration name as defined in the Data Collection Rule. * @param logs An array of objects matching the schema defined by the provided stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> uploadWithResponse( String ruleId, String streamName, BinaryData logs, RequestOptions requestOptions) { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.addRequestCallback(request -> { HttpHeader httpHeader = request.getHeaders().get(CONTENT_ENCODING); if (httpHeader == null) { BinaryData gzippedRequest = BinaryData.fromBytes(gzipRequest(logs.toBytes())); request.setBody(gzippedRequest); request.setHeader(CONTENT_ENCODING, GZIP); } }); return service.uploadWithResponse(ruleId, streamName, logs, requestOptions); } Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { return Mono.defer(() -> splitAndUpload(ruleId, streamName, logs, options, context)); } private UploadLogsResult mapResult(Iterator<List<Object>> logBatchesIterator, UploadLogsResponseHolder responseHolder) { List<Object> logsBatch = logBatchesIterator.next(); if (responseHolder.getStatus() == UploadLogsStatus.FAILURE) { return new UploadLogsResult(responseHolder.getStatus(), Collections.singletonList(new UploadLogsError(responseHolder.getResponseError(), logsBatch))); } return new UploadLogsResult(UploadLogsStatus.SUCCESS, null); } private Mono<UploadLogsResponseHolder> uploadToService(String ruleId, String streamName, RequestOptions requestOptions, byte[] bytes) { return service.uploadWithResponse(ruleId, streamName, BinaryData.fromBytes(bytes), requestOptions) .map(response -> new UploadLogsResponseHolder(UploadLogsStatus.SUCCESS, null)) .onErrorResume(HttpResponseException.class, ex -> Mono.fromSupplier(() -> new UploadLogsResponseHolder(UploadLogsStatus.FAILURE, mapToResponseError(ex)))); } /** * Method to map the exception to {@link ResponseError}. * @param ex the {@link HttpResponseException}. * @return the mapped {@link ResponseError}. */ private ResponseError mapToResponseError(HttpResponseException ex) { ResponseError responseError = null; if (ex.getValue() instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> errorMap = (LinkedHashMap<String, Object>) ex.getValue(); if (errorMap.containsKey("error")) { Object error = errorMap.get("error"); if (error instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, String> errorDetails = (LinkedHashMap<String, String>) error; if (errorDetails.containsKey("code") && errorDetails.containsKey("message")) { responseError = new ResponseError(errorDetails.get("code"), errorDetails.get("message")); } } } } return responseError; } private UploadLogsResult createResponse(List<UploadLogsResult> results) { int failureCount = 0; List<UploadLogsError> errors = new ArrayList<>(); for (UploadLogsResult result : results) { if (result.getStatus() != UploadLogsStatus.SUCCESS) { failureCount++; errors.addAll(result.getErrors()); } } if (failureCount == 0) { return new UploadLogsResult(UploadLogsStatus.SUCCESS, errors); } if (failureCount < results.size()) { return new UploadLogsResult(UploadLogsStatus.PARTIAL_FAILURE, errors); } return new UploadLogsResult(UploadLogsStatus.FAILURE, errors); } private List<byte[]> createGzipRequests(List<Object> logs, ObjectSerializer serializer, List<List<Object>> logBatches) { try { List<byte[]> requests = new ArrayList<>(); long currentBatchSize = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JsonGenerator generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); List<String> serializedLogs = new ArrayList<>(); int currentBatchStart = 0; for (int i = 0; i < logs.size(); i++) { byte[] bytes = serializer.serializeToBytes(logs.get(i)); int currentLogSize = bytes.length; currentBatchSize += currentLogSize; if (currentBatchSize > MAX_REQUEST_PAYLOAD_SIZE) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); byteArrayOutputStream = new ByteArrayOutputStream(); generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); currentBatchSize = currentLogSize; serializedLogs.clear(); logBatches.add(logs.subList(currentBatchStart, i)); currentBatchStart = i; } serializedLogs.add(new String(bytes, StandardCharsets.UTF_8)); } if (currentBatchSize > 0) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); logBatches.add(logs.subList(currentBatchStart, logs.size())); } return requests; } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } private void writeLogsAndCloseJsonGenerator(JsonGenerator generator, List<String> serializedLogs) throws IOException { generator.writeRaw(serializedLogs.stream() .collect(Collectors.joining(","))); generator.writeEndArray(); generator.close(); } /** * Gzips the input byte array. * @param bytes The input byte array. * @return gzipped byte array. */ private byte[] gzipRequest(byte[] bytes) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (GZIPOutputStream zip = new GZIPOutputStream(byteArrayOutputStream)) { zip.write(bytes); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } return byteArrayOutputStream.toByteArray(); } }
done
private Mono<UploadLogsResult> splitAndUpload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { try { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (logs.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'logs' cannot be empty.")); } ObjectSerializer serializer = DEFAULT_SERIALIZER; int concurrency = 1; if (options != null) { if (options.getObjectSerializer() != null) { serializer = options.getObjectSerializer(); } if (options.getMaxConcurrency() != null) { concurrency = options.getMaxConcurrency(); } } List<List<Object>> logBatches = new ArrayList<>(); List<byte[]> requests = createGzipRequests(logs, serializer, logBatches); RequestOptions requestOptions = new RequestOptions() .addHeader(CONTENT_ENCODING, GZIP) .setContext(context); Iterator<List<Object>> logBatchesIterator = logBatches.iterator(); return Flux.fromIterable(requests) .flatMapSequential(bytes -> uploadToService(ruleId, streamName, requestOptions, bytes), concurrency) .map(responseHolder -> mapResult(logBatchesIterator, responseHolder)) .collectList() .map(this::createResponse); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } }
Objects.requireNonNull(ruleId, "'logs' cannot be null.");
private Mono<UploadLogsResult> splitAndUpload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { try { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(streamName, "'streamName' cannot be null."); Objects.requireNonNull(logs, "'logs' cannot be null."); if (logs.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'logs' cannot be empty.")); } ObjectSerializer serializer = DEFAULT_SERIALIZER; int concurrency = 1; if (options != null) { if (options.getObjectSerializer() != null) { serializer = options.getObjectSerializer(); } if (options.getMaxConcurrency() != null) { concurrency = options.getMaxConcurrency(); } } List<List<Object>> logBatches = new ArrayList<>(); List<byte[]> requests = createGzipRequests(logs, serializer, logBatches); RequestOptions requestOptions = new RequestOptions() .addHeader(CONTENT_ENCODING, GZIP) .setContext(context); Iterator<List<Object>> logBatchesIterator = logBatches.iterator(); return Flux.fromIterable(requests) .flatMapSequential(bytes -> uploadToService(ruleId, streamName, requestOptions, bytes), concurrency) .map(responseHolder -> mapResult(logBatchesIterator, responseHolder)) .collectList() .map(this::createResponse); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } }
class LogsIngestionAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionAsyncClient.class); private static final String CONTENT_ENCODING = "Content-Encoding"; private static final long MAX_REQUEST_PAYLOAD_SIZE = 1024 * 1024; private static final String GZIP = "gzip"; private static final JsonSerializer DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(true); private final IngestionUsingDataCollectionRulesAsyncClient service; LogsIngestionAsyncClient(IngestionUsingDataCollectionRulesAsyncClient service) { this.service = service; } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * <pre> * List&lt;Object&gt; logs = getLogs& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs) { return upload(ruleId, streamName, logs, new UploadLogsOptions()); } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * <pre> * List&lt;Object&gt; logs = getLogs& * UploadLogsOptions uploadLogsOptions = new UploadLogsOptions& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @param options the options to configure the upload request. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options) { return withContext(context -> upload(ruleId, streamName, logs, options, context)); } /** * See error response code and error response message for more detail. * * <p><strong>Header Parameters</strong> * * <table border="1"> * <caption>Header Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>Content-Encoding</td><td>String</td><td>No</td><td>gzip</td></tr> * <tr><td>x-ms-client-request-id</td><td>String</td><td>No</td><td>Client request Id</td></tr> * </table> * * <p><strong>Request Body Schema</strong> * * <pre>{@code * [ * Object * ] * }</pre> * * @param ruleId The immutable Id of the Data Collection Rule resource. * @param streamName The streamDeclaration name as defined in the Data Collection Rule. * @param logs An array of objects matching the schema defined by the provided stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> uploadWithResponse( String ruleId, String streamName, BinaryData logs, RequestOptions requestOptions) { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.addRequestCallback(request -> { HttpHeader httpHeader = request.getHeaders().get(CONTENT_ENCODING); if (httpHeader == null) { BinaryData gzippedRequest = BinaryData.fromBytes(gzipRequest(logs.toBytes())); request.setBody(gzippedRequest); request.setHeader(CONTENT_ENCODING, GZIP); } }); return service.uploadWithResponse(ruleId, streamName, logs, requestOptions); } Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { return Mono.defer(() -> splitAndUpload(ruleId, streamName, logs, options, context)); } private UploadLogsResult mapResult(Iterator<List<Object>> logBatchesIterator, UploadLogsResponseHolder responseHolder) { List<Object> logsBatch = logBatchesIterator.next(); if (responseHolder.getStatus() == UploadLogsStatus.FAILURE) { return new UploadLogsResult(responseHolder.getStatus(), Collections.singletonList(new UploadLogsError(responseHolder.getResponseError(), logsBatch))); } return new UploadLogsResult(UploadLogsStatus.SUCCESS, null); } private Mono<UploadLogsResponseHolder> uploadToService(String ruleId, String streamName, RequestOptions requestOptions, byte[] bytes) { return service.uploadWithResponse(ruleId, streamName, BinaryData.fromBytes(bytes), requestOptions) .map(response -> new UploadLogsResponseHolder(UploadLogsStatus.SUCCESS, null)) .onErrorResume(HttpResponseException.class, ex -> Mono.fromSupplier(() -> new UploadLogsResponseHolder(UploadLogsStatus.FAILURE, mapToResponseError(ex)))); } /** * Method to map the exception to {@link ResponseError}. * @param ex the {@link HttpResponseException}. * @return the mapped {@link ResponseError}. */ private ResponseError mapToResponseError(HttpResponseException ex) { ResponseError responseError = null; if (ex.getValue() instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> errorMap = (LinkedHashMap<String, Object>) ex.getValue(); if (errorMap.containsKey("error")) { Object error = errorMap.get("error"); if (error instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, String> errorDetails = (LinkedHashMap<String, String>) error; if (errorDetails.containsKey("code") && errorDetails.containsKey("message")) { responseError = new ResponseError(errorDetails.get("code"), errorDetails.get("message")); } } } } return responseError; } private UploadLogsResult createResponse(List<UploadLogsResult> results) { int failureCount = 0; List<UploadLogsError> errors = new ArrayList<>(); for (UploadLogsResult result : results) { if (result.getStatus() != UploadLogsStatus.SUCCESS) { failureCount++; errors.addAll(result.getErrors()); } } if (failureCount == 0) { return new UploadLogsResult(UploadLogsStatus.SUCCESS, errors); } if (failureCount < results.size()) { return new UploadLogsResult(UploadLogsStatus.PARTIAL_FAILURE, errors); } return new UploadLogsResult(UploadLogsStatus.FAILURE, errors); } private List<byte[]> createGzipRequests(List<Object> logs, ObjectSerializer serializer, List<List<Object>> logBatches) { try { List<byte[]> requests = new ArrayList<>(); long currentBatchSize = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JsonGenerator generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); List<String> serializedLogs = new ArrayList<>(); int currentBatchStart = 0; for (int i = 0; i < logs.size(); i++) { byte[] bytes = serializer.serializeToBytes(logs.get(i)); int currentLogSize = bytes.length; currentBatchSize += currentLogSize; if (currentBatchSize > MAX_REQUEST_PAYLOAD_SIZE) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); byteArrayOutputStream = new ByteArrayOutputStream(); generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); currentBatchSize = currentLogSize; serializedLogs.clear(); logBatches.add(logs.subList(currentBatchStart, i)); currentBatchStart = i; } serializedLogs.add(new String(bytes, StandardCharsets.UTF_8)); } if (currentBatchSize > 0) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); logBatches.add(logs.subList(currentBatchStart, logs.size())); } return requests; } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } private void writeLogsAndCloseJsonGenerator(JsonGenerator generator, List<String> serializedLogs) throws IOException { generator.writeRaw(serializedLogs.stream() .collect(Collectors.joining(","))); generator.writeEndArray(); generator.close(); } /** * Gzips the input byte array. * @param bytes The input byte array. * @return gzipped byte array. */ private byte[] gzipRequest(byte[] bytes) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (GZIPOutputStream zip = new GZIPOutputStream(byteArrayOutputStream)) { zip.write(bytes); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } return byteArrayOutputStream.toByteArray(); } }
class LogsIngestionAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(LogsIngestionAsyncClient.class); private static final String CONTENT_ENCODING = "Content-Encoding"; private static final long MAX_REQUEST_PAYLOAD_SIZE = 1024 * 1024; private static final String GZIP = "gzip"; private static final JsonSerializer DEFAULT_SERIALIZER = JsonSerializerProviders.createInstance(true); private final IngestionUsingDataCollectionRulesAsyncClient service; LogsIngestionAsyncClient(IngestionUsingDataCollectionRulesAsyncClient service) { this.service = service; } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * <pre> * List&lt;Object&gt; logs = getLogs& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.upload --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs) { return upload(ruleId, streamName, logs, new UploadLogsOptions()); } /** * Uploads logs to Azure Monitor with specified data collection rule id and stream name. The input logs may be * too large to be sent as a single request to the Azure Monitor service. In such cases, this method will split * the input logs into multiple smaller requests before sending to the service. * * <p><strong>Upload logs to Azure Monitor</strong></p> * <!-- src_embed com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * <pre> * List&lt;Object&gt; logs = getLogs& * UploadLogsOptions uploadLogsOptions = new UploadLogsOptions& * logsIngestionAsyncClient.upload& * .subscribe& * </pre> * <!-- end com.azure.monitor.ingestion.LogsIngestionAsyncClient.uploadWithConcurrency --> * * @param ruleId the data collection rule id that is configured to collect and transform the logs. * @param streamName the stream name configured in data collection rule that matches defines the structure of the * logs sent in this request. * @param logs the collection of logs to be uploaded. * @param options the options to configure the upload request. * @return the result of the logs upload request. * @throws NullPointerException if any of {@code ruleId}, {@code streamName} or {@code logs} are null. * @throws IllegalArgumentException if {@code logs} is empty. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options) { return withContext(context -> upload(ruleId, streamName, logs, options, context)); } /** * See error response code and error response message for more detail. * * <p><strong>Header Parameters</strong> * * <table border="1"> * <caption>Header Parameters</caption> * <tr><th>Name</th><th>Type</th><th>Required</th><th>Description</th></tr> * <tr><td>Content-Encoding</td><td>String</td><td>No</td><td>gzip</td></tr> * <tr><td>x-ms-client-request-id</td><td>String</td><td>No</td><td>Client request Id</td></tr> * </table> * * <p><strong>Request Body Schema</strong> * * <pre>{@code * [ * Object * ] * }</pre> * * @param ruleId The immutable Id of the Data Collection Rule resource. * @param streamName The streamDeclaration name as defined in the Data Collection Rule. * @param logs An array of objects matching the schema defined by the provided stream. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> uploadWithResponse( String ruleId, String streamName, BinaryData logs, RequestOptions requestOptions) { Objects.requireNonNull(ruleId, "'ruleId' cannot be null."); Objects.requireNonNull(ruleId, "'streamName' cannot be null."); Objects.requireNonNull(ruleId, "'logs' cannot be null."); if (requestOptions == null) { requestOptions = new RequestOptions(); } requestOptions.addRequestCallback(request -> { HttpHeader httpHeader = request.getHeaders().get(CONTENT_ENCODING); if (httpHeader == null) { BinaryData gzippedRequest = BinaryData.fromBytes(gzipRequest(logs.toBytes())); request.setBody(gzippedRequest); request.setHeader(CONTENT_ENCODING, GZIP); } }); return service.uploadWithResponse(ruleId, streamName, logs, requestOptions); } Mono<UploadLogsResult> upload(String ruleId, String streamName, List<Object> logs, UploadLogsOptions options, Context context) { return Mono.defer(() -> splitAndUpload(ruleId, streamName, logs, options, context)); } private UploadLogsResult mapResult(Iterator<List<Object>> logBatchesIterator, UploadLogsResponseHolder responseHolder) { List<Object> logsBatch = logBatchesIterator.next(); if (responseHolder.getStatus() == UploadLogsStatus.FAILURE) { return new UploadLogsResult(responseHolder.getStatus(), Collections.singletonList(new UploadLogsError(responseHolder.getResponseError(), logsBatch))); } return new UploadLogsResult(UploadLogsStatus.SUCCESS, null); } private Mono<UploadLogsResponseHolder> uploadToService(String ruleId, String streamName, RequestOptions requestOptions, byte[] bytes) { return service.uploadWithResponse(ruleId, streamName, BinaryData.fromBytes(bytes), requestOptions) .map(response -> new UploadLogsResponseHolder(UploadLogsStatus.SUCCESS, null)) .onErrorResume(HttpResponseException.class, ex -> Mono.fromSupplier(() -> new UploadLogsResponseHolder(UploadLogsStatus.FAILURE, mapToResponseError(ex)))); } /** * Method to map the exception to {@link ResponseError}. * @param ex the {@link HttpResponseException}. * @return the mapped {@link ResponseError}. */ private ResponseError mapToResponseError(HttpResponseException ex) { ResponseError responseError = null; if (ex.getValue() instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> errorMap = (LinkedHashMap<String, Object>) ex.getValue(); if (errorMap.containsKey("error")) { Object error = errorMap.get("error"); if (error instanceof LinkedHashMap<?, ?>) { @SuppressWarnings("unchecked") LinkedHashMap<String, String> errorDetails = (LinkedHashMap<String, String>) error; if (errorDetails.containsKey("code") && errorDetails.containsKey("message")) { responseError = new ResponseError(errorDetails.get("code"), errorDetails.get("message")); } } } } return responseError; } private UploadLogsResult createResponse(List<UploadLogsResult> results) { int failureCount = 0; List<UploadLogsError> errors = new ArrayList<>(); for (UploadLogsResult result : results) { if (result.getStatus() != UploadLogsStatus.SUCCESS) { failureCount++; errors.addAll(result.getErrors()); } } if (failureCount == 0) { return new UploadLogsResult(UploadLogsStatus.SUCCESS, errors); } if (failureCount < results.size()) { return new UploadLogsResult(UploadLogsStatus.PARTIAL_FAILURE, errors); } return new UploadLogsResult(UploadLogsStatus.FAILURE, errors); } private List<byte[]> createGzipRequests(List<Object> logs, ObjectSerializer serializer, List<List<Object>> logBatches) { try { List<byte[]> requests = new ArrayList<>(); long currentBatchSize = 0; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JsonGenerator generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); List<String> serializedLogs = new ArrayList<>(); int currentBatchStart = 0; for (int i = 0; i < logs.size(); i++) { byte[] bytes = serializer.serializeToBytes(logs.get(i)); int currentLogSize = bytes.length; currentBatchSize += currentLogSize; if (currentBatchSize > MAX_REQUEST_PAYLOAD_SIZE) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); byteArrayOutputStream = new ByteArrayOutputStream(); generator = JsonFactory.builder().build().createGenerator(byteArrayOutputStream); generator.writeStartArray(); currentBatchSize = currentLogSize; serializedLogs.clear(); logBatches.add(logs.subList(currentBatchStart, i)); currentBatchStart = i; } serializedLogs.add(new String(bytes, StandardCharsets.UTF_8)); } if (currentBatchSize > 0) { writeLogsAndCloseJsonGenerator(generator, serializedLogs); requests.add(gzipRequest(byteArrayOutputStream.toByteArray())); logBatches.add(logs.subList(currentBatchStart, logs.size())); } return requests; } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } private void writeLogsAndCloseJsonGenerator(JsonGenerator generator, List<String> serializedLogs) throws IOException { generator.writeRaw(serializedLogs.stream() .collect(Collectors.joining(","))); generator.writeEndArray(); generator.close(); } /** * Gzips the input byte array. * @param bytes The input byte array. * @return gzipped byte array. */ private byte[] gzipRequest(byte[] bytes) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (GZIPOutputStream zip = new GZIPOutputStream(byteArrayOutputStream)) { zip.write(bytes); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } return byteArrayOutputStream.toByteArray(); } }
I just wanted to keep it simple by using block. But yes we can make it a more generic async sample. I have changed it to using subscribe instead
public static void main(String[] args) { LogsIngestionAsyncClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient(); List<Object> dataList = getLogs(); try { Mono<UploadLogsResult> resultMono = client.upload("<data-collection-rule-id>", "<stream-name>", dataList); UploadLogsResult result = resultMono.block(TIMEOUT); if (result == null) { throw new RuntimeException(); } System.out.println(result.getStatus()); } catch (RuntimeException runtimeException) { } }
UploadLogsResult result = resultMono.block(TIMEOUT);
public static void main(String[] args) throws InterruptedException { UploadLogsAsyncClientSample sample = new UploadLogsAsyncClientSample(); sample.run(); }
class UploadLogsAsyncClientSample { private static final Duration TIMEOUT = Duration.ofSeconds(10); /** * Main method to run the sample. * @param args ignore args. */ private static List<Object> getLogs() { List<Object> logs = new ArrayList<>(); for (int i = 0; i < 10; i++) { CustomLogData e = new CustomLogData() .setTime(OffsetDateTime.now()) .setExtendedColumn("extend column data" + i); logs.add(e); } return logs; } }
class UploadLogsAsyncClientSample { private static final Duration TIMEOUT = Duration.ofSeconds(10); /** * Main method to run the sample. * @param args ignore args. */ private void run() throws InterruptedException { LogsIngestionAsyncClient client = new LogsIngestionClientBuilder() .endpoint("<data-collection-endpoint>") .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient(); CountDownLatch countdownLatch = new CountDownLatch(1); List<Object> dataList = getLogs(); try { Mono<UploadLogsResult> resultMono = client.upload("<data-collection-rule-id>", "<stream-name>", dataList); Disposable subscription = resultMono.subscribe( uploadLogsResult -> { if (uploadLogsResult == null) { throw new RuntimeException(); } System.out.println(uploadLogsResult.getStatus()); }, error -> { throw new RuntimeException("Unexpected error calling upload.", error); }); countdownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS); subscription.dispose(); } catch (RuntimeException runtimeException) { } } private static List<Object> getLogs() { List<Object> logs = new ArrayList<>(); for (int i = 0; i < 10; i++) { CustomLogData e = new CustomLogData() .setTime(OffsetDateTime.now()) .setExtendedColumn("extend column data" + i); logs.add(e); } return logs; } }
can it be "MANAGED_IDENTITY_ENABLED=true"?
void testBindAzureGlobalProperties() { getContextRunnerWithEventHubsURL() .withPropertyValues( "spring.cloud.azure.credential.managed-identity-enabled=true" ) .run(context -> { AzureGlobalProperties azureGlobalProperties = context.getBean(AzureGlobalProperties.class); assertTrue(azureGlobalProperties.getCredential().isManagedIdentityEnabled()); P kafkaSpringProperties = getKafkaSpringProperties(context); assertConsumerPropsConfigured(kafkaSpringProperties, MANAGED_IDENTITY_ENABLED, MANAGED_IDENTITY_ENABLED + "=\"true\""); assertProducerPropsConfigured(kafkaSpringProperties, MANAGED_IDENTITY_ENABLED, MANAGED_IDENTITY_ENABLED + "=\"true\""); assertAdminPropsConfigured(kafkaSpringProperties, MANAGED_IDENTITY_ENABLED, MANAGED_IDENTITY_ENABLED + "=\"true\""); }); }
assertConsumerPropsConfigured(kafkaSpringProperties, MANAGED_IDENTITY_ENABLED, MANAGED_IDENTITY_ENABLED + "=\"true\"");
void testBindAzureGlobalProperties() { getContextRunnerWithEventHubsURL() .withPropertyValues( "spring.cloud.azure.credential.managed-identity-enabled=true" ) .run(context -> { AzureGlobalProperties azureGlobalProperties = context.getBean(AzureGlobalProperties.class); assertTrue(azureGlobalProperties.getCredential().isManagedIdentityEnabled()); P kafkaSpringProperties = getKafkaSpringProperties(context); Map<String, Object> mergedConsumerProperties = processor.getMergedConsumerProperties(kafkaSpringProperties); assertOAuthPropertiesConfigure(mergedConsumerProperties); assertPropertyRemoved(mergedConsumerProperties, "azure.credential.managed-identity-enabled"); assertJaasPropertiesConfigured(mergedConsumerProperties, "azure.credential.managed-identity-enabled", "true"); Map<String, Object> mergedProducerProperties = processor.getMergedProducerProperties(kafkaSpringProperties); assertOAuthPropertiesConfigure(mergedProducerProperties); assertPropertyRemoved(mergedProducerProperties, "azure.credential.managed-identity-enabled"); assertJaasPropertiesConfigured(mergedProducerProperties, "azure.credential.managed-identity-enabled", "true"); Map<String, Object> mergedAdminProperties = processor.getMergedAdminProperties(kafkaSpringProperties); assertOAuthPropertiesConfigure(mergedAdminProperties); assertPropertyRemoved(mergedAdminProperties, "azure.credential.managed-identity-enabled"); assertJaasPropertiesConfigured(mergedAdminProperties, "azure.credential.managed-identity-enabled", "true"); }); }
class AbstractAzureKafkaOAuth2AutoConfigurationTests<P, B> { protected static final String SPRING_BOOT_KAFKA_PROPERTIES_PREFIX = "spring.kafka.properties."; protected static final String SPRING_BOOT_KAFKA_PRODUCER_PROPERTIES_PREFIX = "spring.kafka.producer.properties."; protected static final String CLIENT_ID = "azure.credential.client-id"; protected static final String MANAGED_IDENTITY_ENABLED = "azure.credential.managed-identity-enabled"; protected abstract ApplicationContextRunner getContextRunnerWithEventHubsURL(); protected abstract ApplicationContextRunner getContextRunnerWithoutEventHubsURL(); protected abstract P getKafkaSpringProperties(ApplicationContext context); protected final B processor; AbstractAzureKafkaOAuth2AutoConfigurationTests(B processor) { this.processor = processor; } @Test @Test void testNotBindSpringBootKafkaProperties() { getContextRunnerWithoutEventHubsURL() .withPropertyValues( SPRING_BOOT_KAFKA_PROPERTIES_PREFIX + MANAGED_IDENTITY_ENABLED + "=true" ) .run(context -> { AzureGlobalProperties azureGlobalProperties = context.getBean(AzureGlobalProperties.class); assertFalse(azureGlobalProperties.getCredential().isManagedIdentityEnabled()); P kafkaSpringProperties = getKafkaSpringProperties(context); Map<String, Object> consumerProperties = getConsumerProperties(kafkaSpringProperties); assertFalse(consumerProperties.containsKey(MANAGED_IDENTITY_ENABLED)); String adminJaasProperties = getAdminJaasProperties(kafkaSpringProperties); assertNull(adminJaasProperties); }); } protected Map<String, Object> getProducerProperties(P properties) { return ReflectionTestUtils.invokeMethod(processor, "getMergedProducerProperties", properties); } protected Map<String, Object> getConsumerProperties(P properties) { return ReflectionTestUtils.invokeMethod(processor, "getMergedConsumerProperties", properties); } protected Map<String, Object> getAdminProperties(P properties) { return ReflectionTestUtils.invokeMethod(processor, "getMergedAdminProperties", properties); } protected String getProducerJaasProperties(P properties) { return (String) getProducerProperties(properties).get(SASL_JAAS_CONFIG); } protected String getConsumerJaasProperties(P properties) { return (String) getConsumerProperties(properties).get(SASL_JAAS_CONFIG); } protected String getAdminJaasProperties(P properties) { return (String) getAdminProperties(properties).get(SASL_JAAS_CONFIG); } protected void shouldConfigureOAuthProperties(Map<String, Object> configurationProperties) { assertEquals(SECURITY_PROTOCOL_CONFIG_SASL, configurationProperties.get(SECURITY_PROTOCOL_CONFIG)); assertEquals(SASL_MECHANISM_OAUTH, configurationProperties.get(SASL_MECHANISM)); assertTrue(((String) configurationProperties.get(SASL_JAAS_CONFIG)).startsWith(SASL_JAAS_CONFIG_OAUTH_PREFIX)); assertTrue(((String) configurationProperties.get(SASL_JAAS_CONFIG)).contains(AZURE_CONFIGURED_JAAS_OPTIONS)); assertEquals(SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH, configurationProperties.get(SASL_LOGIN_CALLBACK_HANDLER_CLASS)); } protected void assertConsumerPropsConfigured(P properties, String removedProperty, String filledProperty) { assertPropertiesConfigured(getConsumerProperties(properties), getConsumerJaasProperties(properties), removedProperty, filledProperty); } protected void assertProducerPropsConfigured(P properties, String removedProperty, String filledProperty) { assertPropertiesConfigured(getProducerProperties(properties), getProducerJaasProperties(properties), removedProperty, filledProperty); } protected void assertAdminPropsConfigured(P properties, String removedProperty, String filledProperty) { assertPropertiesConfigured(getAdminProperties(properties), getAdminJaasProperties(properties), removedProperty, filledProperty); } protected void assertPropertiesConfigured(Map<String, Object> configs, String jaas, String removedProperty, String filledProperty) { shouldConfigureOAuthProperties(configs); assertFalse(configs.containsKey(removedProperty)); assertTrue(jaas.contains(filledProperty)); } }
class AbstractAzureKafkaOAuth2AutoConfigurationTests<P, B extends AbstractKafkaPropertiesBeanPostProcessor<P>> { protected abstract ApplicationContextRunner getContextRunnerWithEventHubsURL(); protected abstract ApplicationContextRunner getContextRunnerWithoutEventHubsURL(); protected abstract P getKafkaSpringProperties(ApplicationContext context); protected final B processor; AbstractAzureKafkaOAuth2AutoConfigurationTests(B processor) { this.processor = processor; } @Test @Test void testNotBindSpringBootKafkaProperties() { getContextRunnerWithoutEventHubsURL() .withPropertyValues( "spring.kafka.properties.azure.credential.managed-identity-enabled=true" ) .run(context -> { AzureGlobalProperties azureGlobalProperties = context.getBean(AzureGlobalProperties.class); assertFalse(azureGlobalProperties.getCredential().isManagedIdentityEnabled()); P kafkaSpringProperties = getKafkaSpringProperties(context); Map<String, Object> consumerProperties = processor.getMergedConsumerProperties(kafkaSpringProperties); assertPropertyRemoved(consumerProperties, "azure.credential.managed-identity-enabled"); assertNull(processor.getMergedAdminProperties(kafkaSpringProperties).get(SASL_JAAS_CONFIG)); }); } protected void assertOAuthPropertiesConfigure(Map<String, Object> configs) { assertEquals(SECURITY_PROTOCOL_CONFIG_SASL, configs.get(SECURITY_PROTOCOL_CONFIG)); assertEquals(SASL_MECHANISM_OAUTH, configs.get(SASL_MECHANISM)); assertTrue(((String) configs.get(SASL_JAAS_CONFIG)).startsWith("org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required")); assertTrue(((String) configs.get(SASL_JAAS_CONFIG)).contains(AZURE_CONFIGURED_JAAS_OPTIONS_KEY + "=\"" + AZURE_CONFIGURED_JAAS_OPTIONS_VALUE + "\"")); assertEquals(SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH, configs.get(SASL_LOGIN_CALLBACK_HANDLER_CLASS)); } protected void assertPropertyRemoved(Map<String, Object> configs, String key) { assertFalse(configs.containsKey(key)); } protected void assertJaasPropertiesConfigured(Map<String, Object> configs, String key, String value) { String jaas = (String) configs.get(SASL_JAAS_CONFIG); assertTrue(jaas.contains(key.concat("=\"").concat(value).concat("\""))); } }
is this correct? the loginModule can't be null should in the ctor
public String toString() { if (loginModule == null) { LOGGER.error("The login module of JAAS should not be null"); } if (controlFlag == null) { LOGGER.error("The control flag of JAAS should not be null"); } StringBuilder builder = new StringBuilder(String.format(JAAS_PREFIX_FORMAT, loginModule == null ? "" : loginModule, controlFlag == null ? "" : controlFlag)); options.forEach((k, v) -> builder.append(String.format(JAAS_OPTIONS_FORMAT, k, v))); builder.append(TERMINATOR); return builder.toString(); }
}
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(loginModule).append(DELIMITER).append(controlFlag.name().toLowerCase(Locale.ROOT)); for (Map.Entry<String, String> entry : options.entrySet()) { builder.append(DELIMITER).append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); } return builder.append(TERMINATOR).toString(); }
class Jaas { public static final String JAAS_PREFIX_FORMAT = "%s %s"; public static final String JAAS_OPTIONS_FORMAT = " %s=\"%s\""; public static final String TERMINATOR = ";"; private static final Logger LOGGER = LoggerFactory.getLogger(Jaas.class); public Jaas(String loginModule) { this(loginModule, "required"); } public Jaas(String loginModule, String controlFlag) { this(loginModule, controlFlag, new HashMap<>()); } public Jaas(String loginModule, String controlFlag, Map<String, String> options) { this.loginModule = loginModule; this.controlFlag = controlFlag; this.options = options; } /** * Login module. */ private String loginModule; /** * Control flag for login configuration. */ private String controlFlag; /** * Additional JAAS options. */ private Map<String, String> options; public String getLoginModule() { return this.loginModule; } public void setLoginModule(String loginModule) { this.loginModule = loginModule; } public String getControlFlag() { return this.controlFlag; } public void setControlFlag(String controlFlag) { this.controlFlag = controlFlag; } public Map<String, String> getOptions() { return this.options; } public void setOptions(Map<String, String> options) { this.options = options; } public void putOptions(Map<String, String> options) { if (options != null) { this.options.putAll(options); } } @Override }
class Jaas { public static final String DELIMITER = " "; public static final String TERMINATOR = ";"; public Jaas(String loginModule) { this(loginModule, ControlFlag.REQUIRED); } public Jaas(String loginModule, ControlFlag controlFlag) { this(loginModule, controlFlag, new HashMap<>()); } public Jaas(String loginModule, ControlFlag controlFlag, Map<String, String> options) { Assert.hasText(loginModule, "The login module of JAAS should not be null or empty"); Assert.notNull(controlFlag, "The control flag of JAAS should not be null"); this.loginModule = loginModule; this.controlFlag = controlFlag; this.options = options == null ? new HashMap<>() : options; } /** * Login module. */ private String loginModule; /** * Control flag for login configuration. */ private ControlFlag controlFlag; /** * Additional JAAS options. */ private Map<String, String> options; public String getLoginModule() { return this.loginModule; } public void setLoginModule(String loginModule) { this.loginModule = loginModule; } public ControlFlag getControlFlag() { return this.controlFlag; } public void setControlFlag(ControlFlag controlFlag) { this.controlFlag = controlFlag; } public Map<String, String> getOptions() { return this.options; } public void setOptions(Map<String, String> options) { this.options = options; } public void putOptions(Map<String, String> options) { if (options != null) { this.options.putAll(options); } } @Override public enum ControlFlag { REQUIRED, REQUISITE, SUFFICIENT, OPTIONAL; private static final Map<String, ControlFlag> CONTROL_FLAG_MAP = initMap(); private static Map<String, ControlFlag> initMap() { return Collections.unmodifiableMap(Arrays.stream(ControlFlag.values()) .collect(Collectors.toMap(f -> f.name(), Function.identity()))); } public static ControlFlag fromString(String value) { return CONTROL_FLAG_MAP.get(value.toUpperCase(Locale.ROOT)); } } }
let's discuss this
public String toString() { StringBuilder builder = new StringBuilder(String.format(JAAS_PREFIX_FORMAT, loginModule, controlFlag)); options.forEach((k, v) -> builder.append(String.format(JAAS_OPTIONS_FORMAT, k, v))); builder.append(TERMINATOR); return builder.toString(); }
return builder.toString();
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(loginModule).append(DELIMITER).append(controlFlag.name().toLowerCase(Locale.ROOT)); for (Map.Entry<String, String> entry : options.entrySet()) { builder.append(DELIMITER).append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); } return builder.append(TERMINATOR).toString(); }
class Jaas { public static final String JAAS_PREFIX_FORMAT = "%s %s"; public static final String JAAS_OPTIONS_FORMAT = " %s=\"%s\""; public static final String TERMINATOR = ";"; public Jaas(String loginModule) { this(loginModule, "required"); } public Jaas(String loginModule, String controlFlag) { this(loginModule, controlFlag, new HashMap<>()); } public Jaas(String loginModule, String controlFlag, Map<String, String> options) { Assert.hasText(loginModule, "The login module of JAAS should not be null"); Assert.hasText(controlFlag, "The control flag of JAAS should not be null"); this.loginModule = loginModule; this.controlFlag = controlFlag; this.options = options; } /** * Login module. */ private String loginModule; /** * Control flag for login configuration. */ private String controlFlag; /** * Additional JAAS options. */ private Map<String, String> options; public String getLoginModule() { return this.loginModule; } public void setLoginModule(String loginModule) { this.loginModule = loginModule; } public String getControlFlag() { return this.controlFlag; } public void setControlFlag(String controlFlag) { this.controlFlag = controlFlag; } public Map<String, String> getOptions() { return this.options; } public void setOptions(Map<String, String> options) { this.options = options; } public void putOptions(Map<String, String> options) { if (options != null) { this.options.putAll(options); } } @Override }
class Jaas { public static final String DELIMITER = " "; public static final String TERMINATOR = ";"; public Jaas(String loginModule) { this(loginModule, ControlFlag.REQUIRED); } public Jaas(String loginModule, ControlFlag controlFlag) { this(loginModule, controlFlag, new HashMap<>()); } public Jaas(String loginModule, ControlFlag controlFlag, Map<String, String> options) { Assert.hasText(loginModule, "The login module of JAAS should not be null or empty"); Assert.notNull(controlFlag, "The control flag of JAAS should not be null"); this.loginModule = loginModule; this.controlFlag = controlFlag; this.options = options == null ? new HashMap<>() : options; } /** * Login module. */ private String loginModule; /** * Control flag for login configuration. */ private ControlFlag controlFlag; /** * Additional JAAS options. */ private Map<String, String> options; public String getLoginModule() { return this.loginModule; } public void setLoginModule(String loginModule) { this.loginModule = loginModule; } public ControlFlag getControlFlag() { return this.controlFlag; } public void setControlFlag(ControlFlag controlFlag) { this.controlFlag = controlFlag; } public Map<String, String> getOptions() { return this.options; } public void setOptions(Map<String, String> options) { this.options = options; } public void putOptions(Map<String, String> options) { if (options != null) { this.options.putAll(options); } } @Override public enum ControlFlag { REQUIRED, REQUISITE, SUFFICIENT, OPTIONAL; private static final Map<String, ControlFlag> CONTROL_FLAG_MAP = initMap(); private static Map<String, ControlFlag> initMap() { return Collections.unmodifiableMap(Arrays.stream(ControlFlag.values()) .collect(Collectors.toMap(f -> f.name(), Function.identity()))); } public static ControlFlag fromString(String value) { return CONTROL_FLAG_MAP.get(value.toUpperCase(Locale.ROOT)); } } }
can we use ```java return resolver.resolve(jaasConfig).map(AZURE_CONFIGURED_JAAS_OPTIONS_VALUE.equals(jaas.getOptions().get(jaas.getOptions()))).orElse(false); ```
private boolean meetJaasConditions(String jaasConfig) { if (jaasConfig == null) { return true; } AtomicBoolean flag = new AtomicBoolean(false); JaasResolver resolver = new JaasResolver(); resolver.resolve(jaasConfig).ifPresent(jaas -> { if (AZURE_CONFIGURED_JAAS_OPTIONS_VALUE.equals(jaas.getOptions().get(jaas.getOptions()))) { flag.set(true); } }); return flag.get(); }
}
private boolean meetJaasConditions(String jaasConfig) { if (jaasConfig == null) { return true; } JaasResolver resolver = new JaasResolver(); return resolver.resolve(jaasConfig) .map(jaas -> AZURE_CONFIGURED_JAAS_OPTIONS_VALUE.equals( jaas.getOptions().get(AZURE_CONFIGURED_JAAS_OPTIONS_KEY))) .orElse(false); }
class AbstractKafkaPropertiesBeanPostProcessor<T> implements BeanPostProcessor { static final String SECURITY_PROTOCOL_CONFIG_SASL = SASL_SSL.name(); static final String SASL_MECHANISM_OAUTH = OAUTHBEARER_MECHANISM; static final String AZURE_CONFIGURED_JAAS_OPTIONS_KEY = "azure.configured"; static final String AZURE_CONFIGURED_JAAS_OPTIONS_VALUE = "true"; static final String AZURE_CONFIGURED_JAAS_OPTIONS = AZURE_CONFIGURED_JAAS_OPTIONS_KEY + "=\"" + AZURE_CONFIGURED_JAAS_OPTIONS_VALUE + "\""; static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH = KafkaOAuth2AuthenticateCallbackHandler.class.getName(); protected static final PropertyMapper PROPERTY_MAPPER = new PropertyMapper(); private static final Map<String, String> KAFKA_OAUTH_CONFIGS; private static final String LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE = "OAUTHBEARER authentication property {} will be configured as {} to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE = "Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication will be loaded to configure your Kafka security and sasl properties to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION = "Currently {} authentication mechanism is used, recommend to use Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication" + " which supports various Azure Identity credentials. To leverage the auto-configuration for OAuth2, you can just remove all your security, sasl and credential configurations of Kafka and Event Hubs." + " And configure Kafka bootstrap servers instead, which can be set as spring.kafka.boostrap-servers=EventHubsNamespacesFQDN:9093."; static { Map<String, String> configs = new HashMap<>(); configs.put(SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); configs.put(SASL_MECHANISM, SASL_MECHANISM_OAUTH); configs.put(SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); KAFKA_OAUTH_CONFIGS = Collections.unmodifiableMap(configs); } private final AzureGlobalProperties azureGlobalProperties; AbstractKafkaPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { this.azureGlobalProperties = azureGlobalProperties; } @SuppressWarnings("unchecked") @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (needsPostProcess(bean)) { T properties = (T) bean; replaceAzurePropertiesWithJaas(getMergedProducerProperties(properties), getRawProducerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedConsumerProperties(properties), getRawConsumerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedAdminProperties(properties), getRawAdminProperties(properties)); customizeProcess(properties); } return bean; } /** * Create a map of the merged Kafka producer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka producer properties */ protected abstract Map<String, Object> getMergedProducerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores producer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing producer-specific properties */ protected abstract Map<String, String> getRawProducerProperties(T properties); /** * Create a map of the merged Kafka consumer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka consumer properties */ protected abstract Map<String, Object> getMergedConsumerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores consumer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing consumer-specific properties */ protected abstract Map<String, String> getRawConsumerProperties(T properties); /** * Create a map of the merged Kafka admin properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka admin properties */ protected abstract Map<String, Object> getMergedAdminProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores admin-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing admin-specific properties */ protected abstract Map<String, String> getRawAdminProperties(T properties); protected abstract boolean needsPostProcess(Object bean); protected abstract Logger getLogger(); /** * Process Kafka Spring properties for any customized operations. * @param properties the Kafka Spring properties */ protected void customizeProcess(T properties) { } protected void clearAzureProperties(Map<String, String> properties) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(properties::remove); } /** * This method executes two operations: * <p> * 1. When this configuration meets Azure Kafka passwordless startup requirements, convert all Azure properties * in Kafka to {@link Jaas}, and configure the JAAS configuration back to Kafka. * </p> * <p> * 2. Clear any Azure properties in Kafka properties. * </p> * @param mergedProperties the merged Kafka properties which can contain Azure properties to resolve JAAS from * @param rawPropertiesMap the raw Kafka properties Map to configure JAAS to and remove Azure Properties from */ private void replaceAzurePropertiesWithJaas(Map<String, Object> mergedProperties, Map<String, String> rawPropertiesMap) { resolveJaasForAzure(mergedProperties) .ifPresent(jaas -> { configJaasToKafkaRawProperties(jaas, rawPropertiesMap); logConfigureOAuthProperties(); configureKafkaUserAgent(); }); clearAzureProperties(rawPropertiesMap); } private Optional<Jaas> resolveJaasForAzure(Map<String, Object> mergedProperties) { if (needConfigureSaslOAuth(mergedProperties)) { JaasResolver resolver = new JaasResolver(); Jaas jaas = resolver.resolve((String) mergedProperties.get(SASL_JAAS_CONFIG)) .orElse(new Jaas(OAuthBearerLoginModule.class.getName())); setAzurePropertiesToJaasOptionsIfAbsent(azureGlobalProperties, jaas); setKafkaPropertiesToJaasOptions(mergedProperties, jaas); jaas.getOptions().put(AZURE_CONFIGURED_JAAS_OPTIONS_KEY, AZURE_CONFIGURED_JAAS_OPTIONS_VALUE); return Optional.of(jaas); } else { return Optional.empty(); } } private void configJaasToKafkaRawProperties(Jaas jaas, Map<String, String> rawPropertiesMap) { rawPropertiesMap.putAll(KAFKA_OAUTH_CONFIGS); rawPropertiesMap.put(SASL_JAAS_CONFIG, jaas.toString()); } /** * Configure necessary OAuth properties for kafka properties and log for the changes. */ private void logConfigureOAuthProperties() { getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_MECHANISM, SASL_MECHANISM_OAUTH); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_JAAS_CONFIG, "***the value involves credentials and will not be logged***"); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); } private void setKafkaPropertiesToJaasOptions(Map<String, ?> properties, Jaas jaas) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(k -> PROPERTY_MAPPER.from(properties.get(k)).to(p -> jaas.getOptions().put(k, (String) p))); } private void setAzurePropertiesToJaasOptionsIfAbsent(AzureProperties azureProperties, Jaas jaas) { convertAzurePropertiesToMap(azureProperties) .forEach((k, v) -> jaas.getOptions().putIfAbsent(k, v)); } private Map<String, String> convertAzurePropertiesToMap(AzureProperties properties) { Map<String, String> configs = new HashMap<>(); for (AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping m : AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.values()) { PROPERTY_MAPPER.from(m.getter().apply(properties)).to(p -> configs.put(m.propertyKey(), p)); } return configs; } /** * Configure Spring Cloud Azure user-agent for Kafka client. This method is idempotent to avoid configuring UA repeatedly. */ synchronized void configureKafkaUserAgent() { Method dataMethod = ReflectionUtils.findMethod(ApiVersionsRequest.class, "data"); if (dataMethod != null) { ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest.Builder().build(); ApiVersionsRequestData apiVersionsRequestData = (ApiVersionsRequestData) ReflectionUtils.invokeMethod(dataMethod, apiVersionsRequest); if (apiVersionsRequestData != null) { String clientSoftwareName = apiVersionsRequestData.clientSoftwareName(); if (clientSoftwareName != null && !clientSoftwareName.contains(AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH)) { apiVersionsRequestData.setClientSoftwareName(apiVersionsRequestData.clientSoftwareName() + AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH); apiVersionsRequestData.setClientSoftwareVersion(VERSION); } } } } /** * Detect whether we need to configure SASL/OAUTHBEARER properties for {@link KafkaProperties}. Will configure when * the security protocol is not configured, or it's set as SASL_SSL with sasl mechanism as null or OAUTHBEAR. * * @param sourceProperties the source kafka properties for admin/consumer/producer to detect * @return whether we need to configure with Spring Cloud Azure MSI support or not. */ boolean needConfigureSaslOAuth(Map<String, Object> sourceProperties) { return meetAzureBootstrapServerConditions(sourceProperties) && meetSaslOAuthConditions(sourceProperties); } private boolean meetSaslOAuthConditions(Map<String, Object> sourceProperties) { String securityProtocol = (String) sourceProperties.get(SECURITY_PROTOCOL_CONFIG); String saslMechanism = (String) sourceProperties.get(SASL_MECHANISM); String jaasConfig = (String) sourceProperties.get(SASL_JAAS_CONFIG); if (meetSaslProtocolConditions(securityProtocol) && meetSaslOAuth2MechanismConditions(saslMechanism) && meetJaasConditions(jaasConfig)) { return true; } getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION, saslMechanism); return false; } private boolean meetSaslProtocolConditions(String securityProtocol) { return securityProtocol == null || SECURITY_PROTOCOL_CONFIG_SASL.equalsIgnoreCase(securityProtocol); } private boolean meetSaslOAuth2MechanismConditions(String saslMechanism) { return saslMechanism == null || SASL_MECHANISM_OAUTH.equalsIgnoreCase(saslMechanism); } private boolean meetAzureBootstrapServerConditions(Map<String, Object> sourceProperties) { Object bootstrapServers = sourceProperties.get(BOOTSTRAP_SERVERS_CONFIG); List<String> serverList; if (bootstrapServers instanceof String) { serverList = Arrays.asList(delimitedListToStringArray((String) bootstrapServers, ",")); } else if (bootstrapServers instanceof Iterable<?>) { serverList = new ArrayList<>(); for (Object obj : (Iterable) bootstrapServers) { if (obj instanceof String) { serverList.add((String) obj); } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } } } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } return serverList.size() == 1 && serverList.get(0).endsWith(":9093"); } }
class AbstractKafkaPropertiesBeanPostProcessor<T> implements BeanPostProcessor { static final String SECURITY_PROTOCOL_CONFIG_SASL = SASL_SSL.name(); static final String SASL_MECHANISM_OAUTH = OAUTHBEARER_MECHANISM; static final String AZURE_CONFIGURED_JAAS_OPTIONS_KEY = "azure.configured"; static final String AZURE_CONFIGURED_JAAS_OPTIONS_VALUE = "true"; static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH = KafkaOAuth2AuthenticateCallbackHandler.class.getName(); protected static final PropertyMapper PROPERTY_MAPPER = new PropertyMapper(); private static final Map<String, String> KAFKA_OAUTH_CONFIGS; private static final String LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE = "OAUTHBEARER authentication property {} will be configured as {} to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE = "Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication will be loaded to configure your Kafka security and sasl properties to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION = "Currently {} authentication mechanism is used, recommend to use Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication" + " which supports various Azure Identity credentials. To leverage the auto-configuration for OAuth2, you can just remove all your security, sasl and credential configurations of Kafka and Event Hubs." + " And configure Kafka bootstrap servers instead, which can be set as spring.kafka.boostrap-servers=EventHubsNamespacesFQDN:9093."; static { Map<String, String> configs = new HashMap<>(); configs.put(SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); configs.put(SASL_MECHANISM, SASL_MECHANISM_OAUTH); configs.put(SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); KAFKA_OAUTH_CONFIGS = Collections.unmodifiableMap(configs); } private final AzureGlobalProperties azureGlobalProperties; AbstractKafkaPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { this.azureGlobalProperties = azureGlobalProperties; } @SuppressWarnings("unchecked") @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (needsPostProcess(bean)) { T properties = (T) bean; replaceAzurePropertiesWithJaas(getMergedProducerProperties(properties), getRawProducerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedConsumerProperties(properties), getRawConsumerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedAdminProperties(properties), getRawAdminProperties(properties)); customizeProcess(properties); } return bean; } /** * Create a map of the merged Kafka producer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka producer properties */ protected abstract Map<String, Object> getMergedProducerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores producer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing producer-specific properties */ protected abstract Map<String, String> getRawProducerProperties(T properties); /** * Create a map of the merged Kafka consumer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka consumer properties */ protected abstract Map<String, Object> getMergedConsumerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores consumer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing consumer-specific properties */ protected abstract Map<String, String> getRawConsumerProperties(T properties); /** * Create a map of the merged Kafka admin properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka admin properties */ protected abstract Map<String, Object> getMergedAdminProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores admin-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing admin-specific properties */ protected abstract Map<String, String> getRawAdminProperties(T properties); protected abstract boolean needsPostProcess(Object bean); protected abstract Logger getLogger(); /** * Process Kafka Spring properties for any customized operations. * @param properties the Kafka Spring properties */ protected void customizeProcess(T properties) { } protected void clearAzureProperties(Map<String, String> properties) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(properties::remove); } /** * This method executes two operations: * <p> * 1. When this configuration meets Azure Kafka passwordless startup requirements, convert all Azure properties * in Kafka to {@link Jaas}, and configure the JAAS configuration back to Kafka. * </p> * <p> * 2. Clear any Azure properties in Kafka properties. * </p> * @param mergedProperties the merged Kafka properties which can contain Azure properties to resolve JAAS from * @param rawPropertiesMap the raw Kafka properties Map to configure JAAS to and remove Azure Properties from */ private void replaceAzurePropertiesWithJaas(Map<String, Object> mergedProperties, Map<String, String> rawPropertiesMap) { resolveJaasForAzure(mergedProperties) .ifPresent(jaas -> { configJaasToKafkaRawProperties(jaas, rawPropertiesMap); logConfigureOAuthProperties(); configureKafkaUserAgent(); }); clearAzureProperties(rawPropertiesMap); } private Optional<Jaas> resolveJaasForAzure(Map<String, Object> mergedProperties) { if (needConfigureSaslOAuth(mergedProperties)) { JaasResolver resolver = new JaasResolver(); Jaas jaas = resolver.resolve((String) mergedProperties.get(SASL_JAAS_CONFIG)) .orElse(new Jaas(OAuthBearerLoginModule.class.getName())); setAzurePropertiesToJaasOptionsIfAbsent(azureGlobalProperties, jaas); setKafkaPropertiesToJaasOptions(mergedProperties, jaas); jaas.getOptions().put(AZURE_CONFIGURED_JAAS_OPTIONS_KEY, AZURE_CONFIGURED_JAAS_OPTIONS_VALUE); return Optional.of(jaas); } else { return Optional.empty(); } } private void configJaasToKafkaRawProperties(Jaas jaas, Map<String, String> rawPropertiesMap) { rawPropertiesMap.putAll(KAFKA_OAUTH_CONFIGS); rawPropertiesMap.put(SASL_JAAS_CONFIG, jaas.toString()); } /** * Configure necessary OAuth properties for kafka properties and log for the changes. */ private void logConfigureOAuthProperties() { getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_MECHANISM, SASL_MECHANISM_OAUTH); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_JAAS_CONFIG, "***the value involves credentials and will not be logged***"); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); } private void setKafkaPropertiesToJaasOptions(Map<String, ?> properties, Jaas jaas) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(k -> PROPERTY_MAPPER.from(properties.get(k)).to(p -> jaas.getOptions().put(k, (String) p))); } private void setAzurePropertiesToJaasOptionsIfAbsent(AzureProperties azureProperties, Jaas jaas) { convertAzurePropertiesToMap(azureProperties) .forEach((k, v) -> jaas.getOptions().putIfAbsent(k, v)); } private Map<String, String> convertAzurePropertiesToMap(AzureProperties properties) { Map<String, String> configs = new HashMap<>(); for (AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping m : AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.values()) { PROPERTY_MAPPER.from(m.getter().apply(properties)).to(p -> configs.put(m.propertyKey(), p)); } return configs; } /** * Configure Spring Cloud Azure user-agent for Kafka client. This method is idempotent to avoid configuring UA repeatedly. */ synchronized void configureKafkaUserAgent() { Method dataMethod = ReflectionUtils.findMethod(ApiVersionsRequest.class, "data"); if (dataMethod != null) { ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest.Builder().build(); ApiVersionsRequestData apiVersionsRequestData = (ApiVersionsRequestData) ReflectionUtils.invokeMethod(dataMethod, apiVersionsRequest); if (apiVersionsRequestData != null) { String clientSoftwareName = apiVersionsRequestData.clientSoftwareName(); if (clientSoftwareName != null && !clientSoftwareName.contains(AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH)) { apiVersionsRequestData.setClientSoftwareName(apiVersionsRequestData.clientSoftwareName() + AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH); apiVersionsRequestData.setClientSoftwareVersion(VERSION); } } } } /** * Detect whether we need to configure SASL/OAUTHBEARER properties for {@link KafkaProperties}. Will configure when * the security protocol is not configured, or it's set as SASL_SSL with sasl mechanism as null or OAUTHBEAR. * * @param sourceProperties the source kafka properties for admin/consumer/producer to detect * @return whether we need to configure with Spring Cloud Azure MSI support or not. */ boolean needConfigureSaslOAuth(Map<String, Object> sourceProperties) { return meetAzureBootstrapServerConditions(sourceProperties) && meetSaslOAuthConditions(sourceProperties); } private boolean meetSaslOAuthConditions(Map<String, Object> sourceProperties) { String securityProtocol = (String) sourceProperties.get(SECURITY_PROTOCOL_CONFIG); String saslMechanism = (String) sourceProperties.get(SASL_MECHANISM); String jaasConfig = (String) sourceProperties.get(SASL_JAAS_CONFIG); if (meetSaslProtocolConditions(securityProtocol) && meetSaslOAuth2MechanismConditions(saslMechanism) && meetJaasConditions(jaasConfig)) { return true; } getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION, saslMechanism); return false; } private boolean meetSaslProtocolConditions(String securityProtocol) { return securityProtocol == null || SECURITY_PROTOCOL_CONFIG_SASL.equalsIgnoreCase(securityProtocol); } private boolean meetSaslOAuth2MechanismConditions(String saslMechanism) { return saslMechanism == null || SASL_MECHANISM_OAUTH.equalsIgnoreCase(saslMechanism); } private boolean meetAzureBootstrapServerConditions(Map<String, Object> sourceProperties) { Object bootstrapServers = sourceProperties.get(BOOTSTRAP_SERVERS_CONFIG); List<String> serverList; if (bootstrapServers instanceof String) { serverList = Arrays.asList(delimitedListToStringArray((String) bootstrapServers, ",")); } else if (bootstrapServers instanceof Iterable<?>) { serverList = new ArrayList<>(); for (Object obj : (Iterable) bootstrapServers) { if (obj instanceof String) { serverList.add((String) obj); } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } } } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } return serverList.size() == 1 && serverList.get(0).endsWith(":9093"); } }
I will update, `jaas.getOptions().get(jaas.getOptions())` is a typo and also the reason why the ut fails now.
private boolean meetJaasConditions(String jaasConfig) { if (jaasConfig == null) { return true; } AtomicBoolean flag = new AtomicBoolean(false); JaasResolver resolver = new JaasResolver(); resolver.resolve(jaasConfig).ifPresent(jaas -> { if (AZURE_CONFIGURED_JAAS_OPTIONS_VALUE.equals(jaas.getOptions().get(jaas.getOptions()))) { flag.set(true); } }); return flag.get(); }
}
private boolean meetJaasConditions(String jaasConfig) { if (jaasConfig == null) { return true; } JaasResolver resolver = new JaasResolver(); return resolver.resolve(jaasConfig) .map(jaas -> AZURE_CONFIGURED_JAAS_OPTIONS_VALUE.equals( jaas.getOptions().get(AZURE_CONFIGURED_JAAS_OPTIONS_KEY))) .orElse(false); }
class AbstractKafkaPropertiesBeanPostProcessor<T> implements BeanPostProcessor { static final String SECURITY_PROTOCOL_CONFIG_SASL = SASL_SSL.name(); static final String SASL_MECHANISM_OAUTH = OAUTHBEARER_MECHANISM; static final String AZURE_CONFIGURED_JAAS_OPTIONS_KEY = "azure.configured"; static final String AZURE_CONFIGURED_JAAS_OPTIONS_VALUE = "true"; static final String AZURE_CONFIGURED_JAAS_OPTIONS = AZURE_CONFIGURED_JAAS_OPTIONS_KEY + "=\"" + AZURE_CONFIGURED_JAAS_OPTIONS_VALUE + "\""; static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH = KafkaOAuth2AuthenticateCallbackHandler.class.getName(); protected static final PropertyMapper PROPERTY_MAPPER = new PropertyMapper(); private static final Map<String, String> KAFKA_OAUTH_CONFIGS; private static final String LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE = "OAUTHBEARER authentication property {} will be configured as {} to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE = "Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication will be loaded to configure your Kafka security and sasl properties to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION = "Currently {} authentication mechanism is used, recommend to use Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication" + " which supports various Azure Identity credentials. To leverage the auto-configuration for OAuth2, you can just remove all your security, sasl and credential configurations of Kafka and Event Hubs." + " And configure Kafka bootstrap servers instead, which can be set as spring.kafka.boostrap-servers=EventHubsNamespacesFQDN:9093."; static { Map<String, String> configs = new HashMap<>(); configs.put(SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); configs.put(SASL_MECHANISM, SASL_MECHANISM_OAUTH); configs.put(SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); KAFKA_OAUTH_CONFIGS = Collections.unmodifiableMap(configs); } private final AzureGlobalProperties azureGlobalProperties; AbstractKafkaPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { this.azureGlobalProperties = azureGlobalProperties; } @SuppressWarnings("unchecked") @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (needsPostProcess(bean)) { T properties = (T) bean; replaceAzurePropertiesWithJaas(getMergedProducerProperties(properties), getRawProducerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedConsumerProperties(properties), getRawConsumerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedAdminProperties(properties), getRawAdminProperties(properties)); customizeProcess(properties); } return bean; } /** * Create a map of the merged Kafka producer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka producer properties */ protected abstract Map<String, Object> getMergedProducerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores producer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing producer-specific properties */ protected abstract Map<String, String> getRawProducerProperties(T properties); /** * Create a map of the merged Kafka consumer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka consumer properties */ protected abstract Map<String, Object> getMergedConsumerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores consumer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing consumer-specific properties */ protected abstract Map<String, String> getRawConsumerProperties(T properties); /** * Create a map of the merged Kafka admin properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka admin properties */ protected abstract Map<String, Object> getMergedAdminProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores admin-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing admin-specific properties */ protected abstract Map<String, String> getRawAdminProperties(T properties); protected abstract boolean needsPostProcess(Object bean); protected abstract Logger getLogger(); /** * Process Kafka Spring properties for any customized operations. * @param properties the Kafka Spring properties */ protected void customizeProcess(T properties) { } protected void clearAzureProperties(Map<String, String> properties) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(properties::remove); } /** * This method executes two operations: * <p> * 1. When this configuration meets Azure Kafka passwordless startup requirements, convert all Azure properties * in Kafka to {@link Jaas}, and configure the JAAS configuration back to Kafka. * </p> * <p> * 2. Clear any Azure properties in Kafka properties. * </p> * @param mergedProperties the merged Kafka properties which can contain Azure properties to resolve JAAS from * @param rawPropertiesMap the raw Kafka properties Map to configure JAAS to and remove Azure Properties from */ private void replaceAzurePropertiesWithJaas(Map<String, Object> mergedProperties, Map<String, String> rawPropertiesMap) { resolveJaasForAzure(mergedProperties) .ifPresent(jaas -> { configJaasToKafkaRawProperties(jaas, rawPropertiesMap); logConfigureOAuthProperties(); configureKafkaUserAgent(); }); clearAzureProperties(rawPropertiesMap); } private Optional<Jaas> resolveJaasForAzure(Map<String, Object> mergedProperties) { if (needConfigureSaslOAuth(mergedProperties)) { JaasResolver resolver = new JaasResolver(); Jaas jaas = resolver.resolve((String) mergedProperties.get(SASL_JAAS_CONFIG)) .orElse(new Jaas(OAuthBearerLoginModule.class.getName())); setAzurePropertiesToJaasOptionsIfAbsent(azureGlobalProperties, jaas); setKafkaPropertiesToJaasOptions(mergedProperties, jaas); jaas.getOptions().put(AZURE_CONFIGURED_JAAS_OPTIONS_KEY, AZURE_CONFIGURED_JAAS_OPTIONS_VALUE); return Optional.of(jaas); } else { return Optional.empty(); } } private void configJaasToKafkaRawProperties(Jaas jaas, Map<String, String> rawPropertiesMap) { rawPropertiesMap.putAll(KAFKA_OAUTH_CONFIGS); rawPropertiesMap.put(SASL_JAAS_CONFIG, jaas.toString()); } /** * Configure necessary OAuth properties for kafka properties and log for the changes. */ private void logConfigureOAuthProperties() { getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_MECHANISM, SASL_MECHANISM_OAUTH); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_JAAS_CONFIG, "***the value involves credentials and will not be logged***"); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); } private void setKafkaPropertiesToJaasOptions(Map<String, ?> properties, Jaas jaas) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(k -> PROPERTY_MAPPER.from(properties.get(k)).to(p -> jaas.getOptions().put(k, (String) p))); } private void setAzurePropertiesToJaasOptionsIfAbsent(AzureProperties azureProperties, Jaas jaas) { convertAzurePropertiesToMap(azureProperties) .forEach((k, v) -> jaas.getOptions().putIfAbsent(k, v)); } private Map<String, String> convertAzurePropertiesToMap(AzureProperties properties) { Map<String, String> configs = new HashMap<>(); for (AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping m : AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.values()) { PROPERTY_MAPPER.from(m.getter().apply(properties)).to(p -> configs.put(m.propertyKey(), p)); } return configs; } /** * Configure Spring Cloud Azure user-agent for Kafka client. This method is idempotent to avoid configuring UA repeatedly. */ synchronized void configureKafkaUserAgent() { Method dataMethod = ReflectionUtils.findMethod(ApiVersionsRequest.class, "data"); if (dataMethod != null) { ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest.Builder().build(); ApiVersionsRequestData apiVersionsRequestData = (ApiVersionsRequestData) ReflectionUtils.invokeMethod(dataMethod, apiVersionsRequest); if (apiVersionsRequestData != null) { String clientSoftwareName = apiVersionsRequestData.clientSoftwareName(); if (clientSoftwareName != null && !clientSoftwareName.contains(AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH)) { apiVersionsRequestData.setClientSoftwareName(apiVersionsRequestData.clientSoftwareName() + AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH); apiVersionsRequestData.setClientSoftwareVersion(VERSION); } } } } /** * Detect whether we need to configure SASL/OAUTHBEARER properties for {@link KafkaProperties}. Will configure when * the security protocol is not configured, or it's set as SASL_SSL with sasl mechanism as null or OAUTHBEAR. * * @param sourceProperties the source kafka properties for admin/consumer/producer to detect * @return whether we need to configure with Spring Cloud Azure MSI support or not. */ boolean needConfigureSaslOAuth(Map<String, Object> sourceProperties) { return meetAzureBootstrapServerConditions(sourceProperties) && meetSaslOAuthConditions(sourceProperties); } private boolean meetSaslOAuthConditions(Map<String, Object> sourceProperties) { String securityProtocol = (String) sourceProperties.get(SECURITY_PROTOCOL_CONFIG); String saslMechanism = (String) sourceProperties.get(SASL_MECHANISM); String jaasConfig = (String) sourceProperties.get(SASL_JAAS_CONFIG); if (meetSaslProtocolConditions(securityProtocol) && meetSaslOAuth2MechanismConditions(saslMechanism) && meetJaasConditions(jaasConfig)) { return true; } getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION, saslMechanism); return false; } private boolean meetSaslProtocolConditions(String securityProtocol) { return securityProtocol == null || SECURITY_PROTOCOL_CONFIG_SASL.equalsIgnoreCase(securityProtocol); } private boolean meetSaslOAuth2MechanismConditions(String saslMechanism) { return saslMechanism == null || SASL_MECHANISM_OAUTH.equalsIgnoreCase(saslMechanism); } private boolean meetAzureBootstrapServerConditions(Map<String, Object> sourceProperties) { Object bootstrapServers = sourceProperties.get(BOOTSTRAP_SERVERS_CONFIG); List<String> serverList; if (bootstrapServers instanceof String) { serverList = Arrays.asList(delimitedListToStringArray((String) bootstrapServers, ",")); } else if (bootstrapServers instanceof Iterable<?>) { serverList = new ArrayList<>(); for (Object obj : (Iterable) bootstrapServers) { if (obj instanceof String) { serverList.add((String) obj); } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } } } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } return serverList.size() == 1 && serverList.get(0).endsWith(":9093"); } }
class AbstractKafkaPropertiesBeanPostProcessor<T> implements BeanPostProcessor { static final String SECURITY_PROTOCOL_CONFIG_SASL = SASL_SSL.name(); static final String SASL_MECHANISM_OAUTH = OAUTHBEARER_MECHANISM; static final String AZURE_CONFIGURED_JAAS_OPTIONS_KEY = "azure.configured"; static final String AZURE_CONFIGURED_JAAS_OPTIONS_VALUE = "true"; static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH = KafkaOAuth2AuthenticateCallbackHandler.class.getName(); protected static final PropertyMapper PROPERTY_MAPPER = new PropertyMapper(); private static final Map<String, String> KAFKA_OAUTH_CONFIGS; private static final String LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE = "OAUTHBEARER authentication property {} will be configured as {} to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE = "Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication will be loaded to configure your Kafka security and sasl properties to support Azure Identity credentials."; private static final String LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION = "Currently {} authentication mechanism is used, recommend to use Spring Cloud Azure auto-configuration for Kafka OAUTHBEARER authentication" + " which supports various Azure Identity credentials. To leverage the auto-configuration for OAuth2, you can just remove all your security, sasl and credential configurations of Kafka and Event Hubs." + " And configure Kafka bootstrap servers instead, which can be set as spring.kafka.boostrap-servers=EventHubsNamespacesFQDN:9093."; static { Map<String, String> configs = new HashMap<>(); configs.put(SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); configs.put(SASL_MECHANISM, SASL_MECHANISM_OAUTH); configs.put(SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); KAFKA_OAUTH_CONFIGS = Collections.unmodifiableMap(configs); } private final AzureGlobalProperties azureGlobalProperties; AbstractKafkaPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { this.azureGlobalProperties = azureGlobalProperties; } @SuppressWarnings("unchecked") @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (needsPostProcess(bean)) { T properties = (T) bean; replaceAzurePropertiesWithJaas(getMergedProducerProperties(properties), getRawProducerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedConsumerProperties(properties), getRawConsumerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedAdminProperties(properties), getRawAdminProperties(properties)); customizeProcess(properties); } return bean; } /** * Create a map of the merged Kafka producer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka producer properties */ protected abstract Map<String, Object> getMergedProducerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores producer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing producer-specific properties */ protected abstract Map<String, String> getRawProducerProperties(T properties); /** * Create a map of the merged Kafka consumer properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka consumer properties */ protected abstract Map<String, Object> getMergedConsumerProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores consumer-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing consumer-specific properties */ protected abstract Map<String, String> getRawConsumerProperties(T properties); /** * Create a map of the merged Kafka admin properties from the Kafka Spring properties. * @param properties the Kafka Spring properties * @return a Map containing all Kafka admin properties */ protected abstract Map<String, Object> getMergedAdminProperties(T properties); /** * Get the raw {@link Map} object from the Kafka Spring properties that stores admin-specific properties. * @param properties the Kafka Spring properties * @return the map from Kafka properties storing admin-specific properties */ protected abstract Map<String, String> getRawAdminProperties(T properties); protected abstract boolean needsPostProcess(Object bean); protected abstract Logger getLogger(); /** * Process Kafka Spring properties for any customized operations. * @param properties the Kafka Spring properties */ protected void customizeProcess(T properties) { } protected void clearAzureProperties(Map<String, String> properties) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(properties::remove); } /** * This method executes two operations: * <p> * 1. When this configuration meets Azure Kafka passwordless startup requirements, convert all Azure properties * in Kafka to {@link Jaas}, and configure the JAAS configuration back to Kafka. * </p> * <p> * 2. Clear any Azure properties in Kafka properties. * </p> * @param mergedProperties the merged Kafka properties which can contain Azure properties to resolve JAAS from * @param rawPropertiesMap the raw Kafka properties Map to configure JAAS to and remove Azure Properties from */ private void replaceAzurePropertiesWithJaas(Map<String, Object> mergedProperties, Map<String, String> rawPropertiesMap) { resolveJaasForAzure(mergedProperties) .ifPresent(jaas -> { configJaasToKafkaRawProperties(jaas, rawPropertiesMap); logConfigureOAuthProperties(); configureKafkaUserAgent(); }); clearAzureProperties(rawPropertiesMap); } private Optional<Jaas> resolveJaasForAzure(Map<String, Object> mergedProperties) { if (needConfigureSaslOAuth(mergedProperties)) { JaasResolver resolver = new JaasResolver(); Jaas jaas = resolver.resolve((String) mergedProperties.get(SASL_JAAS_CONFIG)) .orElse(new Jaas(OAuthBearerLoginModule.class.getName())); setAzurePropertiesToJaasOptionsIfAbsent(azureGlobalProperties, jaas); setKafkaPropertiesToJaasOptions(mergedProperties, jaas); jaas.getOptions().put(AZURE_CONFIGURED_JAAS_OPTIONS_KEY, AZURE_CONFIGURED_JAAS_OPTIONS_VALUE); return Optional.of(jaas); } else { return Optional.empty(); } } private void configJaasToKafkaRawProperties(Jaas jaas, Map<String, String> rawPropertiesMap) { rawPropertiesMap.putAll(KAFKA_OAUTH_CONFIGS); rawPropertiesMap.put(SASL_JAAS_CONFIG, jaas.toString()); } /** * Configure necessary OAuth properties for kafka properties and log for the changes. */ private void logConfigureOAuthProperties() { getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_CONFIGURE); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SECURITY_PROTOCOL_CONFIG, SECURITY_PROTOCOL_CONFIG_SASL); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_MECHANISM, SASL_MECHANISM_OAUTH); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_JAAS_CONFIG, "***the value involves credentials and will not be logged***"); getLogger().debug(LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE, SASL_LOGIN_CALLBACK_HANDLER_CLASS, SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH); } private void setKafkaPropertiesToJaasOptions(Map<String, ?> properties, Jaas jaas) { AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.getPropertyKeys() .forEach(k -> PROPERTY_MAPPER.from(properties.get(k)).to(p -> jaas.getOptions().put(k, (String) p))); } private void setAzurePropertiesToJaasOptionsIfAbsent(AzureProperties azureProperties, Jaas jaas) { convertAzurePropertiesToMap(azureProperties) .forEach((k, v) -> jaas.getOptions().putIfAbsent(k, v)); } private Map<String, String> convertAzurePropertiesToMap(AzureProperties properties) { Map<String, String> configs = new HashMap<>(); for (AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping m : AzureKafkaPropertiesUtils.AzureKafkaPasswordlessPropertiesMapping.values()) { PROPERTY_MAPPER.from(m.getter().apply(properties)).to(p -> configs.put(m.propertyKey(), p)); } return configs; } /** * Configure Spring Cloud Azure user-agent for Kafka client. This method is idempotent to avoid configuring UA repeatedly. */ synchronized void configureKafkaUserAgent() { Method dataMethod = ReflectionUtils.findMethod(ApiVersionsRequest.class, "data"); if (dataMethod != null) { ApiVersionsRequest apiVersionsRequest = new ApiVersionsRequest.Builder().build(); ApiVersionsRequestData apiVersionsRequestData = (ApiVersionsRequestData) ReflectionUtils.invokeMethod(dataMethod, apiVersionsRequest); if (apiVersionsRequestData != null) { String clientSoftwareName = apiVersionsRequestData.clientSoftwareName(); if (clientSoftwareName != null && !clientSoftwareName.contains(AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH)) { apiVersionsRequestData.setClientSoftwareName(apiVersionsRequestData.clientSoftwareName() + AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH); apiVersionsRequestData.setClientSoftwareVersion(VERSION); } } } } /** * Detect whether we need to configure SASL/OAUTHBEARER properties for {@link KafkaProperties}. Will configure when * the security protocol is not configured, or it's set as SASL_SSL with sasl mechanism as null or OAUTHBEAR. * * @param sourceProperties the source kafka properties for admin/consumer/producer to detect * @return whether we need to configure with Spring Cloud Azure MSI support or not. */ boolean needConfigureSaslOAuth(Map<String, Object> sourceProperties) { return meetAzureBootstrapServerConditions(sourceProperties) && meetSaslOAuthConditions(sourceProperties); } private boolean meetSaslOAuthConditions(Map<String, Object> sourceProperties) { String securityProtocol = (String) sourceProperties.get(SECURITY_PROTOCOL_CONFIG); String saslMechanism = (String) sourceProperties.get(SASL_MECHANISM); String jaasConfig = (String) sourceProperties.get(SASL_JAAS_CONFIG); if (meetSaslProtocolConditions(securityProtocol) && meetSaslOAuth2MechanismConditions(saslMechanism) && meetJaasConditions(jaasConfig)) { return true; } getLogger().info(LOG_OAUTH_AUTOCONFIGURATION_RECOMMENDATION, saslMechanism); return false; } private boolean meetSaslProtocolConditions(String securityProtocol) { return securityProtocol == null || SECURITY_PROTOCOL_CONFIG_SASL.equalsIgnoreCase(securityProtocol); } private boolean meetSaslOAuth2MechanismConditions(String saslMechanism) { return saslMechanism == null || SASL_MECHANISM_OAUTH.equalsIgnoreCase(saslMechanism); } private boolean meetAzureBootstrapServerConditions(Map<String, Object> sourceProperties) { Object bootstrapServers = sourceProperties.get(BOOTSTRAP_SERVERS_CONFIG); List<String> serverList; if (bootstrapServers instanceof String) { serverList = Arrays.asList(delimitedListToStringArray((String) bootstrapServers, ",")); } else if (bootstrapServers instanceof Iterable<?>) { serverList = new ArrayList<>(); for (Object obj : (Iterable) bootstrapServers) { if (obj instanceof String) { serverList.add((String) obj); } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } } } else { getLogger().debug("Kafka bootstrap server configuration doesn't meet passwordless requirements."); return false; } return serverList.size() == 1 && serverList.get(0).endsWith(":9093"); } }
maybe something like this? "awaitCopyStartCompletionAsync" cannot be called on snapshot when "creationMethod" is not "CopyStart"
public Mono<Void> awaitCopyStartCompletionAsync() { if (creationMethod() != DiskCreateOption.COPY_START) { return Mono.error(logger.logThrowableAsError(new IllegalStateException( String.format("Cannot call [awaitCopyStartCompletionAsync] on snapshot: %s, since creationMethod is [%s].", this.name(), this.creationMethod())))); } return getInnerAsync() .flatMap(inner -> { setInner(inner); Mono<SnapshotInner> result = Mono.just(inner); if (inner.copyCompletionError() != null) { result = Mono.error(new ManagementException(inner.copyCompletionError().errorMessage(), null)); } else if (inner.completionPercent() == null || inner.completionPercent() != 100) { logger.info("Wait for CopyStart complete for snapshot: {}. Complete percent: {}.", inner.name(), inner.completionPercent()); result = Mono.empty(); } return result; }) .repeatWhenEmpty(longFlux -> longFlux .flatMap( index -> Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( manager().serviceClient().getDefaultPollInterval())))) .then(); }
String.format("Cannot call [awaitCopyStartCompletionAsync] on snapshot: %s, since creationMethod is [%s].",
public Mono<Void> awaitCopyStartCompletionAsync() { if (creationMethod() != DiskCreateOption.COPY_START) { return Mono.error(logger.logThrowableAsError(new IllegalStateException( String.format( "\"awaitCopyStartCompletionAsync\" cannot be called on snapshot \"%s\" when \"creationMethod\" is not \"CopyStart\"", this.name())))); } return getInnerAsync() .flatMap(inner -> { setInner(inner); Mono<SnapshotInner> result = Mono.just(inner); if (inner.copyCompletionError() != null) { result = Mono.error(new ManagementException(inner.copyCompletionError().errorMessage(), null)); } else if (inner.completionPercent() == null || inner.completionPercent() != 100) { logger.info("Wait for CopyStart complete for snapshot: {}. Complete percent: {}.", inner.name(), inner.completionPercent()); result = Mono.empty(); } return result; }) .repeatWhenEmpty(longFlux -> longFlux .flatMap( index -> Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( manager().serviceClient().getDefaultPollInterval())))) .then(); }
class SnapshotImpl extends GroupableResourceImpl<Snapshot, SnapshotInner, SnapshotImpl, ComputeManager> implements Snapshot, Snapshot.Definition, Snapshot.Update { private final ClientLogger logger = new ClientLogger(SnapshotImpl.class); SnapshotImpl(String name, SnapshotInner innerModel, final ComputeManager computeManager) { super(name, innerModel, computeManager); } @Override public SnapshotSkuType skuType() { if (this.innerModel().sku() == null) { return null; } else { return SnapshotSkuType.fromSnapshotSku(this.innerModel().sku()); } } @Override public DiskCreateOption creationMethod() { return this.innerModel().creationData().createOption(); } @Override public boolean incremental() { return this.innerModel().incremental(); } @Override public int sizeInGB() { return ResourceManagerUtils.toPrimitiveInt(this.innerModel().diskSizeGB()); } @Override public OperatingSystemTypes osType() { return this.innerModel().osType(); } @Override public CreationSource source() { return new CreationSource(this.innerModel().creationData()); } @Override public Float copyCompletionPercent() { return this.innerModel().completionPercent(); } @Override public CopyCompletionError copyCompletionError() { return this.innerModel().copyCompletionError(); } @Override public String grantAccess(int accessDurationInSeconds) { return this.grantAccessAsync(accessDurationInSeconds).block(); } @Override public Mono<String> grantAccessAsync(int accessDurationInSeconds) { GrantAccessData grantAccessDataInner = new GrantAccessData(); grantAccessDataInner.withAccess(AccessLevel.READ).withDurationInSeconds(accessDurationInSeconds); return manager() .serviceClient() .getSnapshots() .grantAccessAsync(resourceGroupName(), name(), grantAccessDataInner) .map(accessUriInner -> accessUriInner.accessSas()); } @Override public void revokeAccess() { this.revokeAccessAsync().block(); } @Override public Mono<Void> revokeAccessAsync() { return this.manager().serviceClient().getSnapshots().revokeAccessAsync(this.resourceGroupName(), this.name()); } @Override public void awaitCopyStartCompletion() { awaitCopyStartCompletionAsync().block(); } @Override public Boolean awaitCopyStartCompletion(Duration maxWaitTime) { Objects.requireNonNull(maxWaitTime); if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw new IllegalArgumentException(String.format("Max wait time is non-positive: %dms", maxWaitTime.toMillis())); } return this.awaitCopyStartCompletionAsync() .then(Mono.just(Boolean.TRUE)) .timeout(maxWaitTime, Mono.just(Boolean.FALSE)) .block(); } @Override @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl) { return withLinuxFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withLinuxFromDisk(String sourceDiskId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceDiskId); return this; } @Override public SnapshotImpl withLinuxFromDisk(Disk sourceDisk) { withLinuxFromDisk(sourceDisk.id()); if (sourceDisk.osType() != null) { this.withOSType(sourceDisk.osType()); } return this; } @Override public SnapshotImpl withLinuxFromSnapshot(String sourceSnapshotId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceSnapshotId); return this; } @Override public SnapshotImpl withLinuxFromSnapshot(Snapshot sourceSnapshot) { withLinuxFromSnapshot(sourceSnapshot.id()); if (sourceSnapshot.osType() != null) { this.withOSType(sourceSnapshot.osType()); } this.withSku(sourceSnapshot.skuType()); return this; } @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl) { return withWindowsFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withWindowsFromDisk(String sourceDiskId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceDiskId); return this; } @Override public SnapshotImpl withWindowsFromDisk(Disk sourceDisk) { withWindowsFromDisk(sourceDisk.id()); if (sourceDisk.osType() != null) { this.withOSType(sourceDisk.osType()); } return this; } @Override public SnapshotImpl withWindowsFromSnapshot(String sourceSnapshotId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceSnapshotId); return this; } @Override public SnapshotImpl withWindowsFromSnapshot(Snapshot sourceSnapshot) { withWindowsFromSnapshot(sourceSnapshot.id()); if (sourceSnapshot.osType() != null) { this.withOSType(sourceSnapshot.osType()); } this.withSku(sourceSnapshot.skuType()); return this; } @Override public SnapshotImpl withDataFromVhd(String vhdUrl) { return withDataFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withDataFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withDataFromSnapshot(String snapshotId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(snapshotId); return this; } @Override public SnapshotImpl withDataFromSnapshot(Snapshot snapshot) { return withDataFromSnapshot(snapshot.id()); } @Override public SnapshotImpl withCopyStart() { this.innerModel() .creationData() .withCreateOption(DiskCreateOption.COPY_START); return this; } @Override public SnapshotImpl withDataFromDisk(String managedDiskId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(managedDiskId); return this; } @Override public SnapshotImpl withDataFromDisk(Disk managedDisk) { return withDataFromDisk(managedDisk.id()).withOSType(managedDisk.osType()); } @Override public SnapshotImpl withSizeInGB(int sizeInGB) { this.innerModel().withDiskSizeGB(sizeInGB); return this; } @Override public SnapshotImpl withIncremental(boolean enabled) { this.innerModel().withIncremental(enabled); return this; } @Override public SnapshotImpl withOSType(OperatingSystemTypes osType) { this.innerModel().withOsType(osType); return this; } @Override public SnapshotImpl withSku(SnapshotSkuType sku) { this.innerModel().withSku(new SnapshotSku().withName(sku.accountType())); return this; } @Override public Mono<Snapshot> createResourceAsync() { return this .manager() .serviceClient() .getSnapshots() .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) .map(innerToFluentMap(this)); } @Override protected Mono<SnapshotInner> getInnerAsync() { return this .manager() .serviceClient() .getSnapshots() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } private String constructStorageAccountId(String vhdUrl) { try { return ResourceUtils .constructResourceId( this.manager().subscriptionId(), resourceGroupName(), "Microsoft.Storage", "storageAccounts", vhdUrl.split("\\.")[0].replace("https: ""); } catch (RuntimeException ex) { throw logger .logExceptionAsError( new IllegalArgumentException(String.format("%s is not valid URI of a blob to import.", vhdUrl))); } } }
class SnapshotImpl extends GroupableResourceImpl<Snapshot, SnapshotInner, SnapshotImpl, ComputeManager> implements Snapshot, Snapshot.Definition, Snapshot.Update { private final ClientLogger logger = new ClientLogger(SnapshotImpl.class); SnapshotImpl(String name, SnapshotInner innerModel, final ComputeManager computeManager) { super(name, innerModel, computeManager); } @Override public SnapshotSkuType skuType() { if (this.innerModel().sku() == null) { return null; } else { return SnapshotSkuType.fromSnapshotSku(this.innerModel().sku()); } } @Override public DiskCreateOption creationMethod() { return this.innerModel().creationData().createOption(); } @Override public boolean incremental() { return this.innerModel().incremental(); } @Override public int sizeInGB() { return ResourceManagerUtils.toPrimitiveInt(this.innerModel().diskSizeGB()); } @Override public OperatingSystemTypes osType() { return this.innerModel().osType(); } @Override public CreationSource source() { return new CreationSource(this.innerModel().creationData()); } @Override public Float copyCompletionPercent() { return this.innerModel().completionPercent(); } @Override public CopyCompletionError copyCompletionError() { return this.innerModel().copyCompletionError(); } @Override public String grantAccess(int accessDurationInSeconds) { return this.grantAccessAsync(accessDurationInSeconds).block(); } @Override public Mono<String> grantAccessAsync(int accessDurationInSeconds) { GrantAccessData grantAccessDataInner = new GrantAccessData(); grantAccessDataInner.withAccess(AccessLevel.READ).withDurationInSeconds(accessDurationInSeconds); return manager() .serviceClient() .getSnapshots() .grantAccessAsync(resourceGroupName(), name(), grantAccessDataInner) .map(accessUriInner -> accessUriInner.accessSas()); } @Override public void revokeAccess() { this.revokeAccessAsync().block(); } @Override public Mono<Void> revokeAccessAsync() { return this.manager().serviceClient().getSnapshots().revokeAccessAsync(this.resourceGroupName(), this.name()); } @Override public void awaitCopyStartCompletion() { awaitCopyStartCompletionAsync().block(); } @Override public Boolean awaitCopyStartCompletion(Duration maxWaitTime) { Objects.requireNonNull(maxWaitTime); if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw new IllegalArgumentException(String.format("Max wait time is non-positive: %dms", maxWaitTime.toMillis())); } return this.awaitCopyStartCompletionAsync() .then(Mono.just(Boolean.TRUE)) .timeout(maxWaitTime, Mono.just(Boolean.FALSE)) .block(); } @Override @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl) { return withLinuxFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withLinuxFromDisk(String sourceDiskId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceDiskId); return this; } @Override public SnapshotImpl withLinuxFromDisk(Disk sourceDisk) { withLinuxFromDisk(sourceDisk.id()); if (sourceDisk.osType() != null) { this.withOSType(sourceDisk.osType()); } return this; } @Override public SnapshotImpl withLinuxFromSnapshot(String sourceSnapshotId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceSnapshotId); return this; } @Override public SnapshotImpl withLinuxFromSnapshot(Snapshot sourceSnapshot) { withLinuxFromSnapshot(sourceSnapshot.id()); if (sourceSnapshot.osType() != null) { this.withOSType(sourceSnapshot.osType()); } this.withSku(sourceSnapshot.skuType()); return this; } @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl) { return withWindowsFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withWindowsFromDisk(String sourceDiskId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceDiskId); return this; } @Override public SnapshotImpl withWindowsFromDisk(Disk sourceDisk) { withWindowsFromDisk(sourceDisk.id()); if (sourceDisk.osType() != null) { this.withOSType(sourceDisk.osType()); } return this; } @Override public SnapshotImpl withWindowsFromSnapshot(String sourceSnapshotId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceSnapshotId); return this; } @Override public SnapshotImpl withWindowsFromSnapshot(Snapshot sourceSnapshot) { withWindowsFromSnapshot(sourceSnapshot.id()); if (sourceSnapshot.osType() != null) { this.withOSType(sourceSnapshot.osType()); } this.withSku(sourceSnapshot.skuType()); return this; } @Override public SnapshotImpl withDataFromVhd(String vhdUrl) { return withDataFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withDataFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withDataFromSnapshot(String snapshotId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(snapshotId); return this; } @Override public SnapshotImpl withDataFromSnapshot(Snapshot snapshot) { return withDataFromSnapshot(snapshot.id()); } @Override public SnapshotImpl withCopyStart() { this.innerModel() .creationData() .withCreateOption(DiskCreateOption.COPY_START); return this; } @Override public SnapshotImpl withDataFromDisk(String managedDiskId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(managedDiskId); return this; } @Override public SnapshotImpl withDataFromDisk(Disk managedDisk) { return withDataFromDisk(managedDisk.id()).withOSType(managedDisk.osType()); } @Override public SnapshotImpl withSizeInGB(int sizeInGB) { this.innerModel().withDiskSizeGB(sizeInGB); return this; } @Override public SnapshotImpl withIncremental(boolean enabled) { this.innerModel().withIncremental(enabled); return this; } @Override public SnapshotImpl withOSType(OperatingSystemTypes osType) { this.innerModel().withOsType(osType); return this; } @Override public SnapshotImpl withSku(SnapshotSkuType sku) { this.innerModel().withSku(new SnapshotSku().withName(sku.accountType())); return this; } @Override public Mono<Snapshot> createResourceAsync() { return this .manager() .serviceClient() .getSnapshots() .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) .map(innerToFluentMap(this)); } @Override protected Mono<SnapshotInner> getInnerAsync() { return this .manager() .serviceClient() .getSnapshots() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } private String constructStorageAccountId(String vhdUrl) { try { return ResourceUtils .constructResourceId( this.manager().subscriptionId(), resourceGroupName(), "Microsoft.Storage", "storageAccounts", vhdUrl.split("\\.")[0].replace("https: ""); } catch (RuntimeException ex) { throw logger .logExceptionAsError( new IllegalArgumentException(String.format("%s is not valid URI of a blob to import.", vhdUrl))); } } }
changed
public Mono<Void> awaitCopyStartCompletionAsync() { if (creationMethod() != DiskCreateOption.COPY_START) { return Mono.error(logger.logThrowableAsError(new IllegalStateException( String.format("Cannot call [awaitCopyStartCompletionAsync] on snapshot: %s, since creationMethod is [%s].", this.name(), this.creationMethod())))); } return getInnerAsync() .flatMap(inner -> { setInner(inner); Mono<SnapshotInner> result = Mono.just(inner); if (inner.copyCompletionError() != null) { result = Mono.error(new ManagementException(inner.copyCompletionError().errorMessage(), null)); } else if (inner.completionPercent() == null || inner.completionPercent() != 100) { logger.info("Wait for CopyStart complete for snapshot: {}. Complete percent: {}.", inner.name(), inner.completionPercent()); result = Mono.empty(); } return result; }) .repeatWhenEmpty(longFlux -> longFlux .flatMap( index -> Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( manager().serviceClient().getDefaultPollInterval())))) .then(); }
String.format("Cannot call [awaitCopyStartCompletionAsync] on snapshot: %s, since creationMethod is [%s].",
public Mono<Void> awaitCopyStartCompletionAsync() { if (creationMethod() != DiskCreateOption.COPY_START) { return Mono.error(logger.logThrowableAsError(new IllegalStateException( String.format( "\"awaitCopyStartCompletionAsync\" cannot be called on snapshot \"%s\" when \"creationMethod\" is not \"CopyStart\"", this.name())))); } return getInnerAsync() .flatMap(inner -> { setInner(inner); Mono<SnapshotInner> result = Mono.just(inner); if (inner.copyCompletionError() != null) { result = Mono.error(new ManagementException(inner.copyCompletionError().errorMessage(), null)); } else if (inner.completionPercent() == null || inner.completionPercent() != 100) { logger.info("Wait for CopyStart complete for snapshot: {}. Complete percent: {}.", inner.name(), inner.completionPercent()); result = Mono.empty(); } return result; }) .repeatWhenEmpty(longFlux -> longFlux .flatMap( index -> Mono.delay(ResourceManagerUtils.InternalRuntimeContext.getDelayDuration( manager().serviceClient().getDefaultPollInterval())))) .then(); }
class SnapshotImpl extends GroupableResourceImpl<Snapshot, SnapshotInner, SnapshotImpl, ComputeManager> implements Snapshot, Snapshot.Definition, Snapshot.Update { private final ClientLogger logger = new ClientLogger(SnapshotImpl.class); SnapshotImpl(String name, SnapshotInner innerModel, final ComputeManager computeManager) { super(name, innerModel, computeManager); } @Override public SnapshotSkuType skuType() { if (this.innerModel().sku() == null) { return null; } else { return SnapshotSkuType.fromSnapshotSku(this.innerModel().sku()); } } @Override public DiskCreateOption creationMethod() { return this.innerModel().creationData().createOption(); } @Override public boolean incremental() { return this.innerModel().incremental(); } @Override public int sizeInGB() { return ResourceManagerUtils.toPrimitiveInt(this.innerModel().diskSizeGB()); } @Override public OperatingSystemTypes osType() { return this.innerModel().osType(); } @Override public CreationSource source() { return new CreationSource(this.innerModel().creationData()); } @Override public Float copyCompletionPercent() { return this.innerModel().completionPercent(); } @Override public CopyCompletionError copyCompletionError() { return this.innerModel().copyCompletionError(); } @Override public String grantAccess(int accessDurationInSeconds) { return this.grantAccessAsync(accessDurationInSeconds).block(); } @Override public Mono<String> grantAccessAsync(int accessDurationInSeconds) { GrantAccessData grantAccessDataInner = new GrantAccessData(); grantAccessDataInner.withAccess(AccessLevel.READ).withDurationInSeconds(accessDurationInSeconds); return manager() .serviceClient() .getSnapshots() .grantAccessAsync(resourceGroupName(), name(), grantAccessDataInner) .map(accessUriInner -> accessUriInner.accessSas()); } @Override public void revokeAccess() { this.revokeAccessAsync().block(); } @Override public Mono<Void> revokeAccessAsync() { return this.manager().serviceClient().getSnapshots().revokeAccessAsync(this.resourceGroupName(), this.name()); } @Override public void awaitCopyStartCompletion() { awaitCopyStartCompletionAsync().block(); } @Override public Boolean awaitCopyStartCompletion(Duration maxWaitTime) { Objects.requireNonNull(maxWaitTime); if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw new IllegalArgumentException(String.format("Max wait time is non-positive: %dms", maxWaitTime.toMillis())); } return this.awaitCopyStartCompletionAsync() .then(Mono.just(Boolean.TRUE)) .timeout(maxWaitTime, Mono.just(Boolean.FALSE)) .block(); } @Override @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl) { return withLinuxFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withLinuxFromDisk(String sourceDiskId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceDiskId); return this; } @Override public SnapshotImpl withLinuxFromDisk(Disk sourceDisk) { withLinuxFromDisk(sourceDisk.id()); if (sourceDisk.osType() != null) { this.withOSType(sourceDisk.osType()); } return this; } @Override public SnapshotImpl withLinuxFromSnapshot(String sourceSnapshotId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceSnapshotId); return this; } @Override public SnapshotImpl withLinuxFromSnapshot(Snapshot sourceSnapshot) { withLinuxFromSnapshot(sourceSnapshot.id()); if (sourceSnapshot.osType() != null) { this.withOSType(sourceSnapshot.osType()); } this.withSku(sourceSnapshot.skuType()); return this; } @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl) { return withWindowsFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withWindowsFromDisk(String sourceDiskId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceDiskId); return this; } @Override public SnapshotImpl withWindowsFromDisk(Disk sourceDisk) { withWindowsFromDisk(sourceDisk.id()); if (sourceDisk.osType() != null) { this.withOSType(sourceDisk.osType()); } return this; } @Override public SnapshotImpl withWindowsFromSnapshot(String sourceSnapshotId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceSnapshotId); return this; } @Override public SnapshotImpl withWindowsFromSnapshot(Snapshot sourceSnapshot) { withWindowsFromSnapshot(sourceSnapshot.id()); if (sourceSnapshot.osType() != null) { this.withOSType(sourceSnapshot.osType()); } this.withSku(sourceSnapshot.skuType()); return this; } @Override public SnapshotImpl withDataFromVhd(String vhdUrl) { return withDataFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withDataFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withDataFromSnapshot(String snapshotId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(snapshotId); return this; } @Override public SnapshotImpl withDataFromSnapshot(Snapshot snapshot) { return withDataFromSnapshot(snapshot.id()); } @Override public SnapshotImpl withCopyStart() { this.innerModel() .creationData() .withCreateOption(DiskCreateOption.COPY_START); return this; } @Override public SnapshotImpl withDataFromDisk(String managedDiskId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(managedDiskId); return this; } @Override public SnapshotImpl withDataFromDisk(Disk managedDisk) { return withDataFromDisk(managedDisk.id()).withOSType(managedDisk.osType()); } @Override public SnapshotImpl withSizeInGB(int sizeInGB) { this.innerModel().withDiskSizeGB(sizeInGB); return this; } @Override public SnapshotImpl withIncremental(boolean enabled) { this.innerModel().withIncremental(enabled); return this; } @Override public SnapshotImpl withOSType(OperatingSystemTypes osType) { this.innerModel().withOsType(osType); return this; } @Override public SnapshotImpl withSku(SnapshotSkuType sku) { this.innerModel().withSku(new SnapshotSku().withName(sku.accountType())); return this; } @Override public Mono<Snapshot> createResourceAsync() { return this .manager() .serviceClient() .getSnapshots() .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) .map(innerToFluentMap(this)); } @Override protected Mono<SnapshotInner> getInnerAsync() { return this .manager() .serviceClient() .getSnapshots() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } private String constructStorageAccountId(String vhdUrl) { try { return ResourceUtils .constructResourceId( this.manager().subscriptionId(), resourceGroupName(), "Microsoft.Storage", "storageAccounts", vhdUrl.split("\\.")[0].replace("https: ""); } catch (RuntimeException ex) { throw logger .logExceptionAsError( new IllegalArgumentException(String.format("%s is not valid URI of a blob to import.", vhdUrl))); } } }
class SnapshotImpl extends GroupableResourceImpl<Snapshot, SnapshotInner, SnapshotImpl, ComputeManager> implements Snapshot, Snapshot.Definition, Snapshot.Update { private final ClientLogger logger = new ClientLogger(SnapshotImpl.class); SnapshotImpl(String name, SnapshotInner innerModel, final ComputeManager computeManager) { super(name, innerModel, computeManager); } @Override public SnapshotSkuType skuType() { if (this.innerModel().sku() == null) { return null; } else { return SnapshotSkuType.fromSnapshotSku(this.innerModel().sku()); } } @Override public DiskCreateOption creationMethod() { return this.innerModel().creationData().createOption(); } @Override public boolean incremental() { return this.innerModel().incremental(); } @Override public int sizeInGB() { return ResourceManagerUtils.toPrimitiveInt(this.innerModel().diskSizeGB()); } @Override public OperatingSystemTypes osType() { return this.innerModel().osType(); } @Override public CreationSource source() { return new CreationSource(this.innerModel().creationData()); } @Override public Float copyCompletionPercent() { return this.innerModel().completionPercent(); } @Override public CopyCompletionError copyCompletionError() { return this.innerModel().copyCompletionError(); } @Override public String grantAccess(int accessDurationInSeconds) { return this.grantAccessAsync(accessDurationInSeconds).block(); } @Override public Mono<String> grantAccessAsync(int accessDurationInSeconds) { GrantAccessData grantAccessDataInner = new GrantAccessData(); grantAccessDataInner.withAccess(AccessLevel.READ).withDurationInSeconds(accessDurationInSeconds); return manager() .serviceClient() .getSnapshots() .grantAccessAsync(resourceGroupName(), name(), grantAccessDataInner) .map(accessUriInner -> accessUriInner.accessSas()); } @Override public void revokeAccess() { this.revokeAccessAsync().block(); } @Override public Mono<Void> revokeAccessAsync() { return this.manager().serviceClient().getSnapshots().revokeAccessAsync(this.resourceGroupName(), this.name()); } @Override public void awaitCopyStartCompletion() { awaitCopyStartCompletionAsync().block(); } @Override public Boolean awaitCopyStartCompletion(Duration maxWaitTime) { Objects.requireNonNull(maxWaitTime); if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw new IllegalArgumentException(String.format("Max wait time is non-positive: %dms", maxWaitTime.toMillis())); } return this.awaitCopyStartCompletionAsync() .then(Mono.just(Boolean.TRUE)) .timeout(maxWaitTime, Mono.just(Boolean.FALSE)) .block(); } @Override @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl) { return withLinuxFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withLinuxFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withLinuxFromDisk(String sourceDiskId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceDiskId); return this; } @Override public SnapshotImpl withLinuxFromDisk(Disk sourceDisk) { withLinuxFromDisk(sourceDisk.id()); if (sourceDisk.osType() != null) { this.withOSType(sourceDisk.osType()); } return this; } @Override public SnapshotImpl withLinuxFromSnapshot(String sourceSnapshotId) { this .innerModel() .withOsType(OperatingSystemTypes.LINUX) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceSnapshotId); return this; } @Override public SnapshotImpl withLinuxFromSnapshot(Snapshot sourceSnapshot) { withLinuxFromSnapshot(sourceSnapshot.id()); if (sourceSnapshot.osType() != null) { this.withOSType(sourceSnapshot.osType()); } this.withSku(sourceSnapshot.skuType()); return this; } @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl) { return withWindowsFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withWindowsFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withWindowsFromDisk(String sourceDiskId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceDiskId); return this; } @Override public SnapshotImpl withWindowsFromDisk(Disk sourceDisk) { withWindowsFromDisk(sourceDisk.id()); if (sourceDisk.osType() != null) { this.withOSType(sourceDisk.osType()); } return this; } @Override public SnapshotImpl withWindowsFromSnapshot(String sourceSnapshotId) { this .innerModel() .withOsType(OperatingSystemTypes.WINDOWS) .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(sourceSnapshotId); return this; } @Override public SnapshotImpl withWindowsFromSnapshot(Snapshot sourceSnapshot) { withWindowsFromSnapshot(sourceSnapshot.id()); if (sourceSnapshot.osType() != null) { this.withOSType(sourceSnapshot.osType()); } this.withSku(sourceSnapshot.skuType()); return this; } @Override public SnapshotImpl withDataFromVhd(String vhdUrl) { return withDataFromVhd(vhdUrl, constructStorageAccountId(vhdUrl)); } @Override public SnapshotImpl withDataFromVhd(String vhdUrl, String storageAccountId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.IMPORT) .withSourceUri(vhdUrl) .withStorageAccountId(storageAccountId); return this; } @Override public SnapshotImpl withDataFromSnapshot(String snapshotId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(snapshotId); return this; } @Override public SnapshotImpl withDataFromSnapshot(Snapshot snapshot) { return withDataFromSnapshot(snapshot.id()); } @Override public SnapshotImpl withCopyStart() { this.innerModel() .creationData() .withCreateOption(DiskCreateOption.COPY_START); return this; } @Override public SnapshotImpl withDataFromDisk(String managedDiskId) { this .innerModel() .withCreationData(new CreationData()) .creationData() .withCreateOption(DiskCreateOption.COPY) .withSourceResourceId(managedDiskId); return this; } @Override public SnapshotImpl withDataFromDisk(Disk managedDisk) { return withDataFromDisk(managedDisk.id()).withOSType(managedDisk.osType()); } @Override public SnapshotImpl withSizeInGB(int sizeInGB) { this.innerModel().withDiskSizeGB(sizeInGB); return this; } @Override public SnapshotImpl withIncremental(boolean enabled) { this.innerModel().withIncremental(enabled); return this; } @Override public SnapshotImpl withOSType(OperatingSystemTypes osType) { this.innerModel().withOsType(osType); return this; } @Override public SnapshotImpl withSku(SnapshotSkuType sku) { this.innerModel().withSku(new SnapshotSku().withName(sku.accountType())); return this; } @Override public Mono<Snapshot> createResourceAsync() { return this .manager() .serviceClient() .getSnapshots() .createOrUpdateAsync(resourceGroupName(), name(), this.innerModel()) .map(innerToFluentMap(this)); } @Override protected Mono<SnapshotInner> getInnerAsync() { return this .manager() .serviceClient() .getSnapshots() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } private String constructStorageAccountId(String vhdUrl) { try { return ResourceUtils .constructResourceId( this.manager().subscriptionId(), resourceGroupName(), "Microsoft.Storage", "storageAccounts", vhdUrl.split("\\.")[0].replace("https: ""); } catch (RuntimeException ex) { throw logger .logExceptionAsError( new IllegalArgumentException(String.format("%s is not valid URI of a blob to import.", vhdUrl))); } } }
Upgrade the checkstyle version and found it keeps failing the checkstyle rule in this PR
public boolean isPrivateIPAddressInNetwork(String ipAddress) { IpAddressAvailabilityResultInner result = checkIPAvailability(ipAddress); return result != null; }
return result != null;
public boolean isPrivateIPAddressInNetwork(String ipAddress) { IpAddressAvailabilityResultInner result = checkIPAvailability(ipAddress); return result != null; }
class NetworkImpl extends GroupableParentResourceWithTagsImpl<Network, VirtualNetworkInner, NetworkImpl, NetworkManager> implements Network, Network.Definition, Network.Update { private final ClientLogger logger = new ClientLogger(getClass()); private Map<String, Subnet> subnets; private NetworkPeeringsImpl peerings; private Creatable<DdosProtectionPlan> ddosProtectionPlanCreatable; NetworkImpl(String name, final VirtualNetworkInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected void initializeChildrenFromInner() { this.subnets = new TreeMap<>(); List<SubnetInner> inners = this.innerModel().subnets(); if (inners != null) { for (SubnetInner inner : inners) { SubnetImpl subnet = new SubnetImpl(inner, this); this.subnets.put(inner.name(), subnet); } } this.peerings = new NetworkPeeringsImpl(this); } @Override public Mono<Network> refreshAsync() { return super .refreshAsync() .map( network -> { NetworkImpl impl = (NetworkImpl) network; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<VirtualNetworkInner> getInnerAsync() { return this .manager() .serviceClient() .getVirtualNetworks() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<VirtualNetworkInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getVirtualNetworks() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override public boolean isPrivateIPAddressAvailable(String ipAddress) { IpAddressAvailabilityResultInner result = checkIPAvailability(ipAddress); return (result != null) ? result.available() : false; } @Override private IpAddressAvailabilityResultInner checkIPAvailability(String ipAddress) { if (ipAddress == null) { return null; } IpAddressAvailabilityResultInner result = null; try { result = this .manager() .serviceClient() .getVirtualNetworks() .checkIpAddressAvailability(this.resourceGroupName(), this.name(), ipAddress); } catch (ManagementException e) { if (!e.getValue().getCode().equalsIgnoreCase("PrivateIPAddressNotInAnySubnet")) { throw logger.logExceptionAsError(e); } } return result; } NetworkImpl withSubnet(SubnetImpl subnet) { this.subnets.put(subnet.name(), subnet); return this; } @Override public NetworkImpl withDnsServer(String ipAddress) { if (this.innerModel().dhcpOptions() == null) { this.innerModel().withDhcpOptions(new DhcpOptions()); } if (this.innerModel().dhcpOptions().dnsServers() == null) { this.innerModel().dhcpOptions().withDnsServers(new ArrayList<String>()); } this.innerModel().dhcpOptions().dnsServers().add(ipAddress); return this; } @Override public NetworkImpl withSubnet(String name, String cidr) { return this.defineSubnet(name).withAddressPrefix(cidr).attach(); } @Override public NetworkImpl withSubnets(Map<String, String> nameCidrPairs) { this.subnets.clear(); for (Entry<String, String> pair : nameCidrPairs.entrySet()) { this.withSubnet(pair.getKey(), pair.getValue()); } return this; } @Override public NetworkImpl withoutSubnet(String name) { this.subnets.remove(name); return this; } @Override public NetworkImpl withAddressSpace(String cidr) { if (this.innerModel().addressSpace() == null) { this.innerModel().withAddressSpace(new AddressSpace()); } if (this.innerModel().addressSpace().addressPrefixes() == null) { this.innerModel().addressSpace().withAddressPrefixes(new ArrayList<String>()); } this.innerModel().addressSpace().addressPrefixes().add(cidr); return this; } @Override public SubnetImpl defineSubnet(String name) { SubnetInner inner = new SubnetInner().withName(name); return new SubnetImpl(inner, this); } @Override public NetworkImpl withoutAddressSpace(String cidr) { if (cidr != null && this.innerModel().addressSpace() != null && this.innerModel().addressSpace().addressPrefixes() != null) { this.innerModel().addressSpace().addressPrefixes().remove(cidr); } return this; } @Override public List<String> addressSpaces() { List<String> addressSpaces = new ArrayList<String>(); if (this.innerModel().addressSpace() == null) { return Collections.unmodifiableList(addressSpaces); } else if (this.innerModel().addressSpace().addressPrefixes() == null) { return Collections.unmodifiableList(addressSpaces); } else { return Collections.unmodifiableList(this.innerModel().addressSpace().addressPrefixes()); } } @Override public List<String> dnsServerIPs() { List<String> ips = new ArrayList<String>(); if (this.innerModel().dhcpOptions() == null) { return Collections.unmodifiableList(ips); } else if (this.innerModel().dhcpOptions().dnsServers() == null) { return Collections.unmodifiableList(ips); } else { return this.innerModel().dhcpOptions().dnsServers(); } } @Override public Map<String, Subnet> subnets() { return Collections.unmodifiableMap(this.subnets); } @Override protected void beforeCreating() { if (this.addressSpaces().size() == 0) { this.withAddressSpace("10.0.0.0/16"); } if (isInCreateMode()) { if (this.subnets.size() == 0) { this.withSubnet("subnet1", this.addressSpaces().get(0)); } } this.innerModel().withSubnets(innersFromWrappers(this.subnets.values())); } @Override public SubnetImpl updateSubnet(String name) { return (SubnetImpl) this.subnets.get(name); } @Override protected Mono<VirtualNetworkInner> createInner() { if (ddosProtectionPlanCreatable != null && this.taskResult(ddosProtectionPlanCreatable.key()) != null) { DdosProtectionPlan ddosProtectionPlan = this.<DdosProtectionPlan>taskResult(ddosProtectionPlanCreatable.key()); withExistingDdosProtectionPlan(ddosProtectionPlan.id()); } return this .manager() .serviceClient() .getVirtualNetworks() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map( virtualNetworkInner -> { NetworkImpl.this.ddosProtectionPlanCreatable = null; return virtualNetworkInner; }); } @Override public NetworkPeerings peerings() { return this.peerings; } @Override public boolean isDdosProtectionEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableDdosProtection()); } @Override public boolean isVmProtectionEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableVmProtection()); } @Override public String ddosProtectionPlanId() { return innerModel().ddosProtectionPlan() == null ? null : innerModel().ddosProtectionPlan().id(); } @Override public NetworkImpl withNewDdosProtectionPlan() { innerModel().withEnableDdosProtection(true); DdosProtectionPlan.DefinitionStages.WithGroup ddosProtectionPlanWithGroup = manager() .ddosProtectionPlans() .define(this.manager().resourceManager().internalContext().randomResourceName(name(), 20)) .withRegion(region()); if (super.creatableGroup != null && isInCreateMode()) { ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withNewResourceGroup(super.creatableGroup); } else { ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withExistingResourceGroup(resourceGroupName()); } this.addDependency(ddosProtectionPlanCreatable); return this; } @Override public NetworkImpl withExistingDdosProtectionPlan(String planId) { innerModel().withEnableDdosProtection(true).withDdosProtectionPlan(new SubResource().withId(planId)); return this; } @Override public NetworkImpl withoutDdosProtectionPlan() { innerModel().withEnableDdosProtection(false).withDdosProtectionPlan(null); return this; } @Override public NetworkImpl withVmProtection() { innerModel().withEnableVmProtection(true); return this; } @Override public NetworkImpl withoutVmProtection() { innerModel().withEnableVmProtection(false); return this; } }
class NetworkImpl extends GroupableParentResourceWithTagsImpl<Network, VirtualNetworkInner, NetworkImpl, NetworkManager> implements Network, Network.Definition, Network.Update { private final ClientLogger logger = new ClientLogger(getClass()); private Map<String, Subnet> subnets; private NetworkPeeringsImpl peerings; private Creatable<DdosProtectionPlan> ddosProtectionPlanCreatable; NetworkImpl(String name, final VirtualNetworkInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected void initializeChildrenFromInner() { this.subnets = new TreeMap<>(); List<SubnetInner> inners = this.innerModel().subnets(); if (inners != null) { for (SubnetInner inner : inners) { SubnetImpl subnet = new SubnetImpl(inner, this); this.subnets.put(inner.name(), subnet); } } this.peerings = new NetworkPeeringsImpl(this); } @Override public Mono<Network> refreshAsync() { return super .refreshAsync() .map( network -> { NetworkImpl impl = (NetworkImpl) network; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<VirtualNetworkInner> getInnerAsync() { return this .manager() .serviceClient() .getVirtualNetworks() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<VirtualNetworkInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getVirtualNetworks() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override public boolean isPrivateIPAddressAvailable(String ipAddress) { IpAddressAvailabilityResultInner result = checkIPAvailability(ipAddress); return (result != null) ? result.available() : false; } @Override private IpAddressAvailabilityResultInner checkIPAvailability(String ipAddress) { if (ipAddress == null) { return null; } IpAddressAvailabilityResultInner result = null; try { result = this .manager() .serviceClient() .getVirtualNetworks() .checkIpAddressAvailability(this.resourceGroupName(), this.name(), ipAddress); } catch (ManagementException e) { if (!e.getValue().getCode().equalsIgnoreCase("PrivateIPAddressNotInAnySubnet")) { throw logger.logExceptionAsError(e); } } return result; } NetworkImpl withSubnet(SubnetImpl subnet) { this.subnets.put(subnet.name(), subnet); return this; } @Override public NetworkImpl withDnsServer(String ipAddress) { if (this.innerModel().dhcpOptions() == null) { this.innerModel().withDhcpOptions(new DhcpOptions()); } if (this.innerModel().dhcpOptions().dnsServers() == null) { this.innerModel().dhcpOptions().withDnsServers(new ArrayList<String>()); } this.innerModel().dhcpOptions().dnsServers().add(ipAddress); return this; } @Override public NetworkImpl withSubnet(String name, String cidr) { return this.defineSubnet(name).withAddressPrefix(cidr).attach(); } @Override public NetworkImpl withSubnets(Map<String, String> nameCidrPairs) { this.subnets.clear(); for (Entry<String, String> pair : nameCidrPairs.entrySet()) { this.withSubnet(pair.getKey(), pair.getValue()); } return this; } @Override public NetworkImpl withoutSubnet(String name) { this.subnets.remove(name); return this; } @Override public NetworkImpl withAddressSpace(String cidr) { if (this.innerModel().addressSpace() == null) { this.innerModel().withAddressSpace(new AddressSpace()); } if (this.innerModel().addressSpace().addressPrefixes() == null) { this.innerModel().addressSpace().withAddressPrefixes(new ArrayList<String>()); } this.innerModel().addressSpace().addressPrefixes().add(cidr); return this; } @Override public SubnetImpl defineSubnet(String name) { SubnetInner inner = new SubnetInner().withName(name); return new SubnetImpl(inner, this); } @Override public NetworkImpl withoutAddressSpace(String cidr) { if (cidr != null && this.innerModel().addressSpace() != null && this.innerModel().addressSpace().addressPrefixes() != null) { this.innerModel().addressSpace().addressPrefixes().remove(cidr); } return this; } @Override public List<String> addressSpaces() { List<String> addressSpaces = new ArrayList<String>(); if (this.innerModel().addressSpace() == null) { return Collections.unmodifiableList(addressSpaces); } else if (this.innerModel().addressSpace().addressPrefixes() == null) { return Collections.unmodifiableList(addressSpaces); } else { return Collections.unmodifiableList(this.innerModel().addressSpace().addressPrefixes()); } } @Override public List<String> dnsServerIPs() { List<String> ips = new ArrayList<String>(); if (this.innerModel().dhcpOptions() == null) { return Collections.unmodifiableList(ips); } else if (this.innerModel().dhcpOptions().dnsServers() == null) { return Collections.unmodifiableList(ips); } else { return this.innerModel().dhcpOptions().dnsServers(); } } @Override public Map<String, Subnet> subnets() { return Collections.unmodifiableMap(this.subnets); } @Override protected void beforeCreating() { if (this.addressSpaces().size() == 0) { this.withAddressSpace("10.0.0.0/16"); } if (isInCreateMode()) { if (this.subnets.size() == 0) { this.withSubnet("subnet1", this.addressSpaces().get(0)); } } this.innerModel().withSubnets(innersFromWrappers(this.subnets.values())); } @Override public SubnetImpl updateSubnet(String name) { return (SubnetImpl) this.subnets.get(name); } @Override protected Mono<VirtualNetworkInner> createInner() { if (ddosProtectionPlanCreatable != null && this.taskResult(ddosProtectionPlanCreatable.key()) != null) { DdosProtectionPlan ddosProtectionPlan = this.<DdosProtectionPlan>taskResult(ddosProtectionPlanCreatable.key()); withExistingDdosProtectionPlan(ddosProtectionPlan.id()); } return this .manager() .serviceClient() .getVirtualNetworks() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map( virtualNetworkInner -> { NetworkImpl.this.ddosProtectionPlanCreatable = null; return virtualNetworkInner; }); } @Override public NetworkPeerings peerings() { return this.peerings; } @Override public boolean isDdosProtectionEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableDdosProtection()); } @Override public boolean isVmProtectionEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableVmProtection()); } @Override public String ddosProtectionPlanId() { return innerModel().ddosProtectionPlan() == null ? null : innerModel().ddosProtectionPlan().id(); } @Override public NetworkImpl withNewDdosProtectionPlan() { innerModel().withEnableDdosProtection(true); DdosProtectionPlan.DefinitionStages.WithGroup ddosProtectionPlanWithGroup = manager() .ddosProtectionPlans() .define(this.manager().resourceManager().internalContext().randomResourceName(name(), 20)) .withRegion(region()); if (super.creatableGroup != null && isInCreateMode()) { ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withNewResourceGroup(super.creatableGroup); } else { ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withExistingResourceGroup(resourceGroupName()); } this.addDependency(ddosProtectionPlanCreatable); return this; } @Override public NetworkImpl withExistingDdosProtectionPlan(String planId) { innerModel().withEnableDdosProtection(true).withDdosProtectionPlan(new SubResource().withId(planId)); return this; } @Override public NetworkImpl withoutDdosProtectionPlan() { innerModel().withEnableDdosProtection(false).withDdosProtectionPlan(null); return this; } @Override public NetworkImpl withVmProtection() { innerModel().withEnableVmProtection(true); return this; } @Override public NetworkImpl withoutVmProtection() { innerModel().withEnableVmProtection(false); return this; } }
so the idea here is that when this Mono got cancelled, we also cancel the record -> but then I think I should also change the logic around metrics capturing? is there any need to record the response length size for cancelled requests? should I use a different timer? (maybe requests.cancelled.xxx) ``` public void markComplete(RntbdRequestRecord requestRecord) { requestRecord.stop(this.requests, requestRecord.isCompletedExceptionally() ? this.responseErrors : this.responseSuccesses); this.requestSize.record(requestRecord.requestLength()); this.responseSize.record(requestRecord.responseLength()); } ```
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null addressUri"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, addressUri); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); return Mono.fromFuture(record).map(storeResponse -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } RequestTimeline timeline = record.takeTimelineSnapshot(); storeResponse.setRequestTimeline(timeline); storeResponse.setEndpointStatistics(record.serviceEndpointStatistics()); storeResponse.setRntbdResponseLength(record.responseLength()); storeResponse.setRntbdRequestLength(record.requestLength()); storeResponse.setRequestPayloadLength(request.getContentLength()); storeResponse.setRntbdChannelTaskQueueSize(record.channelTaskQueueLength()); storeResponse.setRntbdPendingRequestSize(record.pendingRequestQueueSize()); if (this.channelAcquisitionContextEnabled) { storeResponse.setChannelAcquisitionTimeline(record.getChannelAcquisitionTimeline()); } return storeResponse; }).onErrorMap(throwable -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address, error instanceof Exception ? (Exception) error : new RuntimeException(error)); } assert error instanceof CosmosException; CosmosException cosmosException = (CosmosException) error; BridgeInternal.setServiceEndpointStatistics(cosmosException, record.serviceEndpointStatistics()); BridgeInternal.setRntbdRequestLength(cosmosException, record.requestLength()); BridgeInternal.setRntbdResponseLength(cosmosException, record.responseLength()); BridgeInternal.setRequestBodyLength(cosmosException, request.getContentLength()); BridgeInternal.setRequestTimeline(cosmosException, record.takeTimelineSnapshot()); BridgeInternal.setRntbdPendingRequestQueueSize(cosmosException, record.pendingRequestQueueSize()); BridgeInternal.setChannelTaskQueueSize(cosmosException, record.channelTaskQueueLength()); BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted()); if (this.channelAcquisitionContextEnabled) { BridgeInternal.setChannelAcquisitionTimeline(cosmosException, record.getChannelAcquisitionTimeline()); } return cosmosException; }).contextWrite(reactorContext); }
return Mono.fromFuture(record).map(storeResponse -> {
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null addressUri"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, addressUri); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); return Mono.fromFuture(record).map(storeResponse -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } RequestTimeline timeline = record.takeTimelineSnapshot(); storeResponse.setRequestTimeline(timeline); storeResponse.setEndpointStatistics(record.serviceEndpointStatistics()); storeResponse.setRntbdResponseLength(record.responseLength()); storeResponse.setRntbdRequestLength(record.requestLength()); storeResponse.setRequestPayloadLength(request.getContentLength()); storeResponse.setRntbdChannelTaskQueueSize(record.channelTaskQueueLength()); storeResponse.setRntbdPendingRequestSize(record.pendingRequestQueueSize()); if (this.channelAcquisitionContextEnabled) { storeResponse.setChannelAcquisitionTimeline(record.getChannelAcquisitionTimeline()); } return storeResponse; }).onErrorMap(throwable -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); if (!(error instanceof CancellationException)) { reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); } error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address, error instanceof Exception ? (Exception) error : new RuntimeException(error)); } assert error instanceof CosmosException; CosmosException cosmosException = (CosmosException) error; BridgeInternal.setServiceEndpointStatistics(cosmosException, record.serviceEndpointStatistics()); BridgeInternal.setRntbdRequestLength(cosmosException, record.requestLength()); BridgeInternal.setRntbdResponseLength(cosmosException, record.responseLength()); BridgeInternal.setRequestBodyLength(cosmosException, request.getContentLength()); BridgeInternal.setRequestTimeline(cosmosException, record.takeTimelineSnapshot()); BridgeInternal.setRntbdPendingRequestQueueSize(cosmosException, record.pendingRequestQueueSize()); BridgeInternal.setChannelTaskQueueSize(cosmosException, record.channelTaskQueueLength()); BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted()); if (this.channelAcquisitionContextEnabled) { BridgeInternal.setChannelAcquisitionTimeline(cosmosException, record.getChannelAcquisitionTimeline()); } return cosmosException; }).doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } record.cancel(true); }).contextWrite(reactorContext); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * NOTE: This context key name has been copied from {link Hooks * not exposed as public Api but package internal only * * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; private boolean channelAcquisitionContextEnabled; private final GlobalEndpointManager globalEndpointManager; /** * Initializes a newly created {@linkplain RntbdTransportClient} object. * * @param configs A {@link Configs} instance containing the {@link SslContext} to be used. * @param connectionPolicy The {@linkplain ConnectionPolicy connection policy} to be applied. * @param userAgent The {@linkplain UserAgentContainer user agent} identifying. * @param addressResolver The address resolver to be used for connection endpoint rediscovery, if connection * endpoint rediscovery is enabled by {@code connectionPolicy}. */ public RntbdTransportClient( final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this( new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext(), addressResolver, clientTelemetry, globalEndpointManager); } RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.globalEndpointManager = null; } RntbdTransportClient( final Options options, final SslContext sslContext, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this.endpointProvider = new RntbdServiceEndpoint.Provider( this, options, checkNotNull(sslContext, "expected non-null sslContext"), addressResolver, clientTelemetry); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.channelAcquisitionContextEnabled = options.channelAcquisitionContextEnabled; this.globalEndpointManager = globalEndpointManager; } /** * {@code true} if this {@linkplain RntbdTransportClient client} is closed. * * @return {@code true} if this {@linkplain RntbdTransportClient client} is closed; {@code false} otherwise. */ public boolean isClosed() { return this.closed.get(); } /** * Closes this {@linkplain RntbdTransportClient client} and releases all resources associated with it. */ @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } @Override protected GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } /** * The number of {@linkplain RntbdEndpoint endpoints} allocated to this {@linkplain RntbdTransportClient client}. * * @return The number of {@linkplain RntbdEndpoint endpoints} associated with this {@linkplain RntbdTransportClient * client}. */ public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } /** * The integer identity of this {@linkplain RntbdTransportClient client}. * <p> * Clients are numbered sequentially based on the order in which they are initialized. * * @return The integer identity of this {@linkplain RntbdTransportClient client}. */ public long id() { return this.id; } /** * Issues a Direct TCP request to the specified Cosmos service address asynchronously. * * @param addressUri A Cosmos service address. * @param request The {@linkplain RxDocumentServiceRequest request} to issue. * * @return A {@link Mono} of type {@link StoreResponse} that will complete when the Direct TCP request completes. * I shI * @throws TransportException if this {@linkplain RntbdTransportClient client} is closed. */ @Override @Override public Mono<OpenConnectionResponse> openConnection(Uri addressUri) { checkNotNull(addressUri, "Argument 'addressUri' should not be null"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdEndpoint endpoint = this.endpointProvider.get(address); return Mono.fromFuture(endpoint.openConnection(addressUri)); } /** * The key-value pair used to classify and drill into metrics produced by this {@linkplain RntbdTransportClient * client}. * * @return The key-value pair used to classify and drill into metrics collected by this {@linkplain * RntbdTransportClient client}. */ public Tag tag() { return this.tag; } @Override public String toString() { return RntbdObjectMapper.toString(this); } private static Tag tag(long id) { return Tag.of(TAG_NAME, Strings.padStart(Long.toHexString(id).toUpperCase(Locale.ROOT), 4, '0')); } private void throwIfClosed() { if (this.closed.get()) { throw new TransportException(lenientFormat("%s is closed", this), null); } } public static final class Options { private static final int DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 10_000; @JsonProperty() private final int bufferPageSize; @JsonProperty() private final Duration connectionAcquisitionTimeout; @JsonProperty() private final boolean connectionEndpointRediscoveryEnabled; @JsonProperty() private final Duration connectTimeout; @JsonProperty() private final Duration idleChannelTimeout; @JsonProperty() private final Duration idleChannelTimerResolution; @JsonProperty() private final Duration idleEndpointTimeout; @JsonProperty() private final int maxBufferCapacity; @JsonProperty() private final int maxChannelsPerEndpoint; @JsonProperty() private final int maxRequestsPerChannel; @JsonProperty() private final int maxConcurrentRequestsPerEndpointOverride; @JsonProperty() private final Duration receiveHangDetectionTime; @JsonProperty() private final Duration tcpNetworkRequestTimeout; @JsonProperty() private final Duration requestTimerResolution; @JsonProperty() private final Duration sendHangDetectionTime; @JsonProperty() private final Duration shutdownTimeout; @JsonProperty() private final int threadCount; @JsonIgnore() private final UserAgentContainer userAgent; @JsonProperty() private final boolean channelAcquisitionContextEnabled; @JsonProperty() private final int ioThreadPriority; @JsonProperty() private final int tcpKeepIntvl; @JsonProperty() private final int tcpKeepIdle; @JsonProperty() private final boolean preferTcpNative; @JsonProperty() private final Duration sslHandshakeTimeoutMinDuration; @JsonCreator private Options() { this(ConnectionPolicy.getDefaultPolicy()); } private Options(final Builder builder) { this.bufferPageSize = builder.bufferPageSize; this.connectionAcquisitionTimeout = builder.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = builder.connectionEndpointRediscoveryEnabled; this.idleChannelTimeout = builder.idleChannelTimeout; this.idleChannelTimerResolution = builder.idleChannelTimerResolution; this.idleEndpointTimeout = builder.idleEndpointTimeout; this.maxBufferCapacity = builder.maxBufferCapacity; this.maxChannelsPerEndpoint = builder.maxChannelsPerEndpoint; this.maxRequestsPerChannel = builder.maxRequestsPerChannel; this.maxConcurrentRequestsPerEndpointOverride = builder.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = builder.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = builder.tcpNetworkRequestTimeout; this.requestTimerResolution = builder.requestTimerResolution; this.sendHangDetectionTime = builder.sendHangDetectionTime; this.shutdownTimeout = builder.shutdownTimeout; this.threadCount = builder.threadCount; this.userAgent = builder.userAgent; this.channelAcquisitionContextEnabled = builder.channelAcquisitionContextEnabled; this.ioThreadPriority = builder.ioThreadPriority; this.tcpKeepIntvl = builder.tcpKeepIntvl; this.tcpKeepIdle = builder.tcpKeepIdle; this.preferTcpNative = builder.preferTcpNative; this.sslHandshakeTimeoutMinDuration = builder.sslHandshakeTimeoutMinDuration; this.connectTimeout = builder.connectTimeout == null ? builder.tcpNetworkRequestTimeout : builder.connectTimeout; } private Options(final ConnectionPolicy connectionPolicy) { this.bufferPageSize = 8192; this.connectionAcquisitionTimeout = Duration.ofSeconds(5L); this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = Duration.ofMillis(100); this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = 8192 << 10; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = -1; this.receiveHangDetectionTime = Duration.ofSeconds(65L); this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = Duration.ofMillis(100L); this.sendHangDetectionTime = Duration.ofSeconds(10L); this.shutdownTimeout = Duration.ofSeconds(15L); this.threadCount = connectionPolicy.getIoThreadCountPerCoreFactor() * Runtime.getRuntime().availableProcessors(); this.userAgent = new UserAgentContainer(); this.channelAcquisitionContextEnabled = false; this.ioThreadPriority = connectionPolicy.getIoThreadPriority(); this.tcpKeepIntvl = 1; this.tcpKeepIdle = 30; this.sslHandshakeTimeoutMinDuration = Duration.ofSeconds(5); this.preferTcpNative = true; } public int bufferPageSize() { return this.bufferPageSize; } public Duration connectionAcquisitionTimeout() { return this.connectionAcquisitionTimeout; } public Duration connectTimeout() { return this.connectTimeout; } public Duration idleChannelTimeout() { return this.idleChannelTimeout; } public Duration idleChannelTimerResolution() { return this.idleChannelTimerResolution; } public Duration idleEndpointTimeout() { return this.idleEndpointTimeout; } public boolean isConnectionEndpointRediscoveryEnabled() { return this.connectionEndpointRediscoveryEnabled; } public int maxBufferCapacity() { return this.maxBufferCapacity; } public int maxChannelsPerEndpoint() { return this.maxChannelsPerEndpoint; } public int maxRequestsPerChannel() { return this.maxRequestsPerChannel; } public int maxConcurrentRequestsPerEndpoint() { if (this.maxConcurrentRequestsPerEndpointOverride > 0) { return maxConcurrentRequestsPerEndpointOverride; } return Math.max( DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, this.maxChannelsPerEndpoint * this.maxRequestsPerChannel); } public Duration receiveHangDetectionTime() { return this.receiveHangDetectionTime; } public Duration tcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } public Duration requestTimerResolution() { return this.requestTimerResolution; } public Duration sendHangDetectionTime() { return this.sendHangDetectionTime; } public Duration shutdownTimeout() { return this.shutdownTimeout; } public int threadCount() { return this.threadCount; } public UserAgentContainer userAgent() { return this.userAgent; } public boolean isChannelAcquisitionContextEnabled() { return this.channelAcquisitionContextEnabled; } public int ioThreadPriority() { checkArgument( this.ioThreadPriority >= Thread.MIN_PRIORITY && this.ioThreadPriority <= Thread.MAX_PRIORITY, "Expect ioThread priority between [%s, %s]", Thread.MIN_PRIORITY, Thread.MAX_PRIORITY); return this.ioThreadPriority; } public int tcpKeepIntvl() { return this.tcpKeepIntvl; } public int tcpKeepIdle() { return this.tcpKeepIdle; } public boolean preferTcpNative() { return this.preferTcpNative; } public long sslHandshakeTimeoutInMillis() { return Math.max(this.sslHandshakeTimeoutMinDuration.toMillis(), this.connectTimeout.toMillis()); } @Override public String toString() { return RntbdObjectMapper.toJson(this); } public String toDiagnosticsString() { return lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)", connectTimeout, tcpNetworkRequestTimeout, idleChannelTimeout, idleEndpointTimeout, maxChannelsPerEndpoint, maxRequestsPerChannel, connectionEndpointRediscoveryEnabled); } /** * A builder for constructing {@link Options} instances. * * <h3>Using system properties to set the default {@link Options} used by an {@link Builder}</h3> * <p> * A default options instance is created when the {@link Builder} class is initialized. This instance specifies * the default options used by every {@link Builder} instance. In priority order the default options instance * is created from: * <ol> * <li>The JSON value of system property {@code azure.cosmos.directTcp.defaultOptions}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptions={\"maxChannelsPerEndpoint\":5,\"maxRequestsPerChannel\":30}}</pre> * </li> * <li>The contents of the JSON file located by system property {@code azure.cosmos.directTcp * .defaultOptionsFile}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file}</pre> * </li> * <li>The contents of JSON resource file {@code azure.cosmos.directTcp.defaultOptions.json}. * <p>Specifically, the resource file is read from this stream: * <pre>{@code RntbdTransportClient.class.getClassLoader().getResourceAsStream("azure.cosmos.directTcp.defaultOptions.json")}</pre> * <p>Example: <pre>{@code { * "bufferPageSize": 8192, * "connectionEndpointRediscoveryEnabled": false, * "connectTimeout": "PT5S", * "idleChannelTimeout": "PT0S", * "idleEndpointTimeout": "PT1H", * "maxBufferCapacity": 8388608, * "maxChannelsPerEndpoint": 130, * "maxRequestsPerChannel": 30, * "maxConcurrentRequestsPerEndpointOverride": -1, * "receiveHangDetectionTime": "PT1M5S", * "requestTimeout": "PT5S", * "requestTimerResolution": "PT100MS", * "sendHangDetectionTime": "PT10S", * "shutdownTimeout": "PT15S", * "threadCount": 16 * }}</pre> * </li> * </ol> * <p>JSON value errors are logged and then ignored. If none of the above values are available or all available * values are in error, the default options instance is created from the private parameterless constructor for * {@link Options}. */ @SuppressWarnings("UnusedReturnValue") public static class Builder { private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions"; private static final Options DEFAULT_OPTIONS; static { Options options = null; try { final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME); if (string != null) { try { options = RntbdObjectMapper.readValue(string, Options.class); } catch (IOException error) { logger.error("failed to parse default Direct TCP options {} due to ", string, error); } } if (options == null) { final String path = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME + "File"); if (path != null) { try { options = RntbdObjectMapper.readValue(new File(path), Options.class); } catch (IOException error) { logger.error("failed to load default Direct TCP options from {} due to ", path, error); } } } if (options == null) { final ClassLoader loader = RntbdTransportClient.class.getClassLoader(); final String name = DEFAULT_OPTIONS_PROPERTY_NAME + ".json"; try (InputStream stream = loader.getResourceAsStream(name)) { if (stream != null) { options = RntbdObjectMapper.readValue(stream, Options.class); } } catch (IOException error) { logger.error("failed to load Direct TCP options from resource {} due to ", name, error); } } } finally { if (options == null) { logger.info("Using default Direct TCP options: {}", DEFAULT_OPTIONS_PROPERTY_NAME); DEFAULT_OPTIONS = new Options(ConnectionPolicy.getDefaultPolicy()); } else { logger.info("Updated default Direct TCP options from system property {}: {}", DEFAULT_OPTIONS_PROPERTY_NAME, options); DEFAULT_OPTIONS = options; } } } private int bufferPageSize; private Duration connectionAcquisitionTimeout; private boolean connectionEndpointRediscoveryEnabled; private Duration connectTimeout; private Duration idleChannelTimeout; private Duration idleChannelTimerResolution; private Duration idleEndpointTimeout; private int maxBufferCapacity; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; private int maxConcurrentRequestsPerEndpointOverride; private Duration receiveHangDetectionTime; private Duration tcpNetworkRequestTimeout; private Duration requestTimerResolution; private Duration sendHangDetectionTime; private Duration shutdownTimeout; private int threadCount; private UserAgentContainer userAgent; private boolean channelAcquisitionContextEnabled; private int ioThreadPriority; private int tcpKeepIntvl; private int tcpKeepIdle; private boolean preferTcpNative; private Duration sslHandshakeTimeoutMinDuration; public Builder(ConnectionPolicy connectionPolicy) { this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize; this.connectionAcquisitionTimeout = DEFAULT_OPTIONS.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = DEFAULT_OPTIONS.idleChannelTimerResolution; this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = DEFAULT_OPTIONS.maxBufferCapacity; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = DEFAULT_OPTIONS.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = DEFAULT_OPTIONS.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = DEFAULT_OPTIONS.requestTimerResolution; this.sendHangDetectionTime = DEFAULT_OPTIONS.sendHangDetectionTime; this.shutdownTimeout = DEFAULT_OPTIONS.shutdownTimeout; this.threadCount = DEFAULT_OPTIONS.threadCount; this.userAgent = DEFAULT_OPTIONS.userAgent; this.channelAcquisitionContextEnabled = DEFAULT_OPTIONS.channelAcquisitionContextEnabled; this.ioThreadPriority = DEFAULT_OPTIONS.ioThreadPriority; this.tcpKeepIntvl = DEFAULT_OPTIONS.tcpKeepIntvl; this.tcpKeepIdle = DEFAULT_OPTIONS.tcpKeepIdle; this.preferTcpNative = DEFAULT_OPTIONS.preferTcpNative; this.sslHandshakeTimeoutMinDuration = DEFAULT_OPTIONS.sslHandshakeTimeoutMinDuration; } public Builder bufferPageSize(final int value) { checkArgument(value >= 4096 && (value & (value - 1)) == 0, "expected value to be a power of 2 >= 4096, not %s", value); this.bufferPageSize = value; return this; } public Options build() { checkState(this.bufferPageSize <= this.maxBufferCapacity, "expected bufferPageSize (%s) <= maxBufferCapacity (%s)", this.bufferPageSize, this.maxBufferCapacity); return new Options(this); } public Builder connectionAcquisitionTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.connectionAcquisitionTimeout = value.compareTo(Duration.ZERO) < 0 ? Duration.ZERO : value; return this; } public Builder connectionEndpointRediscoveryEnabled(final boolean value) { this.connectionEndpointRediscoveryEnabled = value; return this; } public Builder connectionTimeout(final Duration value) { checkArgument(value == null || value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.connectTimeout = value; return this; } public Builder idleChannelTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.idleChannelTimeout = value; return this; } public Builder idleChannelTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) <= 0, "expected positive value, not %s", value); this.idleChannelTimerResolution = value; return this; } public Builder idleEndpointTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.idleEndpointTimeout = value; return this; } public Builder maxBufferCapacity(final int value) { checkArgument(value > 0 && (value & (value - 1)) == 0, "expected positive value, not %s", value); this.maxBufferCapacity = value; return this; } public Builder maxChannelsPerEndpoint(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxChannelsPerEndpoint = value; return this; } public Builder maxRequestsPerChannel(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxRequestsPerChannel = value; return this; } public Builder maxConcurrentRequestsPerEndpointOverride(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxConcurrentRequestsPerEndpointOverride = value; return this; } public Builder receiveHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.receiveHangDetectionTime = value; return this; } public Builder tcpNetworkRequestTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.tcpNetworkRequestTimeout = value; return this; } public Builder requestTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.requestTimerResolution = value; return this; } public Builder sendHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.sendHangDetectionTime = value; return this; } public Builder shutdownTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.shutdownTimeout = value; return this; } public Builder threadCount(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.threadCount = value; return this; } public Builder userAgent(final UserAgentContainer value) { checkNotNull(value, "expected non-null value"); this.userAgent = value; return this; } } } static final class JsonSerializer extends StdSerializer<RntbdTransportClient> { private static final long serialVersionUID = 1007663695768825670L; JsonSerializer() { super(RntbdTransportClient.class); } @Override public void serialize( final RntbdTransportClient value, final JsonGenerator generator, final SerializerProvider provider ) throws IOException { generator.writeStartObject(); generator.writeNumberField("id", value.id()); generator.writeBooleanField("isClosed", value.isClosed()); generator.writeObjectField("configuration", value.endpointProvider.config()); generator.writeObjectFieldStart("serviceEndpoints"); generator.writeNumberField("count", value.endpointCount()); generator.writeArrayFieldStart("items"); for (final Iterator<RntbdEndpoint> iterator = value.endpointProvider.list().iterator(); iterator.hasNext(); ) { generator.writeObject(iterator.next()); } generator.writeEndArray(); generator.writeEndObject(); generator.writeEndObject(); } } }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * NOTE: This context key name has been copied from {link Hooks * not exposed as public Api but package internal only * * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; private boolean channelAcquisitionContextEnabled; private final GlobalEndpointManager globalEndpointManager; /** * Initializes a newly created {@linkplain RntbdTransportClient} object. * * @param configs A {@link Configs} instance containing the {@link SslContext} to be used. * @param connectionPolicy The {@linkplain ConnectionPolicy connection policy} to be applied. * @param userAgent The {@linkplain UserAgentContainer user agent} identifying. * @param addressResolver The address resolver to be used for connection endpoint rediscovery, if connection * endpoint rediscovery is enabled by {@code connectionPolicy}. */ public RntbdTransportClient( final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this( new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext(), addressResolver, clientTelemetry, globalEndpointManager); } RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.globalEndpointManager = null; } RntbdTransportClient( final Options options, final SslContext sslContext, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this.endpointProvider = new RntbdServiceEndpoint.Provider( this, options, checkNotNull(sslContext, "expected non-null sslContext"), addressResolver, clientTelemetry); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.channelAcquisitionContextEnabled = options.channelAcquisitionContextEnabled; this.globalEndpointManager = globalEndpointManager; } /** * {@code true} if this {@linkplain RntbdTransportClient client} is closed. * * @return {@code true} if this {@linkplain RntbdTransportClient client} is closed; {@code false} otherwise. */ public boolean isClosed() { return this.closed.get(); } /** * Closes this {@linkplain RntbdTransportClient client} and releases all resources associated with it. */ @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } @Override protected GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } /** * The number of {@linkplain RntbdEndpoint endpoints} allocated to this {@linkplain RntbdTransportClient client}. * * @return The number of {@linkplain RntbdEndpoint endpoints} associated with this {@linkplain RntbdTransportClient * client}. */ public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } /** * The integer identity of this {@linkplain RntbdTransportClient client}. * <p> * Clients are numbered sequentially based on the order in which they are initialized. * * @return The integer identity of this {@linkplain RntbdTransportClient client}. */ public long id() { return this.id; } /** * Issues a Direct TCP request to the specified Cosmos service address asynchronously. * * @param addressUri A Cosmos service address. * @param request The {@linkplain RxDocumentServiceRequest request} to issue. * * @return A {@link Mono} of type {@link StoreResponse} that will complete when the Direct TCP request completes. * I shI * @throws TransportException if this {@linkplain RntbdTransportClient client} is closed. */ @Override @Override public Mono<OpenConnectionResponse> openConnection(Uri addressUri) { checkNotNull(addressUri, "Argument 'addressUri' should not be null"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdEndpoint endpoint = this.endpointProvider.get(address); return Mono.fromFuture(endpoint.openConnection(addressUri)); } /** * The key-value pair used to classify and drill into metrics produced by this {@linkplain RntbdTransportClient * client}. * * @return The key-value pair used to classify and drill into metrics collected by this {@linkplain * RntbdTransportClient client}. */ public Tag tag() { return this.tag; } @Override public String toString() { return RntbdObjectMapper.toString(this); } private static Tag tag(long id) { return Tag.of(TAG_NAME, Strings.padStart(Long.toHexString(id).toUpperCase(Locale.ROOT), 4, '0')); } private void throwIfClosed() { if (this.closed.get()) { throw new TransportException(lenientFormat("%s is closed", this), null); } } public static final class Options { private static final int DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 10_000; @JsonProperty() private final int bufferPageSize; @JsonProperty() private final Duration connectionAcquisitionTimeout; @JsonProperty() private final boolean connectionEndpointRediscoveryEnabled; @JsonProperty() private final Duration connectTimeout; @JsonProperty() private final Duration idleChannelTimeout; @JsonProperty() private final Duration idleChannelTimerResolution; @JsonProperty() private final Duration idleEndpointTimeout; @JsonProperty() private final int maxBufferCapacity; @JsonProperty() private final int maxChannelsPerEndpoint; @JsonProperty() private final int maxRequestsPerChannel; @JsonProperty() private final int maxConcurrentRequestsPerEndpointOverride; @JsonProperty() private final Duration receiveHangDetectionTime; @JsonProperty() private final Duration tcpNetworkRequestTimeout; @JsonProperty() private final Duration requestTimerResolution; @JsonProperty() private final Duration sendHangDetectionTime; @JsonProperty() private final Duration shutdownTimeout; @JsonProperty() private final int threadCount; @JsonIgnore() private final UserAgentContainer userAgent; @JsonProperty() private final boolean channelAcquisitionContextEnabled; @JsonProperty() private final int ioThreadPriority; @JsonProperty() private final int tcpKeepIntvl; @JsonProperty() private final int tcpKeepIdle; @JsonProperty() private final boolean preferTcpNative; @JsonProperty() private final Duration sslHandshakeTimeoutMinDuration; /** * This property will be used in {@link RntbdClientChannelHealthChecker} to determine whether there is a readHang. * If there is no successful reads for up to receiveHangDetectionTime, and the number of consecutive timeout has also reached this config, * then SDK is going to treat the channel as unhealthy and close it. */ @JsonProperty() private final int transientTimeoutDetectionThreshold; @JsonCreator private Options() { this(ConnectionPolicy.getDefaultPolicy()); } private Options(final Builder builder) { this.bufferPageSize = builder.bufferPageSize; this.connectionAcquisitionTimeout = builder.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = builder.connectionEndpointRediscoveryEnabled; this.idleChannelTimeout = builder.idleChannelTimeout; this.idleChannelTimerResolution = builder.idleChannelTimerResolution; this.idleEndpointTimeout = builder.idleEndpointTimeout; this.maxBufferCapacity = builder.maxBufferCapacity; this.maxChannelsPerEndpoint = builder.maxChannelsPerEndpoint; this.maxRequestsPerChannel = builder.maxRequestsPerChannel; this.maxConcurrentRequestsPerEndpointOverride = builder.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = builder.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = builder.tcpNetworkRequestTimeout; this.requestTimerResolution = builder.requestTimerResolution; this.sendHangDetectionTime = builder.sendHangDetectionTime; this.shutdownTimeout = builder.shutdownTimeout; this.threadCount = builder.threadCount; this.userAgent = builder.userAgent; this.channelAcquisitionContextEnabled = builder.channelAcquisitionContextEnabled; this.ioThreadPriority = builder.ioThreadPriority; this.tcpKeepIntvl = builder.tcpKeepIntvl; this.tcpKeepIdle = builder.tcpKeepIdle; this.preferTcpNative = builder.preferTcpNative; this.sslHandshakeTimeoutMinDuration = builder.sslHandshakeTimeoutMinDuration; this.transientTimeoutDetectionThreshold = builder.transientTimeoutDetectionThreshold; this.connectTimeout = builder.connectTimeout == null ? builder.tcpNetworkRequestTimeout : builder.connectTimeout; } private Options(final ConnectionPolicy connectionPolicy) { this.bufferPageSize = 8192; this.connectionAcquisitionTimeout = Duration.ofSeconds(5L); this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = Duration.ofMillis(100); this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = 8192 << 10; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = -1; this.receiveHangDetectionTime = Duration.ofSeconds(65L); this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = Duration.ofMillis(100L); this.sendHangDetectionTime = Duration.ofSeconds(10L); this.shutdownTimeout = Duration.ofSeconds(15L); this.threadCount = connectionPolicy.getIoThreadCountPerCoreFactor() * Runtime.getRuntime().availableProcessors(); this.userAgent = new UserAgentContainer(); this.channelAcquisitionContextEnabled = false; this.ioThreadPriority = connectionPolicy.getIoThreadPriority(); this.tcpKeepIntvl = 1; this.tcpKeepIdle = 30; this.sslHandshakeTimeoutMinDuration = Duration.ofSeconds(5); this.transientTimeoutDetectionThreshold = 3; this.preferTcpNative = true; } public int bufferPageSize() { return this.bufferPageSize; } public Duration connectionAcquisitionTimeout() { return this.connectionAcquisitionTimeout; } public Duration connectTimeout() { return this.connectTimeout; } public Duration idleChannelTimeout() { return this.idleChannelTimeout; } public Duration idleChannelTimerResolution() { return this.idleChannelTimerResolution; } public Duration idleEndpointTimeout() { return this.idleEndpointTimeout; } public boolean isConnectionEndpointRediscoveryEnabled() { return this.connectionEndpointRediscoveryEnabled; } public int maxBufferCapacity() { return this.maxBufferCapacity; } public int maxChannelsPerEndpoint() { return this.maxChannelsPerEndpoint; } public int maxRequestsPerChannel() { return this.maxRequestsPerChannel; } public int maxConcurrentRequestsPerEndpoint() { if (this.maxConcurrentRequestsPerEndpointOverride > 0) { return maxConcurrentRequestsPerEndpointOverride; } return Math.max( DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, this.maxChannelsPerEndpoint * this.maxRequestsPerChannel); } public Duration receiveHangDetectionTime() { return this.receiveHangDetectionTime; } public Duration tcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } public Duration requestTimerResolution() { return this.requestTimerResolution; } public Duration sendHangDetectionTime() { return this.sendHangDetectionTime; } public Duration shutdownTimeout() { return this.shutdownTimeout; } public int threadCount() { return this.threadCount; } public UserAgentContainer userAgent() { return this.userAgent; } public boolean isChannelAcquisitionContextEnabled() { return this.channelAcquisitionContextEnabled; } public int ioThreadPriority() { checkArgument( this.ioThreadPriority >= Thread.MIN_PRIORITY && this.ioThreadPriority <= Thread.MAX_PRIORITY, "Expect ioThread priority between [%s, %s]", Thread.MIN_PRIORITY, Thread.MAX_PRIORITY); return this.ioThreadPriority; } public int tcpKeepIntvl() { return this.tcpKeepIntvl; } public int tcpKeepIdle() { return this.tcpKeepIdle; } public boolean preferTcpNative() { return this.preferTcpNative; } public long sslHandshakeTimeoutInMillis() { return Math.max(this.sslHandshakeTimeoutMinDuration.toMillis(), this.connectTimeout.toMillis()); } public int transientTimeoutDetectionThreshold() { return this.transientTimeoutDetectionThreshold; } @Override public String toString() { return RntbdObjectMapper.toJson(this); } public String toDiagnosticsString() { return lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)", connectTimeout, tcpNetworkRequestTimeout, idleChannelTimeout, idleEndpointTimeout, maxChannelsPerEndpoint, maxRequestsPerChannel, connectionEndpointRediscoveryEnabled); } /** * A builder for constructing {@link Options} instances. * * <h3>Using system properties to set the default {@link Options} used by an {@link Builder}</h3> * <p> * A default options instance is created when the {@link Builder} class is initialized. This instance specifies * the default options used by every {@link Builder} instance. In priority order the default options instance * is created from: * <ol> * <li>The JSON value of system property {@code azure.cosmos.directTcp.defaultOptions}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptions={\"maxChannelsPerEndpoint\":5,\"maxRequestsPerChannel\":30}}</pre> * </li> * <li>The contents of the JSON file located by system property {@code azure.cosmos.directTcp * .defaultOptionsFile}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file}</pre> * </li> * <li>The contents of JSON resource file {@code azure.cosmos.directTcp.defaultOptions.json}. * <p>Specifically, the resource file is read from this stream: * <pre>{@code RntbdTransportClient.class.getClassLoader().getResourceAsStream("azure.cosmos.directTcp.defaultOptions.json")}</pre> * <p>Example: <pre>{@code { * "bufferPageSize": 8192, * "connectionEndpointRediscoveryEnabled": false, * "connectTimeout": "PT5S", * "idleChannelTimeout": "PT0S", * "idleEndpointTimeout": "PT1H", * "maxBufferCapacity": 8388608, * "maxChannelsPerEndpoint": 130, * "maxRequestsPerChannel": 30, * "maxConcurrentRequestsPerEndpointOverride": -1, * "receiveHangDetectionTime": "PT1M5S", * "requestTimeout": "PT5S", * "requestTimerResolution": "PT100MS", * "sendHangDetectionTime": "PT10S", * "shutdownTimeout": "PT15S", * "threadCount": 16, * "transientTimeoutDetectionThreshold": 3 * }}</pre> * </li> * </ol> * <p>JSON value errors are logged and then ignored. If none of the above values are available or all available * values are in error, the default options instance is created from the private parameterless constructor for * {@link Options}. */ @SuppressWarnings("UnusedReturnValue") public static class Builder { private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions"; private static final Options DEFAULT_OPTIONS; static { Options options = null; try { final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME); if (string != null) { try { options = RntbdObjectMapper.readValue(string, Options.class); } catch (IOException error) { logger.error("failed to parse default Direct TCP options {} due to ", string, error); } } if (options == null) { final String path = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME + "File"); if (path != null) { try { options = RntbdObjectMapper.readValue(new File(path), Options.class); } catch (IOException error) { logger.error("failed to load default Direct TCP options from {} due to ", path, error); } } } if (options == null) { final ClassLoader loader = RntbdTransportClient.class.getClassLoader(); final String name = DEFAULT_OPTIONS_PROPERTY_NAME + ".json"; try (InputStream stream = loader.getResourceAsStream(name)) { if (stream != null) { options = RntbdObjectMapper.readValue(stream, Options.class); } } catch (IOException error) { logger.error("failed to load Direct TCP options from resource {} due to ", name, error); } } } finally { if (options == null) { logger.info("Using default Direct TCP options: {}", DEFAULT_OPTIONS_PROPERTY_NAME); DEFAULT_OPTIONS = new Options(ConnectionPolicy.getDefaultPolicy()); } else { logger.info("Updated default Direct TCP options from system property {}: {}", DEFAULT_OPTIONS_PROPERTY_NAME, options); DEFAULT_OPTIONS = options; } } } private int bufferPageSize; private Duration connectionAcquisitionTimeout; private boolean connectionEndpointRediscoveryEnabled; private Duration connectTimeout; private Duration idleChannelTimeout; private Duration idleChannelTimerResolution; private Duration idleEndpointTimeout; private int maxBufferCapacity; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; private int maxConcurrentRequestsPerEndpointOverride; private Duration receiveHangDetectionTime; private Duration tcpNetworkRequestTimeout; private Duration requestTimerResolution; private Duration sendHangDetectionTime; private Duration shutdownTimeout; private int threadCount; private UserAgentContainer userAgent; private boolean channelAcquisitionContextEnabled; private int ioThreadPriority; private int tcpKeepIntvl; private int tcpKeepIdle; private boolean preferTcpNative; private Duration sslHandshakeTimeoutMinDuration; private int transientTimeoutDetectionThreshold; public Builder(ConnectionPolicy connectionPolicy) { this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize; this.connectionAcquisitionTimeout = DEFAULT_OPTIONS.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = DEFAULT_OPTIONS.idleChannelTimerResolution; this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = DEFAULT_OPTIONS.maxBufferCapacity; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = DEFAULT_OPTIONS.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = DEFAULT_OPTIONS.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = DEFAULT_OPTIONS.requestTimerResolution; this.sendHangDetectionTime = DEFAULT_OPTIONS.sendHangDetectionTime; this.shutdownTimeout = DEFAULT_OPTIONS.shutdownTimeout; this.threadCount = DEFAULT_OPTIONS.threadCount; this.userAgent = DEFAULT_OPTIONS.userAgent; this.channelAcquisitionContextEnabled = DEFAULT_OPTIONS.channelAcquisitionContextEnabled; this.ioThreadPriority = DEFAULT_OPTIONS.ioThreadPriority; this.tcpKeepIntvl = DEFAULT_OPTIONS.tcpKeepIntvl; this.tcpKeepIdle = DEFAULT_OPTIONS.tcpKeepIdle; this.preferTcpNative = DEFAULT_OPTIONS.preferTcpNative; this.sslHandshakeTimeoutMinDuration = DEFAULT_OPTIONS.sslHandshakeTimeoutMinDuration; this.transientTimeoutDetectionThreshold = DEFAULT_OPTIONS.transientTimeoutDetectionThreshold; } public Builder bufferPageSize(final int value) { checkArgument(value >= 4096 && (value & (value - 1)) == 0, "expected value to be a power of 2 >= 4096, not %s", value); this.bufferPageSize = value; return this; } public Options build() { checkState(this.bufferPageSize <= this.maxBufferCapacity, "expected bufferPageSize (%s) <= maxBufferCapacity (%s)", this.bufferPageSize, this.maxBufferCapacity); return new Options(this); } public Builder connectionAcquisitionTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.connectionAcquisitionTimeout = value.compareTo(Duration.ZERO) < 0 ? Duration.ZERO : value; return this; } public Builder connectionEndpointRediscoveryEnabled(final boolean value) { this.connectionEndpointRediscoveryEnabled = value; return this; } public Builder connectionTimeout(final Duration value) { checkArgument(value == null || value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.connectTimeout = value; return this; } public Builder idleChannelTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.idleChannelTimeout = value; return this; } public Builder idleChannelTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) <= 0, "expected positive value, not %s", value); this.idleChannelTimerResolution = value; return this; } public Builder idleEndpointTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.idleEndpointTimeout = value; return this; } public Builder maxBufferCapacity(final int value) { checkArgument(value > 0 && (value & (value - 1)) == 0, "expected positive value, not %s", value); this.maxBufferCapacity = value; return this; } public Builder maxChannelsPerEndpoint(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxChannelsPerEndpoint = value; return this; } public Builder maxRequestsPerChannel(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxRequestsPerChannel = value; return this; } public Builder maxConcurrentRequestsPerEndpointOverride(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxConcurrentRequestsPerEndpointOverride = value; return this; } public Builder receiveHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.receiveHangDetectionTime = value; return this; } public Builder tcpNetworkRequestTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.tcpNetworkRequestTimeout = value; return this; } public Builder requestTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.requestTimerResolution = value; return this; } public Builder sendHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.sendHangDetectionTime = value; return this; } public Builder shutdownTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.shutdownTimeout = value; return this; } public Builder threadCount(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.threadCount = value; return this; } public Builder userAgent(final UserAgentContainer value) { checkNotNull(value, "expected non-null value"); this.userAgent = value; return this; } } } static final class JsonSerializer extends StdSerializer<RntbdTransportClient> { private static final long serialVersionUID = 1007663695768825670L; JsonSerializer() { super(RntbdTransportClient.class); } @Override public void serialize( final RntbdTransportClient value, final JsonGenerator generator, final SerializerProvider provider ) throws IOException { generator.writeStartObject(); generator.writeNumberField("id", value.id()); generator.writeBooleanField("isClosed", value.isClosed()); generator.writeObjectField("configuration", value.endpointProvider.config()); generator.writeObjectFieldStart("serviceEndpoints"); generator.writeNumberField("count", value.endpointCount()); generator.writeArrayFieldStart("items"); for (final Iterator<RntbdEndpoint> iterator = value.endpointProvider.list().iterator(); iterator.hasNext(); ) { generator.writeObject(iterator.next()); } generator.writeEndArray(); generator.writeEndObject(); generator.writeEndObject(); } } }
No need to report response size for cancelled requests IMO
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null addressUri"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, addressUri); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); return Mono.fromFuture(record).map(storeResponse -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } RequestTimeline timeline = record.takeTimelineSnapshot(); storeResponse.setRequestTimeline(timeline); storeResponse.setEndpointStatistics(record.serviceEndpointStatistics()); storeResponse.setRntbdResponseLength(record.responseLength()); storeResponse.setRntbdRequestLength(record.requestLength()); storeResponse.setRequestPayloadLength(request.getContentLength()); storeResponse.setRntbdChannelTaskQueueSize(record.channelTaskQueueLength()); storeResponse.setRntbdPendingRequestSize(record.pendingRequestQueueSize()); if (this.channelAcquisitionContextEnabled) { storeResponse.setChannelAcquisitionTimeline(record.getChannelAcquisitionTimeline()); } return storeResponse; }).onErrorMap(throwable -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address, error instanceof Exception ? (Exception) error : new RuntimeException(error)); } assert error instanceof CosmosException; CosmosException cosmosException = (CosmosException) error; BridgeInternal.setServiceEndpointStatistics(cosmosException, record.serviceEndpointStatistics()); BridgeInternal.setRntbdRequestLength(cosmosException, record.requestLength()); BridgeInternal.setRntbdResponseLength(cosmosException, record.responseLength()); BridgeInternal.setRequestBodyLength(cosmosException, request.getContentLength()); BridgeInternal.setRequestTimeline(cosmosException, record.takeTimelineSnapshot()); BridgeInternal.setRntbdPendingRequestQueueSize(cosmosException, record.pendingRequestQueueSize()); BridgeInternal.setChannelTaskQueueSize(cosmosException, record.channelTaskQueueLength()); BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted()); if (this.channelAcquisitionContextEnabled) { BridgeInternal.setChannelAcquisitionTimeline(cosmosException, record.getChannelAcquisitionTimeline()); } return cosmosException; }).contextWrite(reactorContext); }
return Mono.fromFuture(record).map(storeResponse -> {
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null addressUri"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, addressUri); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); return Mono.fromFuture(record).map(storeResponse -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } RequestTimeline timeline = record.takeTimelineSnapshot(); storeResponse.setRequestTimeline(timeline); storeResponse.setEndpointStatistics(record.serviceEndpointStatistics()); storeResponse.setRntbdResponseLength(record.responseLength()); storeResponse.setRntbdRequestLength(record.requestLength()); storeResponse.setRequestPayloadLength(request.getContentLength()); storeResponse.setRntbdChannelTaskQueueSize(record.channelTaskQueueLength()); storeResponse.setRntbdPendingRequestSize(record.pendingRequestQueueSize()); if (this.channelAcquisitionContextEnabled) { storeResponse.setChannelAcquisitionTimeline(record.getChannelAcquisitionTimeline()); } return storeResponse; }).onErrorMap(throwable -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); if (!(error instanceof CancellationException)) { reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); } error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address, error instanceof Exception ? (Exception) error : new RuntimeException(error)); } assert error instanceof CosmosException; CosmosException cosmosException = (CosmosException) error; BridgeInternal.setServiceEndpointStatistics(cosmosException, record.serviceEndpointStatistics()); BridgeInternal.setRntbdRequestLength(cosmosException, record.requestLength()); BridgeInternal.setRntbdResponseLength(cosmosException, record.responseLength()); BridgeInternal.setRequestBodyLength(cosmosException, request.getContentLength()); BridgeInternal.setRequestTimeline(cosmosException, record.takeTimelineSnapshot()); BridgeInternal.setRntbdPendingRequestQueueSize(cosmosException, record.pendingRequestQueueSize()); BridgeInternal.setChannelTaskQueueSize(cosmosException, record.channelTaskQueueLength()); BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted()); if (this.channelAcquisitionContextEnabled) { BridgeInternal.setChannelAcquisitionTimeline(cosmosException, record.getChannelAcquisitionTimeline()); } return cosmosException; }).doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } record.cancel(true); }).contextWrite(reactorContext); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * NOTE: This context key name has been copied from {link Hooks * not exposed as public Api but package internal only * * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; private boolean channelAcquisitionContextEnabled; private final GlobalEndpointManager globalEndpointManager; /** * Initializes a newly created {@linkplain RntbdTransportClient} object. * * @param configs A {@link Configs} instance containing the {@link SslContext} to be used. * @param connectionPolicy The {@linkplain ConnectionPolicy connection policy} to be applied. * @param userAgent The {@linkplain UserAgentContainer user agent} identifying. * @param addressResolver The address resolver to be used for connection endpoint rediscovery, if connection * endpoint rediscovery is enabled by {@code connectionPolicy}. */ public RntbdTransportClient( final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this( new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext(), addressResolver, clientTelemetry, globalEndpointManager); } RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.globalEndpointManager = null; } RntbdTransportClient( final Options options, final SslContext sslContext, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this.endpointProvider = new RntbdServiceEndpoint.Provider( this, options, checkNotNull(sslContext, "expected non-null sslContext"), addressResolver, clientTelemetry); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.channelAcquisitionContextEnabled = options.channelAcquisitionContextEnabled; this.globalEndpointManager = globalEndpointManager; } /** * {@code true} if this {@linkplain RntbdTransportClient client} is closed. * * @return {@code true} if this {@linkplain RntbdTransportClient client} is closed; {@code false} otherwise. */ public boolean isClosed() { return this.closed.get(); } /** * Closes this {@linkplain RntbdTransportClient client} and releases all resources associated with it. */ @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } @Override protected GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } /** * The number of {@linkplain RntbdEndpoint endpoints} allocated to this {@linkplain RntbdTransportClient client}. * * @return The number of {@linkplain RntbdEndpoint endpoints} associated with this {@linkplain RntbdTransportClient * client}. */ public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } /** * The integer identity of this {@linkplain RntbdTransportClient client}. * <p> * Clients are numbered sequentially based on the order in which they are initialized. * * @return The integer identity of this {@linkplain RntbdTransportClient client}. */ public long id() { return this.id; } /** * Issues a Direct TCP request to the specified Cosmos service address asynchronously. * * @param addressUri A Cosmos service address. * @param request The {@linkplain RxDocumentServiceRequest request} to issue. * * @return A {@link Mono} of type {@link StoreResponse} that will complete when the Direct TCP request completes. * I shI * @throws TransportException if this {@linkplain RntbdTransportClient client} is closed. */ @Override @Override public Mono<OpenConnectionResponse> openConnection(Uri addressUri) { checkNotNull(addressUri, "Argument 'addressUri' should not be null"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdEndpoint endpoint = this.endpointProvider.get(address); return Mono.fromFuture(endpoint.openConnection(addressUri)); } /** * The key-value pair used to classify and drill into metrics produced by this {@linkplain RntbdTransportClient * client}. * * @return The key-value pair used to classify and drill into metrics collected by this {@linkplain * RntbdTransportClient client}. */ public Tag tag() { return this.tag; } @Override public String toString() { return RntbdObjectMapper.toString(this); } private static Tag tag(long id) { return Tag.of(TAG_NAME, Strings.padStart(Long.toHexString(id).toUpperCase(Locale.ROOT), 4, '0')); } private void throwIfClosed() { if (this.closed.get()) { throw new TransportException(lenientFormat("%s is closed", this), null); } } public static final class Options { private static final int DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 10_000; @JsonProperty() private final int bufferPageSize; @JsonProperty() private final Duration connectionAcquisitionTimeout; @JsonProperty() private final boolean connectionEndpointRediscoveryEnabled; @JsonProperty() private final Duration connectTimeout; @JsonProperty() private final Duration idleChannelTimeout; @JsonProperty() private final Duration idleChannelTimerResolution; @JsonProperty() private final Duration idleEndpointTimeout; @JsonProperty() private final int maxBufferCapacity; @JsonProperty() private final int maxChannelsPerEndpoint; @JsonProperty() private final int maxRequestsPerChannel; @JsonProperty() private final int maxConcurrentRequestsPerEndpointOverride; @JsonProperty() private final Duration receiveHangDetectionTime; @JsonProperty() private final Duration tcpNetworkRequestTimeout; @JsonProperty() private final Duration requestTimerResolution; @JsonProperty() private final Duration sendHangDetectionTime; @JsonProperty() private final Duration shutdownTimeout; @JsonProperty() private final int threadCount; @JsonIgnore() private final UserAgentContainer userAgent; @JsonProperty() private final boolean channelAcquisitionContextEnabled; @JsonProperty() private final int ioThreadPriority; @JsonProperty() private final int tcpKeepIntvl; @JsonProperty() private final int tcpKeepIdle; @JsonProperty() private final boolean preferTcpNative; @JsonProperty() private final Duration sslHandshakeTimeoutMinDuration; @JsonCreator private Options() { this(ConnectionPolicy.getDefaultPolicy()); } private Options(final Builder builder) { this.bufferPageSize = builder.bufferPageSize; this.connectionAcquisitionTimeout = builder.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = builder.connectionEndpointRediscoveryEnabled; this.idleChannelTimeout = builder.idleChannelTimeout; this.idleChannelTimerResolution = builder.idleChannelTimerResolution; this.idleEndpointTimeout = builder.idleEndpointTimeout; this.maxBufferCapacity = builder.maxBufferCapacity; this.maxChannelsPerEndpoint = builder.maxChannelsPerEndpoint; this.maxRequestsPerChannel = builder.maxRequestsPerChannel; this.maxConcurrentRequestsPerEndpointOverride = builder.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = builder.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = builder.tcpNetworkRequestTimeout; this.requestTimerResolution = builder.requestTimerResolution; this.sendHangDetectionTime = builder.sendHangDetectionTime; this.shutdownTimeout = builder.shutdownTimeout; this.threadCount = builder.threadCount; this.userAgent = builder.userAgent; this.channelAcquisitionContextEnabled = builder.channelAcquisitionContextEnabled; this.ioThreadPriority = builder.ioThreadPriority; this.tcpKeepIntvl = builder.tcpKeepIntvl; this.tcpKeepIdle = builder.tcpKeepIdle; this.preferTcpNative = builder.preferTcpNative; this.sslHandshakeTimeoutMinDuration = builder.sslHandshakeTimeoutMinDuration; this.connectTimeout = builder.connectTimeout == null ? builder.tcpNetworkRequestTimeout : builder.connectTimeout; } private Options(final ConnectionPolicy connectionPolicy) { this.bufferPageSize = 8192; this.connectionAcquisitionTimeout = Duration.ofSeconds(5L); this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = Duration.ofMillis(100); this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = 8192 << 10; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = -1; this.receiveHangDetectionTime = Duration.ofSeconds(65L); this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = Duration.ofMillis(100L); this.sendHangDetectionTime = Duration.ofSeconds(10L); this.shutdownTimeout = Duration.ofSeconds(15L); this.threadCount = connectionPolicy.getIoThreadCountPerCoreFactor() * Runtime.getRuntime().availableProcessors(); this.userAgent = new UserAgentContainer(); this.channelAcquisitionContextEnabled = false; this.ioThreadPriority = connectionPolicy.getIoThreadPriority(); this.tcpKeepIntvl = 1; this.tcpKeepIdle = 30; this.sslHandshakeTimeoutMinDuration = Duration.ofSeconds(5); this.preferTcpNative = true; } public int bufferPageSize() { return this.bufferPageSize; } public Duration connectionAcquisitionTimeout() { return this.connectionAcquisitionTimeout; } public Duration connectTimeout() { return this.connectTimeout; } public Duration idleChannelTimeout() { return this.idleChannelTimeout; } public Duration idleChannelTimerResolution() { return this.idleChannelTimerResolution; } public Duration idleEndpointTimeout() { return this.idleEndpointTimeout; } public boolean isConnectionEndpointRediscoveryEnabled() { return this.connectionEndpointRediscoveryEnabled; } public int maxBufferCapacity() { return this.maxBufferCapacity; } public int maxChannelsPerEndpoint() { return this.maxChannelsPerEndpoint; } public int maxRequestsPerChannel() { return this.maxRequestsPerChannel; } public int maxConcurrentRequestsPerEndpoint() { if (this.maxConcurrentRequestsPerEndpointOverride > 0) { return maxConcurrentRequestsPerEndpointOverride; } return Math.max( DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, this.maxChannelsPerEndpoint * this.maxRequestsPerChannel); } public Duration receiveHangDetectionTime() { return this.receiveHangDetectionTime; } public Duration tcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } public Duration requestTimerResolution() { return this.requestTimerResolution; } public Duration sendHangDetectionTime() { return this.sendHangDetectionTime; } public Duration shutdownTimeout() { return this.shutdownTimeout; } public int threadCount() { return this.threadCount; } public UserAgentContainer userAgent() { return this.userAgent; } public boolean isChannelAcquisitionContextEnabled() { return this.channelAcquisitionContextEnabled; } public int ioThreadPriority() { checkArgument( this.ioThreadPriority >= Thread.MIN_PRIORITY && this.ioThreadPriority <= Thread.MAX_PRIORITY, "Expect ioThread priority between [%s, %s]", Thread.MIN_PRIORITY, Thread.MAX_PRIORITY); return this.ioThreadPriority; } public int tcpKeepIntvl() { return this.tcpKeepIntvl; } public int tcpKeepIdle() { return this.tcpKeepIdle; } public boolean preferTcpNative() { return this.preferTcpNative; } public long sslHandshakeTimeoutInMillis() { return Math.max(this.sslHandshakeTimeoutMinDuration.toMillis(), this.connectTimeout.toMillis()); } @Override public String toString() { return RntbdObjectMapper.toJson(this); } public String toDiagnosticsString() { return lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)", connectTimeout, tcpNetworkRequestTimeout, idleChannelTimeout, idleEndpointTimeout, maxChannelsPerEndpoint, maxRequestsPerChannel, connectionEndpointRediscoveryEnabled); } /** * A builder for constructing {@link Options} instances. * * <h3>Using system properties to set the default {@link Options} used by an {@link Builder}</h3> * <p> * A default options instance is created when the {@link Builder} class is initialized. This instance specifies * the default options used by every {@link Builder} instance. In priority order the default options instance * is created from: * <ol> * <li>The JSON value of system property {@code azure.cosmos.directTcp.defaultOptions}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptions={\"maxChannelsPerEndpoint\":5,\"maxRequestsPerChannel\":30}}</pre> * </li> * <li>The contents of the JSON file located by system property {@code azure.cosmos.directTcp * .defaultOptionsFile}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file}</pre> * </li> * <li>The contents of JSON resource file {@code azure.cosmos.directTcp.defaultOptions.json}. * <p>Specifically, the resource file is read from this stream: * <pre>{@code RntbdTransportClient.class.getClassLoader().getResourceAsStream("azure.cosmos.directTcp.defaultOptions.json")}</pre> * <p>Example: <pre>{@code { * "bufferPageSize": 8192, * "connectionEndpointRediscoveryEnabled": false, * "connectTimeout": "PT5S", * "idleChannelTimeout": "PT0S", * "idleEndpointTimeout": "PT1H", * "maxBufferCapacity": 8388608, * "maxChannelsPerEndpoint": 130, * "maxRequestsPerChannel": 30, * "maxConcurrentRequestsPerEndpointOverride": -1, * "receiveHangDetectionTime": "PT1M5S", * "requestTimeout": "PT5S", * "requestTimerResolution": "PT100MS", * "sendHangDetectionTime": "PT10S", * "shutdownTimeout": "PT15S", * "threadCount": 16 * }}</pre> * </li> * </ol> * <p>JSON value errors are logged and then ignored. If none of the above values are available or all available * values are in error, the default options instance is created from the private parameterless constructor for * {@link Options}. */ @SuppressWarnings("UnusedReturnValue") public static class Builder { private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions"; private static final Options DEFAULT_OPTIONS; static { Options options = null; try { final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME); if (string != null) { try { options = RntbdObjectMapper.readValue(string, Options.class); } catch (IOException error) { logger.error("failed to parse default Direct TCP options {} due to ", string, error); } } if (options == null) { final String path = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME + "File"); if (path != null) { try { options = RntbdObjectMapper.readValue(new File(path), Options.class); } catch (IOException error) { logger.error("failed to load default Direct TCP options from {} due to ", path, error); } } } if (options == null) { final ClassLoader loader = RntbdTransportClient.class.getClassLoader(); final String name = DEFAULT_OPTIONS_PROPERTY_NAME + ".json"; try (InputStream stream = loader.getResourceAsStream(name)) { if (stream != null) { options = RntbdObjectMapper.readValue(stream, Options.class); } } catch (IOException error) { logger.error("failed to load Direct TCP options from resource {} due to ", name, error); } } } finally { if (options == null) { logger.info("Using default Direct TCP options: {}", DEFAULT_OPTIONS_PROPERTY_NAME); DEFAULT_OPTIONS = new Options(ConnectionPolicy.getDefaultPolicy()); } else { logger.info("Updated default Direct TCP options from system property {}: {}", DEFAULT_OPTIONS_PROPERTY_NAME, options); DEFAULT_OPTIONS = options; } } } private int bufferPageSize; private Duration connectionAcquisitionTimeout; private boolean connectionEndpointRediscoveryEnabled; private Duration connectTimeout; private Duration idleChannelTimeout; private Duration idleChannelTimerResolution; private Duration idleEndpointTimeout; private int maxBufferCapacity; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; private int maxConcurrentRequestsPerEndpointOverride; private Duration receiveHangDetectionTime; private Duration tcpNetworkRequestTimeout; private Duration requestTimerResolution; private Duration sendHangDetectionTime; private Duration shutdownTimeout; private int threadCount; private UserAgentContainer userAgent; private boolean channelAcquisitionContextEnabled; private int ioThreadPriority; private int tcpKeepIntvl; private int tcpKeepIdle; private boolean preferTcpNative; private Duration sslHandshakeTimeoutMinDuration; public Builder(ConnectionPolicy connectionPolicy) { this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize; this.connectionAcquisitionTimeout = DEFAULT_OPTIONS.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = DEFAULT_OPTIONS.idleChannelTimerResolution; this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = DEFAULT_OPTIONS.maxBufferCapacity; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = DEFAULT_OPTIONS.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = DEFAULT_OPTIONS.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = DEFAULT_OPTIONS.requestTimerResolution; this.sendHangDetectionTime = DEFAULT_OPTIONS.sendHangDetectionTime; this.shutdownTimeout = DEFAULT_OPTIONS.shutdownTimeout; this.threadCount = DEFAULT_OPTIONS.threadCount; this.userAgent = DEFAULT_OPTIONS.userAgent; this.channelAcquisitionContextEnabled = DEFAULT_OPTIONS.channelAcquisitionContextEnabled; this.ioThreadPriority = DEFAULT_OPTIONS.ioThreadPriority; this.tcpKeepIntvl = DEFAULT_OPTIONS.tcpKeepIntvl; this.tcpKeepIdle = DEFAULT_OPTIONS.tcpKeepIdle; this.preferTcpNative = DEFAULT_OPTIONS.preferTcpNative; this.sslHandshakeTimeoutMinDuration = DEFAULT_OPTIONS.sslHandshakeTimeoutMinDuration; } public Builder bufferPageSize(final int value) { checkArgument(value >= 4096 && (value & (value - 1)) == 0, "expected value to be a power of 2 >= 4096, not %s", value); this.bufferPageSize = value; return this; } public Options build() { checkState(this.bufferPageSize <= this.maxBufferCapacity, "expected bufferPageSize (%s) <= maxBufferCapacity (%s)", this.bufferPageSize, this.maxBufferCapacity); return new Options(this); } public Builder connectionAcquisitionTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.connectionAcquisitionTimeout = value.compareTo(Duration.ZERO) < 0 ? Duration.ZERO : value; return this; } public Builder connectionEndpointRediscoveryEnabled(final boolean value) { this.connectionEndpointRediscoveryEnabled = value; return this; } public Builder connectionTimeout(final Duration value) { checkArgument(value == null || value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.connectTimeout = value; return this; } public Builder idleChannelTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.idleChannelTimeout = value; return this; } public Builder idleChannelTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) <= 0, "expected positive value, not %s", value); this.idleChannelTimerResolution = value; return this; } public Builder idleEndpointTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.idleEndpointTimeout = value; return this; } public Builder maxBufferCapacity(final int value) { checkArgument(value > 0 && (value & (value - 1)) == 0, "expected positive value, not %s", value); this.maxBufferCapacity = value; return this; } public Builder maxChannelsPerEndpoint(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxChannelsPerEndpoint = value; return this; } public Builder maxRequestsPerChannel(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxRequestsPerChannel = value; return this; } public Builder maxConcurrentRequestsPerEndpointOverride(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxConcurrentRequestsPerEndpointOverride = value; return this; } public Builder receiveHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.receiveHangDetectionTime = value; return this; } public Builder tcpNetworkRequestTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.tcpNetworkRequestTimeout = value; return this; } public Builder requestTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.requestTimerResolution = value; return this; } public Builder sendHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.sendHangDetectionTime = value; return this; } public Builder shutdownTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.shutdownTimeout = value; return this; } public Builder threadCount(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.threadCount = value; return this; } public Builder userAgent(final UserAgentContainer value) { checkNotNull(value, "expected non-null value"); this.userAgent = value; return this; } } } static final class JsonSerializer extends StdSerializer<RntbdTransportClient> { private static final long serialVersionUID = 1007663695768825670L; JsonSerializer() { super(RntbdTransportClient.class); } @Override public void serialize( final RntbdTransportClient value, final JsonGenerator generator, final SerializerProvider provider ) throws IOException { generator.writeStartObject(); generator.writeNumberField("id", value.id()); generator.writeBooleanField("isClosed", value.isClosed()); generator.writeObjectField("configuration", value.endpointProvider.config()); generator.writeObjectFieldStart("serviceEndpoints"); generator.writeNumberField("count", value.endpointCount()); generator.writeArrayFieldStart("items"); for (final Iterator<RntbdEndpoint> iterator = value.endpointProvider.list().iterator(); iterator.hasNext(); ) { generator.writeObject(iterator.next()); } generator.writeEndArray(); generator.writeEndObject(); generator.writeEndObject(); } } }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * NOTE: This context key name has been copied from {link Hooks * not exposed as public Api but package internal only * * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; private boolean channelAcquisitionContextEnabled; private final GlobalEndpointManager globalEndpointManager; /** * Initializes a newly created {@linkplain RntbdTransportClient} object. * * @param configs A {@link Configs} instance containing the {@link SslContext} to be used. * @param connectionPolicy The {@linkplain ConnectionPolicy connection policy} to be applied. * @param userAgent The {@linkplain UserAgentContainer user agent} identifying. * @param addressResolver The address resolver to be used for connection endpoint rediscovery, if connection * endpoint rediscovery is enabled by {@code connectionPolicy}. */ public RntbdTransportClient( final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this( new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext(), addressResolver, clientTelemetry, globalEndpointManager); } RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.globalEndpointManager = null; } RntbdTransportClient( final Options options, final SslContext sslContext, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this.endpointProvider = new RntbdServiceEndpoint.Provider( this, options, checkNotNull(sslContext, "expected non-null sslContext"), addressResolver, clientTelemetry); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.channelAcquisitionContextEnabled = options.channelAcquisitionContextEnabled; this.globalEndpointManager = globalEndpointManager; } /** * {@code true} if this {@linkplain RntbdTransportClient client} is closed. * * @return {@code true} if this {@linkplain RntbdTransportClient client} is closed; {@code false} otherwise. */ public boolean isClosed() { return this.closed.get(); } /** * Closes this {@linkplain RntbdTransportClient client} and releases all resources associated with it. */ @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } @Override protected GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } /** * The number of {@linkplain RntbdEndpoint endpoints} allocated to this {@linkplain RntbdTransportClient client}. * * @return The number of {@linkplain RntbdEndpoint endpoints} associated with this {@linkplain RntbdTransportClient * client}. */ public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } /** * The integer identity of this {@linkplain RntbdTransportClient client}. * <p> * Clients are numbered sequentially based on the order in which they are initialized. * * @return The integer identity of this {@linkplain RntbdTransportClient client}. */ public long id() { return this.id; } /** * Issues a Direct TCP request to the specified Cosmos service address asynchronously. * * @param addressUri A Cosmos service address. * @param request The {@linkplain RxDocumentServiceRequest request} to issue. * * @return A {@link Mono} of type {@link StoreResponse} that will complete when the Direct TCP request completes. * I shI * @throws TransportException if this {@linkplain RntbdTransportClient client} is closed. */ @Override @Override public Mono<OpenConnectionResponse> openConnection(Uri addressUri) { checkNotNull(addressUri, "Argument 'addressUri' should not be null"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdEndpoint endpoint = this.endpointProvider.get(address); return Mono.fromFuture(endpoint.openConnection(addressUri)); } /** * The key-value pair used to classify and drill into metrics produced by this {@linkplain RntbdTransportClient * client}. * * @return The key-value pair used to classify and drill into metrics collected by this {@linkplain * RntbdTransportClient client}. */ public Tag tag() { return this.tag; } @Override public String toString() { return RntbdObjectMapper.toString(this); } private static Tag tag(long id) { return Tag.of(TAG_NAME, Strings.padStart(Long.toHexString(id).toUpperCase(Locale.ROOT), 4, '0')); } private void throwIfClosed() { if (this.closed.get()) { throw new TransportException(lenientFormat("%s is closed", this), null); } } public static final class Options { private static final int DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 10_000; @JsonProperty() private final int bufferPageSize; @JsonProperty() private final Duration connectionAcquisitionTimeout; @JsonProperty() private final boolean connectionEndpointRediscoveryEnabled; @JsonProperty() private final Duration connectTimeout; @JsonProperty() private final Duration idleChannelTimeout; @JsonProperty() private final Duration idleChannelTimerResolution; @JsonProperty() private final Duration idleEndpointTimeout; @JsonProperty() private final int maxBufferCapacity; @JsonProperty() private final int maxChannelsPerEndpoint; @JsonProperty() private final int maxRequestsPerChannel; @JsonProperty() private final int maxConcurrentRequestsPerEndpointOverride; @JsonProperty() private final Duration receiveHangDetectionTime; @JsonProperty() private final Duration tcpNetworkRequestTimeout; @JsonProperty() private final Duration requestTimerResolution; @JsonProperty() private final Duration sendHangDetectionTime; @JsonProperty() private final Duration shutdownTimeout; @JsonProperty() private final int threadCount; @JsonIgnore() private final UserAgentContainer userAgent; @JsonProperty() private final boolean channelAcquisitionContextEnabled; @JsonProperty() private final int ioThreadPriority; @JsonProperty() private final int tcpKeepIntvl; @JsonProperty() private final int tcpKeepIdle; @JsonProperty() private final boolean preferTcpNative; @JsonProperty() private final Duration sslHandshakeTimeoutMinDuration; /** * This property will be used in {@link RntbdClientChannelHealthChecker} to determine whether there is a readHang. * If there is no successful reads for up to receiveHangDetectionTime, and the number of consecutive timeout has also reached this config, * then SDK is going to treat the channel as unhealthy and close it. */ @JsonProperty() private final int transientTimeoutDetectionThreshold; @JsonCreator private Options() { this(ConnectionPolicy.getDefaultPolicy()); } private Options(final Builder builder) { this.bufferPageSize = builder.bufferPageSize; this.connectionAcquisitionTimeout = builder.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = builder.connectionEndpointRediscoveryEnabled; this.idleChannelTimeout = builder.idleChannelTimeout; this.idleChannelTimerResolution = builder.idleChannelTimerResolution; this.idleEndpointTimeout = builder.idleEndpointTimeout; this.maxBufferCapacity = builder.maxBufferCapacity; this.maxChannelsPerEndpoint = builder.maxChannelsPerEndpoint; this.maxRequestsPerChannel = builder.maxRequestsPerChannel; this.maxConcurrentRequestsPerEndpointOverride = builder.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = builder.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = builder.tcpNetworkRequestTimeout; this.requestTimerResolution = builder.requestTimerResolution; this.sendHangDetectionTime = builder.sendHangDetectionTime; this.shutdownTimeout = builder.shutdownTimeout; this.threadCount = builder.threadCount; this.userAgent = builder.userAgent; this.channelAcquisitionContextEnabled = builder.channelAcquisitionContextEnabled; this.ioThreadPriority = builder.ioThreadPriority; this.tcpKeepIntvl = builder.tcpKeepIntvl; this.tcpKeepIdle = builder.tcpKeepIdle; this.preferTcpNative = builder.preferTcpNative; this.sslHandshakeTimeoutMinDuration = builder.sslHandshakeTimeoutMinDuration; this.transientTimeoutDetectionThreshold = builder.transientTimeoutDetectionThreshold; this.connectTimeout = builder.connectTimeout == null ? builder.tcpNetworkRequestTimeout : builder.connectTimeout; } private Options(final ConnectionPolicy connectionPolicy) { this.bufferPageSize = 8192; this.connectionAcquisitionTimeout = Duration.ofSeconds(5L); this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = Duration.ofMillis(100); this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = 8192 << 10; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = -1; this.receiveHangDetectionTime = Duration.ofSeconds(65L); this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = Duration.ofMillis(100L); this.sendHangDetectionTime = Duration.ofSeconds(10L); this.shutdownTimeout = Duration.ofSeconds(15L); this.threadCount = connectionPolicy.getIoThreadCountPerCoreFactor() * Runtime.getRuntime().availableProcessors(); this.userAgent = new UserAgentContainer(); this.channelAcquisitionContextEnabled = false; this.ioThreadPriority = connectionPolicy.getIoThreadPriority(); this.tcpKeepIntvl = 1; this.tcpKeepIdle = 30; this.sslHandshakeTimeoutMinDuration = Duration.ofSeconds(5); this.transientTimeoutDetectionThreshold = 3; this.preferTcpNative = true; } public int bufferPageSize() { return this.bufferPageSize; } public Duration connectionAcquisitionTimeout() { return this.connectionAcquisitionTimeout; } public Duration connectTimeout() { return this.connectTimeout; } public Duration idleChannelTimeout() { return this.idleChannelTimeout; } public Duration idleChannelTimerResolution() { return this.idleChannelTimerResolution; } public Duration idleEndpointTimeout() { return this.idleEndpointTimeout; } public boolean isConnectionEndpointRediscoveryEnabled() { return this.connectionEndpointRediscoveryEnabled; } public int maxBufferCapacity() { return this.maxBufferCapacity; } public int maxChannelsPerEndpoint() { return this.maxChannelsPerEndpoint; } public int maxRequestsPerChannel() { return this.maxRequestsPerChannel; } public int maxConcurrentRequestsPerEndpoint() { if (this.maxConcurrentRequestsPerEndpointOverride > 0) { return maxConcurrentRequestsPerEndpointOverride; } return Math.max( DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, this.maxChannelsPerEndpoint * this.maxRequestsPerChannel); } public Duration receiveHangDetectionTime() { return this.receiveHangDetectionTime; } public Duration tcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } public Duration requestTimerResolution() { return this.requestTimerResolution; } public Duration sendHangDetectionTime() { return this.sendHangDetectionTime; } public Duration shutdownTimeout() { return this.shutdownTimeout; } public int threadCount() { return this.threadCount; } public UserAgentContainer userAgent() { return this.userAgent; } public boolean isChannelAcquisitionContextEnabled() { return this.channelAcquisitionContextEnabled; } public int ioThreadPriority() { checkArgument( this.ioThreadPriority >= Thread.MIN_PRIORITY && this.ioThreadPriority <= Thread.MAX_PRIORITY, "Expect ioThread priority between [%s, %s]", Thread.MIN_PRIORITY, Thread.MAX_PRIORITY); return this.ioThreadPriority; } public int tcpKeepIntvl() { return this.tcpKeepIntvl; } public int tcpKeepIdle() { return this.tcpKeepIdle; } public boolean preferTcpNative() { return this.preferTcpNative; } public long sslHandshakeTimeoutInMillis() { return Math.max(this.sslHandshakeTimeoutMinDuration.toMillis(), this.connectTimeout.toMillis()); } public int transientTimeoutDetectionThreshold() { return this.transientTimeoutDetectionThreshold; } @Override public String toString() { return RntbdObjectMapper.toJson(this); } public String toDiagnosticsString() { return lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)", connectTimeout, tcpNetworkRequestTimeout, idleChannelTimeout, idleEndpointTimeout, maxChannelsPerEndpoint, maxRequestsPerChannel, connectionEndpointRediscoveryEnabled); } /** * A builder for constructing {@link Options} instances. * * <h3>Using system properties to set the default {@link Options} used by an {@link Builder}</h3> * <p> * A default options instance is created when the {@link Builder} class is initialized. This instance specifies * the default options used by every {@link Builder} instance. In priority order the default options instance * is created from: * <ol> * <li>The JSON value of system property {@code azure.cosmos.directTcp.defaultOptions}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptions={\"maxChannelsPerEndpoint\":5,\"maxRequestsPerChannel\":30}}</pre> * </li> * <li>The contents of the JSON file located by system property {@code azure.cosmos.directTcp * .defaultOptionsFile}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file}</pre> * </li> * <li>The contents of JSON resource file {@code azure.cosmos.directTcp.defaultOptions.json}. * <p>Specifically, the resource file is read from this stream: * <pre>{@code RntbdTransportClient.class.getClassLoader().getResourceAsStream("azure.cosmos.directTcp.defaultOptions.json")}</pre> * <p>Example: <pre>{@code { * "bufferPageSize": 8192, * "connectionEndpointRediscoveryEnabled": false, * "connectTimeout": "PT5S", * "idleChannelTimeout": "PT0S", * "idleEndpointTimeout": "PT1H", * "maxBufferCapacity": 8388608, * "maxChannelsPerEndpoint": 130, * "maxRequestsPerChannel": 30, * "maxConcurrentRequestsPerEndpointOverride": -1, * "receiveHangDetectionTime": "PT1M5S", * "requestTimeout": "PT5S", * "requestTimerResolution": "PT100MS", * "sendHangDetectionTime": "PT10S", * "shutdownTimeout": "PT15S", * "threadCount": 16, * "transientTimeoutDetectionThreshold": 3 * }}</pre> * </li> * </ol> * <p>JSON value errors are logged and then ignored. If none of the above values are available or all available * values are in error, the default options instance is created from the private parameterless constructor for * {@link Options}. */ @SuppressWarnings("UnusedReturnValue") public static class Builder { private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions"; private static final Options DEFAULT_OPTIONS; static { Options options = null; try { final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME); if (string != null) { try { options = RntbdObjectMapper.readValue(string, Options.class); } catch (IOException error) { logger.error("failed to parse default Direct TCP options {} due to ", string, error); } } if (options == null) { final String path = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME + "File"); if (path != null) { try { options = RntbdObjectMapper.readValue(new File(path), Options.class); } catch (IOException error) { logger.error("failed to load default Direct TCP options from {} due to ", path, error); } } } if (options == null) { final ClassLoader loader = RntbdTransportClient.class.getClassLoader(); final String name = DEFAULT_OPTIONS_PROPERTY_NAME + ".json"; try (InputStream stream = loader.getResourceAsStream(name)) { if (stream != null) { options = RntbdObjectMapper.readValue(stream, Options.class); } } catch (IOException error) { logger.error("failed to load Direct TCP options from resource {} due to ", name, error); } } } finally { if (options == null) { logger.info("Using default Direct TCP options: {}", DEFAULT_OPTIONS_PROPERTY_NAME); DEFAULT_OPTIONS = new Options(ConnectionPolicy.getDefaultPolicy()); } else { logger.info("Updated default Direct TCP options from system property {}: {}", DEFAULT_OPTIONS_PROPERTY_NAME, options); DEFAULT_OPTIONS = options; } } } private int bufferPageSize; private Duration connectionAcquisitionTimeout; private boolean connectionEndpointRediscoveryEnabled; private Duration connectTimeout; private Duration idleChannelTimeout; private Duration idleChannelTimerResolution; private Duration idleEndpointTimeout; private int maxBufferCapacity; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; private int maxConcurrentRequestsPerEndpointOverride; private Duration receiveHangDetectionTime; private Duration tcpNetworkRequestTimeout; private Duration requestTimerResolution; private Duration sendHangDetectionTime; private Duration shutdownTimeout; private int threadCount; private UserAgentContainer userAgent; private boolean channelAcquisitionContextEnabled; private int ioThreadPriority; private int tcpKeepIntvl; private int tcpKeepIdle; private boolean preferTcpNative; private Duration sslHandshakeTimeoutMinDuration; private int transientTimeoutDetectionThreshold; public Builder(ConnectionPolicy connectionPolicy) { this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize; this.connectionAcquisitionTimeout = DEFAULT_OPTIONS.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = DEFAULT_OPTIONS.idleChannelTimerResolution; this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = DEFAULT_OPTIONS.maxBufferCapacity; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = DEFAULT_OPTIONS.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = DEFAULT_OPTIONS.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = DEFAULT_OPTIONS.requestTimerResolution; this.sendHangDetectionTime = DEFAULT_OPTIONS.sendHangDetectionTime; this.shutdownTimeout = DEFAULT_OPTIONS.shutdownTimeout; this.threadCount = DEFAULT_OPTIONS.threadCount; this.userAgent = DEFAULT_OPTIONS.userAgent; this.channelAcquisitionContextEnabled = DEFAULT_OPTIONS.channelAcquisitionContextEnabled; this.ioThreadPriority = DEFAULT_OPTIONS.ioThreadPriority; this.tcpKeepIntvl = DEFAULT_OPTIONS.tcpKeepIntvl; this.tcpKeepIdle = DEFAULT_OPTIONS.tcpKeepIdle; this.preferTcpNative = DEFAULT_OPTIONS.preferTcpNative; this.sslHandshakeTimeoutMinDuration = DEFAULT_OPTIONS.sslHandshakeTimeoutMinDuration; this.transientTimeoutDetectionThreshold = DEFAULT_OPTIONS.transientTimeoutDetectionThreshold; } public Builder bufferPageSize(final int value) { checkArgument(value >= 4096 && (value & (value - 1)) == 0, "expected value to be a power of 2 >= 4096, not %s", value); this.bufferPageSize = value; return this; } public Options build() { checkState(this.bufferPageSize <= this.maxBufferCapacity, "expected bufferPageSize (%s) <= maxBufferCapacity (%s)", this.bufferPageSize, this.maxBufferCapacity); return new Options(this); } public Builder connectionAcquisitionTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.connectionAcquisitionTimeout = value.compareTo(Duration.ZERO) < 0 ? Duration.ZERO : value; return this; } public Builder connectionEndpointRediscoveryEnabled(final boolean value) { this.connectionEndpointRediscoveryEnabled = value; return this; } public Builder connectionTimeout(final Duration value) { checkArgument(value == null || value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.connectTimeout = value; return this; } public Builder idleChannelTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.idleChannelTimeout = value; return this; } public Builder idleChannelTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) <= 0, "expected positive value, not %s", value); this.idleChannelTimerResolution = value; return this; } public Builder idleEndpointTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.idleEndpointTimeout = value; return this; } public Builder maxBufferCapacity(final int value) { checkArgument(value > 0 && (value & (value - 1)) == 0, "expected positive value, not %s", value); this.maxBufferCapacity = value; return this; } public Builder maxChannelsPerEndpoint(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxChannelsPerEndpoint = value; return this; } public Builder maxRequestsPerChannel(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxRequestsPerChannel = value; return this; } public Builder maxConcurrentRequestsPerEndpointOverride(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxConcurrentRequestsPerEndpointOverride = value; return this; } public Builder receiveHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.receiveHangDetectionTime = value; return this; } public Builder tcpNetworkRequestTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.tcpNetworkRequestTimeout = value; return this; } public Builder requestTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.requestTimerResolution = value; return this; } public Builder sendHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.sendHangDetectionTime = value; return this; } public Builder shutdownTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.shutdownTimeout = value; return this; } public Builder threadCount(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.threadCount = value; return this; } public Builder userAgent(final UserAgentContainer value) { checkNotNull(value, "expected non-null value"); this.userAgent = value; return this; } } } static final class JsonSerializer extends StdSerializer<RntbdTransportClient> { private static final long serialVersionUID = 1007663695768825670L; JsonSerializer() { super(RntbdTransportClient.class); } @Override public void serialize( final RntbdTransportClient value, final JsonGenerator generator, final SerializerProvider provider ) throws IOException { generator.writeStartObject(); generator.writeNumberField("id", value.id()); generator.writeBooleanField("isClosed", value.isClosed()); generator.writeObjectField("configuration", value.endpointProvider.config()); generator.writeObjectFieldStart("serviceEndpoints"); generator.writeNumberField("count", value.endpointCount()); generator.writeArrayFieldStart("items"); for (final Iterator<RntbdEndpoint> iterator = value.endpointProvider.list().iterator(); iterator.hasNext(); ) { generator.writeObject(iterator.next()); } generator.writeEndArray(); generator.writeEndObject(); generator.writeEndObject(); } } }
Thanks - good catch - missed yesterday that you are ensuring consistency already here.
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null addressUri"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, addressUri); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); return Mono.fromFuture(record).map(storeResponse -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } RequestTimeline timeline = record.takeTimelineSnapshot(); storeResponse.setRequestTimeline(timeline); storeResponse.setEndpointStatistics(record.serviceEndpointStatistics()); storeResponse.setRntbdResponseLength(record.responseLength()); storeResponse.setRntbdRequestLength(record.requestLength()); storeResponse.setRequestPayloadLength(request.getContentLength()); storeResponse.setRntbdChannelTaskQueueSize(record.channelTaskQueueLength()); storeResponse.setRntbdPendingRequestSize(record.pendingRequestQueueSize()); if (this.channelAcquisitionContextEnabled) { storeResponse.setChannelAcquisitionTimeline(record.getChannelAcquisitionTimeline()); } return storeResponse; }).onErrorMap(throwable -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); if (!(error instanceof CancellationException)) { reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); } error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address, error instanceof Exception ? (Exception) error : new RuntimeException(error)); } assert error instanceof CosmosException; CosmosException cosmosException = (CosmosException) error; BridgeInternal.setServiceEndpointStatistics(cosmosException, record.serviceEndpointStatistics()); BridgeInternal.setRntbdRequestLength(cosmosException, record.requestLength()); BridgeInternal.setRntbdResponseLength(cosmosException, record.responseLength()); BridgeInternal.setRequestBodyLength(cosmosException, request.getContentLength()); BridgeInternal.setRequestTimeline(cosmosException, record.takeTimelineSnapshot()); BridgeInternal.setRntbdPendingRequestQueueSize(cosmosException, record.pendingRequestQueueSize()); BridgeInternal.setChannelTaskQueueSize(cosmosException, record.channelTaskQueueLength()); BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted()); if (this.channelAcquisitionContextEnabled) { BridgeInternal.setChannelAcquisitionTimeline(cosmosException, record.getChannelAcquisitionTimeline()); } return cosmosException; }).doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } record.cancel(true); }).contextWrite(reactorContext); }
record.cancel(true);
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null addressUri"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, addressUri); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); return Mono.fromFuture(record).map(storeResponse -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } RequestTimeline timeline = record.takeTimelineSnapshot(); storeResponse.setRequestTimeline(timeline); storeResponse.setEndpointStatistics(record.serviceEndpointStatistics()); storeResponse.setRntbdResponseLength(record.responseLength()); storeResponse.setRntbdRequestLength(record.requestLength()); storeResponse.setRequestPayloadLength(request.getContentLength()); storeResponse.setRntbdChannelTaskQueueSize(record.channelTaskQueueLength()); storeResponse.setRntbdPendingRequestSize(record.pendingRequestQueueSize()); if (this.channelAcquisitionContextEnabled) { storeResponse.setChannelAcquisitionTimeline(record.getChannelAcquisitionTimeline()); } return storeResponse; }).onErrorMap(throwable -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); if (!(error instanceof CancellationException)) { reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); } error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address, error instanceof Exception ? (Exception) error : new RuntimeException(error)); } assert error instanceof CosmosException; CosmosException cosmosException = (CosmosException) error; BridgeInternal.setServiceEndpointStatistics(cosmosException, record.serviceEndpointStatistics()); BridgeInternal.setRntbdRequestLength(cosmosException, record.requestLength()); BridgeInternal.setRntbdResponseLength(cosmosException, record.responseLength()); BridgeInternal.setRequestBodyLength(cosmosException, request.getContentLength()); BridgeInternal.setRequestTimeline(cosmosException, record.takeTimelineSnapshot()); BridgeInternal.setRntbdPendingRequestQueueSize(cosmosException, record.pendingRequestQueueSize()); BridgeInternal.setChannelTaskQueueSize(cosmosException, record.channelTaskQueueLength()); BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted()); if (this.channelAcquisitionContextEnabled) { BridgeInternal.setChannelAcquisitionTimeline(cosmosException, record.getChannelAcquisitionTimeline()); } return cosmosException; }).doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } record.cancel(true); }).contextWrite(reactorContext); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * NOTE: This context key name has been copied from {link Hooks * not exposed as public Api but package internal only * * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; private boolean channelAcquisitionContextEnabled; private final GlobalEndpointManager globalEndpointManager; /** * Initializes a newly created {@linkplain RntbdTransportClient} object. * * @param configs A {@link Configs} instance containing the {@link SslContext} to be used. * @param connectionPolicy The {@linkplain ConnectionPolicy connection policy} to be applied. * @param userAgent The {@linkplain UserAgentContainer user agent} identifying. * @param addressResolver The address resolver to be used for connection endpoint rediscovery, if connection * endpoint rediscovery is enabled by {@code connectionPolicy}. */ public RntbdTransportClient( final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this( new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext(), addressResolver, clientTelemetry, globalEndpointManager); } RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.globalEndpointManager = null; } RntbdTransportClient( final Options options, final SslContext sslContext, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this.endpointProvider = new RntbdServiceEndpoint.Provider( this, options, checkNotNull(sslContext, "expected non-null sslContext"), addressResolver, clientTelemetry); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.channelAcquisitionContextEnabled = options.channelAcquisitionContextEnabled; this.globalEndpointManager = globalEndpointManager; } /** * {@code true} if this {@linkplain RntbdTransportClient client} is closed. * * @return {@code true} if this {@linkplain RntbdTransportClient client} is closed; {@code false} otherwise. */ public boolean isClosed() { return this.closed.get(); } /** * Closes this {@linkplain RntbdTransportClient client} and releases all resources associated with it. */ @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } @Override protected GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } /** * The number of {@linkplain RntbdEndpoint endpoints} allocated to this {@linkplain RntbdTransportClient client}. * * @return The number of {@linkplain RntbdEndpoint endpoints} associated with this {@linkplain RntbdTransportClient * client}. */ public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } /** * The integer identity of this {@linkplain RntbdTransportClient client}. * <p> * Clients are numbered sequentially based on the order in which they are initialized. * * @return The integer identity of this {@linkplain RntbdTransportClient client}. */ public long id() { return this.id; } /** * Issues a Direct TCP request to the specified Cosmos service address asynchronously. * * @param addressUri A Cosmos service address. * @param request The {@linkplain RxDocumentServiceRequest request} to issue. * * @return A {@link Mono} of type {@link StoreResponse} that will complete when the Direct TCP request completes. * I shI * @throws TransportException if this {@linkplain RntbdTransportClient client} is closed. */ @Override @Override public Mono<OpenConnectionResponse> openConnection(Uri addressUri) { checkNotNull(addressUri, "Argument 'addressUri' should not be null"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdEndpoint endpoint = this.endpointProvider.get(address); return Mono.fromFuture(endpoint.openConnection(addressUri)); } /** * The key-value pair used to classify and drill into metrics produced by this {@linkplain RntbdTransportClient * client}. * * @return The key-value pair used to classify and drill into metrics collected by this {@linkplain * RntbdTransportClient client}. */ public Tag tag() { return this.tag; } @Override public String toString() { return RntbdObjectMapper.toString(this); } private static Tag tag(long id) { return Tag.of(TAG_NAME, Strings.padStart(Long.toHexString(id).toUpperCase(Locale.ROOT), 4, '0')); } private void throwIfClosed() { if (this.closed.get()) { throw new TransportException(lenientFormat("%s is closed", this), null); } } public static final class Options { private static final int DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 10_000; @JsonProperty() private final int bufferPageSize; @JsonProperty() private final Duration connectionAcquisitionTimeout; @JsonProperty() private final boolean connectionEndpointRediscoveryEnabled; @JsonProperty() private final Duration connectTimeout; @JsonProperty() private final Duration idleChannelTimeout; @JsonProperty() private final Duration idleChannelTimerResolution; @JsonProperty() private final Duration idleEndpointTimeout; @JsonProperty() private final int maxBufferCapacity; @JsonProperty() private final int maxChannelsPerEndpoint; @JsonProperty() private final int maxRequestsPerChannel; @JsonProperty() private final int maxConcurrentRequestsPerEndpointOverride; @JsonProperty() private final Duration receiveHangDetectionTime; @JsonProperty() private final Duration tcpNetworkRequestTimeout; @JsonProperty() private final Duration requestTimerResolution; @JsonProperty() private final Duration sendHangDetectionTime; @JsonProperty() private final Duration shutdownTimeout; @JsonProperty() private final int threadCount; @JsonIgnore() private final UserAgentContainer userAgent; @JsonProperty() private final boolean channelAcquisitionContextEnabled; @JsonProperty() private final int ioThreadPriority; @JsonProperty() private final int tcpKeepIntvl; @JsonProperty() private final int tcpKeepIdle; @JsonProperty() private final boolean preferTcpNative; @JsonProperty() private final Duration sslHandshakeTimeoutMinDuration; /** * This property will be used in {@link RntbdClientChannelHealthChecker} to determine whether there is a readHang. * If there is no successful reads for up to receiveHangDetectionTime, and the number of consecutive timeout has also reached this config, * then SDK is going to treat the channel as unhealthy and close it. */ @JsonProperty() private final int transientTimeoutDetectionThreshold; @JsonCreator private Options() { this(ConnectionPolicy.getDefaultPolicy()); } private Options(final Builder builder) { this.bufferPageSize = builder.bufferPageSize; this.connectionAcquisitionTimeout = builder.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = builder.connectionEndpointRediscoveryEnabled; this.idleChannelTimeout = builder.idleChannelTimeout; this.idleChannelTimerResolution = builder.idleChannelTimerResolution; this.idleEndpointTimeout = builder.idleEndpointTimeout; this.maxBufferCapacity = builder.maxBufferCapacity; this.maxChannelsPerEndpoint = builder.maxChannelsPerEndpoint; this.maxRequestsPerChannel = builder.maxRequestsPerChannel; this.maxConcurrentRequestsPerEndpointOverride = builder.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = builder.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = builder.tcpNetworkRequestTimeout; this.requestTimerResolution = builder.requestTimerResolution; this.sendHangDetectionTime = builder.sendHangDetectionTime; this.shutdownTimeout = builder.shutdownTimeout; this.threadCount = builder.threadCount; this.userAgent = builder.userAgent; this.channelAcquisitionContextEnabled = builder.channelAcquisitionContextEnabled; this.ioThreadPriority = builder.ioThreadPriority; this.tcpKeepIntvl = builder.tcpKeepIntvl; this.tcpKeepIdle = builder.tcpKeepIdle; this.preferTcpNative = builder.preferTcpNative; this.sslHandshakeTimeoutMinDuration = builder.sslHandshakeTimeoutMinDuration; this.transientTimeoutDetectionThreshold = builder.transientTimeoutDetectionThreshold; this.connectTimeout = builder.connectTimeout == null ? builder.tcpNetworkRequestTimeout : builder.connectTimeout; } private Options(final ConnectionPolicy connectionPolicy) { this.bufferPageSize = 8192; this.connectionAcquisitionTimeout = Duration.ofSeconds(5L); this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = Duration.ofMillis(100); this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = 8192 << 10; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = -1; this.receiveHangDetectionTime = Duration.ofSeconds(65L); this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = Duration.ofMillis(100L); this.sendHangDetectionTime = Duration.ofSeconds(10L); this.shutdownTimeout = Duration.ofSeconds(15L); this.threadCount = connectionPolicy.getIoThreadCountPerCoreFactor() * Runtime.getRuntime().availableProcessors(); this.userAgent = new UserAgentContainer(); this.channelAcquisitionContextEnabled = false; this.ioThreadPriority = connectionPolicy.getIoThreadPriority(); this.tcpKeepIntvl = 1; this.tcpKeepIdle = 30; this.sslHandshakeTimeoutMinDuration = Duration.ofSeconds(5); this.transientTimeoutDetectionThreshold = 3; this.preferTcpNative = true; } public int bufferPageSize() { return this.bufferPageSize; } public Duration connectionAcquisitionTimeout() { return this.connectionAcquisitionTimeout; } public Duration connectTimeout() { return this.connectTimeout; } public Duration idleChannelTimeout() { return this.idleChannelTimeout; } public Duration idleChannelTimerResolution() { return this.idleChannelTimerResolution; } public Duration idleEndpointTimeout() { return this.idleEndpointTimeout; } public boolean isConnectionEndpointRediscoveryEnabled() { return this.connectionEndpointRediscoveryEnabled; } public int maxBufferCapacity() { return this.maxBufferCapacity; } public int maxChannelsPerEndpoint() { return this.maxChannelsPerEndpoint; } public int maxRequestsPerChannel() { return this.maxRequestsPerChannel; } public int maxConcurrentRequestsPerEndpoint() { if (this.maxConcurrentRequestsPerEndpointOverride > 0) { return maxConcurrentRequestsPerEndpointOverride; } return Math.max( DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, this.maxChannelsPerEndpoint * this.maxRequestsPerChannel); } public Duration receiveHangDetectionTime() { return this.receiveHangDetectionTime; } public Duration tcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } public Duration requestTimerResolution() { return this.requestTimerResolution; } public Duration sendHangDetectionTime() { return this.sendHangDetectionTime; } public Duration shutdownTimeout() { return this.shutdownTimeout; } public int threadCount() { return this.threadCount; } public UserAgentContainer userAgent() { return this.userAgent; } public boolean isChannelAcquisitionContextEnabled() { return this.channelAcquisitionContextEnabled; } public int ioThreadPriority() { checkArgument( this.ioThreadPriority >= Thread.MIN_PRIORITY && this.ioThreadPriority <= Thread.MAX_PRIORITY, "Expect ioThread priority between [%s, %s]", Thread.MIN_PRIORITY, Thread.MAX_PRIORITY); return this.ioThreadPriority; } public int tcpKeepIntvl() { return this.tcpKeepIntvl; } public int tcpKeepIdle() { return this.tcpKeepIdle; } public boolean preferTcpNative() { return this.preferTcpNative; } public long sslHandshakeTimeoutInMillis() { return Math.max(this.sslHandshakeTimeoutMinDuration.toMillis(), this.connectTimeout.toMillis()); } public int transientTimeoutDetectionThreshold() { return this.transientTimeoutDetectionThreshold; } @Override public String toString() { return RntbdObjectMapper.toJson(this); } public String toDiagnosticsString() { return lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)", connectTimeout, tcpNetworkRequestTimeout, idleChannelTimeout, idleEndpointTimeout, maxChannelsPerEndpoint, maxRequestsPerChannel, connectionEndpointRediscoveryEnabled); } /** * A builder for constructing {@link Options} instances. * * <h3>Using system properties to set the default {@link Options} used by an {@link Builder}</h3> * <p> * A default options instance is created when the {@link Builder} class is initialized. This instance specifies * the default options used by every {@link Builder} instance. In priority order the default options instance * is created from: * <ol> * <li>The JSON value of system property {@code azure.cosmos.directTcp.defaultOptions}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptions={\"maxChannelsPerEndpoint\":5,\"maxRequestsPerChannel\":30}}</pre> * </li> * <li>The contents of the JSON file located by system property {@code azure.cosmos.directTcp * .defaultOptionsFile}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file}</pre> * </li> * <li>The contents of JSON resource file {@code azure.cosmos.directTcp.defaultOptions.json}. * <p>Specifically, the resource file is read from this stream: * <pre>{@code RntbdTransportClient.class.getClassLoader().getResourceAsStream("azure.cosmos.directTcp.defaultOptions.json")}</pre> * <p>Example: <pre>{@code { * "bufferPageSize": 8192, * "connectionEndpointRediscoveryEnabled": false, * "connectTimeout": "PT5S", * "idleChannelTimeout": "PT0S", * "idleEndpointTimeout": "PT1H", * "maxBufferCapacity": 8388608, * "maxChannelsPerEndpoint": 130, * "maxRequestsPerChannel": 30, * "maxConcurrentRequestsPerEndpointOverride": -1, * "receiveHangDetectionTime": "PT1M5S", * "requestTimeout": "PT5S", * "requestTimerResolution": "PT100MS", * "sendHangDetectionTime": "PT10S", * "shutdownTimeout": "PT15S", * "threadCount": 16, * "transientTimeoutDetectionThreshold": 3 * }}</pre> * </li> * </ol> * <p>JSON value errors are logged and then ignored. If none of the above values are available or all available * values are in error, the default options instance is created from the private parameterless constructor for * {@link Options}. */ @SuppressWarnings("UnusedReturnValue") public static class Builder { private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions"; private static final Options DEFAULT_OPTIONS; static { Options options = null; try { final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME); if (string != null) { try { options = RntbdObjectMapper.readValue(string, Options.class); } catch (IOException error) { logger.error("failed to parse default Direct TCP options {} due to ", string, error); } } if (options == null) { final String path = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME + "File"); if (path != null) { try { options = RntbdObjectMapper.readValue(new File(path), Options.class); } catch (IOException error) { logger.error("failed to load default Direct TCP options from {} due to ", path, error); } } } if (options == null) { final ClassLoader loader = RntbdTransportClient.class.getClassLoader(); final String name = DEFAULT_OPTIONS_PROPERTY_NAME + ".json"; try (InputStream stream = loader.getResourceAsStream(name)) { if (stream != null) { options = RntbdObjectMapper.readValue(stream, Options.class); } } catch (IOException error) { logger.error("failed to load Direct TCP options from resource {} due to ", name, error); } } } finally { if (options == null) { logger.info("Using default Direct TCP options: {}", DEFAULT_OPTIONS_PROPERTY_NAME); DEFAULT_OPTIONS = new Options(ConnectionPolicy.getDefaultPolicy()); } else { logger.info("Updated default Direct TCP options from system property {}: {}", DEFAULT_OPTIONS_PROPERTY_NAME, options); DEFAULT_OPTIONS = options; } } } private int bufferPageSize; private Duration connectionAcquisitionTimeout; private boolean connectionEndpointRediscoveryEnabled; private Duration connectTimeout; private Duration idleChannelTimeout; private Duration idleChannelTimerResolution; private Duration idleEndpointTimeout; private int maxBufferCapacity; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; private int maxConcurrentRequestsPerEndpointOverride; private Duration receiveHangDetectionTime; private Duration tcpNetworkRequestTimeout; private Duration requestTimerResolution; private Duration sendHangDetectionTime; private Duration shutdownTimeout; private int threadCount; private UserAgentContainer userAgent; private boolean channelAcquisitionContextEnabled; private int ioThreadPriority; private int tcpKeepIntvl; private int tcpKeepIdle; private boolean preferTcpNative; private Duration sslHandshakeTimeoutMinDuration; private int transientTimeoutDetectionThreshold; public Builder(ConnectionPolicy connectionPolicy) { this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize; this.connectionAcquisitionTimeout = DEFAULT_OPTIONS.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = DEFAULT_OPTIONS.idleChannelTimerResolution; this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = DEFAULT_OPTIONS.maxBufferCapacity; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = DEFAULT_OPTIONS.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = DEFAULT_OPTIONS.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = DEFAULT_OPTIONS.requestTimerResolution; this.sendHangDetectionTime = DEFAULT_OPTIONS.sendHangDetectionTime; this.shutdownTimeout = DEFAULT_OPTIONS.shutdownTimeout; this.threadCount = DEFAULT_OPTIONS.threadCount; this.userAgent = DEFAULT_OPTIONS.userAgent; this.channelAcquisitionContextEnabled = DEFAULT_OPTIONS.channelAcquisitionContextEnabled; this.ioThreadPriority = DEFAULT_OPTIONS.ioThreadPriority; this.tcpKeepIntvl = DEFAULT_OPTIONS.tcpKeepIntvl; this.tcpKeepIdle = DEFAULT_OPTIONS.tcpKeepIdle; this.preferTcpNative = DEFAULT_OPTIONS.preferTcpNative; this.sslHandshakeTimeoutMinDuration = DEFAULT_OPTIONS.sslHandshakeTimeoutMinDuration; this.transientTimeoutDetectionThreshold = DEFAULT_OPTIONS.transientTimeoutDetectionThreshold; } public Builder bufferPageSize(final int value) { checkArgument(value >= 4096 && (value & (value - 1)) == 0, "expected value to be a power of 2 >= 4096, not %s", value); this.bufferPageSize = value; return this; } public Options build() { checkState(this.bufferPageSize <= this.maxBufferCapacity, "expected bufferPageSize (%s) <= maxBufferCapacity (%s)", this.bufferPageSize, this.maxBufferCapacity); return new Options(this); } public Builder connectionAcquisitionTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.connectionAcquisitionTimeout = value.compareTo(Duration.ZERO) < 0 ? Duration.ZERO : value; return this; } public Builder connectionEndpointRediscoveryEnabled(final boolean value) { this.connectionEndpointRediscoveryEnabled = value; return this; } public Builder connectionTimeout(final Duration value) { checkArgument(value == null || value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.connectTimeout = value; return this; } public Builder idleChannelTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.idleChannelTimeout = value; return this; } public Builder idleChannelTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) <= 0, "expected positive value, not %s", value); this.idleChannelTimerResolution = value; return this; } public Builder idleEndpointTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.idleEndpointTimeout = value; return this; } public Builder maxBufferCapacity(final int value) { checkArgument(value > 0 && (value & (value - 1)) == 0, "expected positive value, not %s", value); this.maxBufferCapacity = value; return this; } public Builder maxChannelsPerEndpoint(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxChannelsPerEndpoint = value; return this; } public Builder maxRequestsPerChannel(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxRequestsPerChannel = value; return this; } public Builder maxConcurrentRequestsPerEndpointOverride(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxConcurrentRequestsPerEndpointOverride = value; return this; } public Builder receiveHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.receiveHangDetectionTime = value; return this; } public Builder tcpNetworkRequestTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.tcpNetworkRequestTimeout = value; return this; } public Builder requestTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.requestTimerResolution = value; return this; } public Builder sendHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.sendHangDetectionTime = value; return this; } public Builder shutdownTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.shutdownTimeout = value; return this; } public Builder threadCount(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.threadCount = value; return this; } public Builder userAgent(final UserAgentContainer value) { checkNotNull(value, "expected non-null value"); this.userAgent = value; return this; } } } static final class JsonSerializer extends StdSerializer<RntbdTransportClient> { private static final long serialVersionUID = 1007663695768825670L; JsonSerializer() { super(RntbdTransportClient.class); } @Override public void serialize( final RntbdTransportClient value, final JsonGenerator generator, final SerializerProvider provider ) throws IOException { generator.writeStartObject(); generator.writeNumberField("id", value.id()); generator.writeBooleanField("isClosed", value.isClosed()); generator.writeObjectField("configuration", value.endpointProvider.config()); generator.writeObjectFieldStart("serviceEndpoints"); generator.writeNumberField("count", value.endpointCount()); generator.writeArrayFieldStart("items"); for (final Iterator<RntbdEndpoint> iterator = value.endpointProvider.list().iterator(); iterator.hasNext(); ) { generator.writeObject(iterator.next()); } generator.writeEndArray(); generator.writeEndObject(); generator.writeEndObject(); } } }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * NOTE: This context key name has been copied from {link Hooks * not exposed as public Api but package internal only * * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; private boolean channelAcquisitionContextEnabled; private final GlobalEndpointManager globalEndpointManager; /** * Initializes a newly created {@linkplain RntbdTransportClient} object. * * @param configs A {@link Configs} instance containing the {@link SslContext} to be used. * @param connectionPolicy The {@linkplain ConnectionPolicy connection policy} to be applied. * @param userAgent The {@linkplain UserAgentContainer user agent} identifying. * @param addressResolver The address resolver to be used for connection endpoint rediscovery, if connection * endpoint rediscovery is enabled by {@code connectionPolicy}. */ public RntbdTransportClient( final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this( new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext(), addressResolver, clientTelemetry, globalEndpointManager); } RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.globalEndpointManager = null; } RntbdTransportClient( final Options options, final SslContext sslContext, final IAddressResolver addressResolver, final ClientTelemetry clientTelemetry, final GlobalEndpointManager globalEndpointManager) { this.endpointProvider = new RntbdServiceEndpoint.Provider( this, options, checkNotNull(sslContext, "expected non-null sslContext"), addressResolver, clientTelemetry); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); this.channelAcquisitionContextEnabled = options.channelAcquisitionContextEnabled; this.globalEndpointManager = globalEndpointManager; } /** * {@code true} if this {@linkplain RntbdTransportClient client} is closed. * * @return {@code true} if this {@linkplain RntbdTransportClient client} is closed; {@code false} otherwise. */ public boolean isClosed() { return this.closed.get(); } /** * Closes this {@linkplain RntbdTransportClient client} and releases all resources associated with it. */ @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } @Override protected GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } /** * The number of {@linkplain RntbdEndpoint endpoints} allocated to this {@linkplain RntbdTransportClient client}. * * @return The number of {@linkplain RntbdEndpoint endpoints} associated with this {@linkplain RntbdTransportClient * client}. */ public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } /** * The integer identity of this {@linkplain RntbdTransportClient client}. * <p> * Clients are numbered sequentially based on the order in which they are initialized. * * @return The integer identity of this {@linkplain RntbdTransportClient client}. */ public long id() { return this.id; } /** * Issues a Direct TCP request to the specified Cosmos service address asynchronously. * * @param addressUri A Cosmos service address. * @param request The {@linkplain RxDocumentServiceRequest request} to issue. * * @return A {@link Mono} of type {@link StoreResponse} that will complete when the Direct TCP request completes. * I shI * @throws TransportException if this {@linkplain RntbdTransportClient client} is closed. */ @Override @Override public Mono<OpenConnectionResponse> openConnection(Uri addressUri) { checkNotNull(addressUri, "Argument 'addressUri' should not be null"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdEndpoint endpoint = this.endpointProvider.get(address); return Mono.fromFuture(endpoint.openConnection(addressUri)); } /** * The key-value pair used to classify and drill into metrics produced by this {@linkplain RntbdTransportClient * client}. * * @return The key-value pair used to classify and drill into metrics collected by this {@linkplain * RntbdTransportClient client}. */ public Tag tag() { return this.tag; } @Override public String toString() { return RntbdObjectMapper.toString(this); } private static Tag tag(long id) { return Tag.of(TAG_NAME, Strings.padStart(Long.toHexString(id).toUpperCase(Locale.ROOT), 4, '0')); } private void throwIfClosed() { if (this.closed.get()) { throw new TransportException(lenientFormat("%s is closed", this), null); } } public static final class Options { private static final int DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT = 10_000; @JsonProperty() private final int bufferPageSize; @JsonProperty() private final Duration connectionAcquisitionTimeout; @JsonProperty() private final boolean connectionEndpointRediscoveryEnabled; @JsonProperty() private final Duration connectTimeout; @JsonProperty() private final Duration idleChannelTimeout; @JsonProperty() private final Duration idleChannelTimerResolution; @JsonProperty() private final Duration idleEndpointTimeout; @JsonProperty() private final int maxBufferCapacity; @JsonProperty() private final int maxChannelsPerEndpoint; @JsonProperty() private final int maxRequestsPerChannel; @JsonProperty() private final int maxConcurrentRequestsPerEndpointOverride; @JsonProperty() private final Duration receiveHangDetectionTime; @JsonProperty() private final Duration tcpNetworkRequestTimeout; @JsonProperty() private final Duration requestTimerResolution; @JsonProperty() private final Duration sendHangDetectionTime; @JsonProperty() private final Duration shutdownTimeout; @JsonProperty() private final int threadCount; @JsonIgnore() private final UserAgentContainer userAgent; @JsonProperty() private final boolean channelAcquisitionContextEnabled; @JsonProperty() private final int ioThreadPriority; @JsonProperty() private final int tcpKeepIntvl; @JsonProperty() private final int tcpKeepIdle; @JsonProperty() private final boolean preferTcpNative; @JsonProperty() private final Duration sslHandshakeTimeoutMinDuration; /** * This property will be used in {@link RntbdClientChannelHealthChecker} to determine whether there is a readHang. * If there is no successful reads for up to receiveHangDetectionTime, and the number of consecutive timeout has also reached this config, * then SDK is going to treat the channel as unhealthy and close it. */ @JsonProperty() private final int transientTimeoutDetectionThreshold; @JsonCreator private Options() { this(ConnectionPolicy.getDefaultPolicy()); } private Options(final Builder builder) { this.bufferPageSize = builder.bufferPageSize; this.connectionAcquisitionTimeout = builder.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = builder.connectionEndpointRediscoveryEnabled; this.idleChannelTimeout = builder.idleChannelTimeout; this.idleChannelTimerResolution = builder.idleChannelTimerResolution; this.idleEndpointTimeout = builder.idleEndpointTimeout; this.maxBufferCapacity = builder.maxBufferCapacity; this.maxChannelsPerEndpoint = builder.maxChannelsPerEndpoint; this.maxRequestsPerChannel = builder.maxRequestsPerChannel; this.maxConcurrentRequestsPerEndpointOverride = builder.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = builder.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = builder.tcpNetworkRequestTimeout; this.requestTimerResolution = builder.requestTimerResolution; this.sendHangDetectionTime = builder.sendHangDetectionTime; this.shutdownTimeout = builder.shutdownTimeout; this.threadCount = builder.threadCount; this.userAgent = builder.userAgent; this.channelAcquisitionContextEnabled = builder.channelAcquisitionContextEnabled; this.ioThreadPriority = builder.ioThreadPriority; this.tcpKeepIntvl = builder.tcpKeepIntvl; this.tcpKeepIdle = builder.tcpKeepIdle; this.preferTcpNative = builder.preferTcpNative; this.sslHandshakeTimeoutMinDuration = builder.sslHandshakeTimeoutMinDuration; this.transientTimeoutDetectionThreshold = builder.transientTimeoutDetectionThreshold; this.connectTimeout = builder.connectTimeout == null ? builder.tcpNetworkRequestTimeout : builder.connectTimeout; } private Options(final ConnectionPolicy connectionPolicy) { this.bufferPageSize = 8192; this.connectionAcquisitionTimeout = Duration.ofSeconds(5L); this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = Duration.ofMillis(100); this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = 8192 << 10; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = -1; this.receiveHangDetectionTime = Duration.ofSeconds(65L); this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = Duration.ofMillis(100L); this.sendHangDetectionTime = Duration.ofSeconds(10L); this.shutdownTimeout = Duration.ofSeconds(15L); this.threadCount = connectionPolicy.getIoThreadCountPerCoreFactor() * Runtime.getRuntime().availableProcessors(); this.userAgent = new UserAgentContainer(); this.channelAcquisitionContextEnabled = false; this.ioThreadPriority = connectionPolicy.getIoThreadPriority(); this.tcpKeepIntvl = 1; this.tcpKeepIdle = 30; this.sslHandshakeTimeoutMinDuration = Duration.ofSeconds(5); this.transientTimeoutDetectionThreshold = 3; this.preferTcpNative = true; } public int bufferPageSize() { return this.bufferPageSize; } public Duration connectionAcquisitionTimeout() { return this.connectionAcquisitionTimeout; } public Duration connectTimeout() { return this.connectTimeout; } public Duration idleChannelTimeout() { return this.idleChannelTimeout; } public Duration idleChannelTimerResolution() { return this.idleChannelTimerResolution; } public Duration idleEndpointTimeout() { return this.idleEndpointTimeout; } public boolean isConnectionEndpointRediscoveryEnabled() { return this.connectionEndpointRediscoveryEnabled; } public int maxBufferCapacity() { return this.maxBufferCapacity; } public int maxChannelsPerEndpoint() { return this.maxChannelsPerEndpoint; } public int maxRequestsPerChannel() { return this.maxRequestsPerChannel; } public int maxConcurrentRequestsPerEndpoint() { if (this.maxConcurrentRequestsPerEndpointOverride > 0) { return maxConcurrentRequestsPerEndpointOverride; } return Math.max( DEFAULT_MIN_MAX_CONCURRENT_REQUESTS_PER_ENDPOINT, this.maxChannelsPerEndpoint * this.maxRequestsPerChannel); } public Duration receiveHangDetectionTime() { return this.receiveHangDetectionTime; } public Duration tcpNetworkRequestTimeout() { return this.tcpNetworkRequestTimeout; } public Duration requestTimerResolution() { return this.requestTimerResolution; } public Duration sendHangDetectionTime() { return this.sendHangDetectionTime; } public Duration shutdownTimeout() { return this.shutdownTimeout; } public int threadCount() { return this.threadCount; } public UserAgentContainer userAgent() { return this.userAgent; } public boolean isChannelAcquisitionContextEnabled() { return this.channelAcquisitionContextEnabled; } public int ioThreadPriority() { checkArgument( this.ioThreadPriority >= Thread.MIN_PRIORITY && this.ioThreadPriority <= Thread.MAX_PRIORITY, "Expect ioThread priority between [%s, %s]", Thread.MIN_PRIORITY, Thread.MAX_PRIORITY); return this.ioThreadPriority; } public int tcpKeepIntvl() { return this.tcpKeepIntvl; } public int tcpKeepIdle() { return this.tcpKeepIdle; } public boolean preferTcpNative() { return this.preferTcpNative; } public long sslHandshakeTimeoutInMillis() { return Math.max(this.sslHandshakeTimeoutMinDuration.toMillis(), this.connectTimeout.toMillis()); } public int transientTimeoutDetectionThreshold() { return this.transientTimeoutDetectionThreshold; } @Override public String toString() { return RntbdObjectMapper.toJson(this); } public String toDiagnosticsString() { return lenientFormat("(cto:%s, nrto:%s, icto:%s, ieto:%s, mcpe:%s, mrpc:%s, cer:%s)", connectTimeout, tcpNetworkRequestTimeout, idleChannelTimeout, idleEndpointTimeout, maxChannelsPerEndpoint, maxRequestsPerChannel, connectionEndpointRediscoveryEnabled); } /** * A builder for constructing {@link Options} instances. * * <h3>Using system properties to set the default {@link Options} used by an {@link Builder}</h3> * <p> * A default options instance is created when the {@link Builder} class is initialized. This instance specifies * the default options used by every {@link Builder} instance. In priority order the default options instance * is created from: * <ol> * <li>The JSON value of system property {@code azure.cosmos.directTcp.defaultOptions}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptions={\"maxChannelsPerEndpoint\":5,\"maxRequestsPerChannel\":30}}</pre> * </li> * <li>The contents of the JSON file located by system property {@code azure.cosmos.directTcp * .defaultOptionsFile}. * <p>Example: * <pre>{@code -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file}</pre> * </li> * <li>The contents of JSON resource file {@code azure.cosmos.directTcp.defaultOptions.json}. * <p>Specifically, the resource file is read from this stream: * <pre>{@code RntbdTransportClient.class.getClassLoader().getResourceAsStream("azure.cosmos.directTcp.defaultOptions.json")}</pre> * <p>Example: <pre>{@code { * "bufferPageSize": 8192, * "connectionEndpointRediscoveryEnabled": false, * "connectTimeout": "PT5S", * "idleChannelTimeout": "PT0S", * "idleEndpointTimeout": "PT1H", * "maxBufferCapacity": 8388608, * "maxChannelsPerEndpoint": 130, * "maxRequestsPerChannel": 30, * "maxConcurrentRequestsPerEndpointOverride": -1, * "receiveHangDetectionTime": "PT1M5S", * "requestTimeout": "PT5S", * "requestTimerResolution": "PT100MS", * "sendHangDetectionTime": "PT10S", * "shutdownTimeout": "PT15S", * "threadCount": 16, * "transientTimeoutDetectionThreshold": 3 * }}</pre> * </li> * </ol> * <p>JSON value errors are logged and then ignored. If none of the above values are available or all available * values are in error, the default options instance is created from the private parameterless constructor for * {@link Options}. */ @SuppressWarnings("UnusedReturnValue") public static class Builder { private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions"; private static final Options DEFAULT_OPTIONS; static { Options options = null; try { final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME); if (string != null) { try { options = RntbdObjectMapper.readValue(string, Options.class); } catch (IOException error) { logger.error("failed to parse default Direct TCP options {} due to ", string, error); } } if (options == null) { final String path = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME + "File"); if (path != null) { try { options = RntbdObjectMapper.readValue(new File(path), Options.class); } catch (IOException error) { logger.error("failed to load default Direct TCP options from {} due to ", path, error); } } } if (options == null) { final ClassLoader loader = RntbdTransportClient.class.getClassLoader(); final String name = DEFAULT_OPTIONS_PROPERTY_NAME + ".json"; try (InputStream stream = loader.getResourceAsStream(name)) { if (stream != null) { options = RntbdObjectMapper.readValue(stream, Options.class); } } catch (IOException error) { logger.error("failed to load Direct TCP options from resource {} due to ", name, error); } } } finally { if (options == null) { logger.info("Using default Direct TCP options: {}", DEFAULT_OPTIONS_PROPERTY_NAME); DEFAULT_OPTIONS = new Options(ConnectionPolicy.getDefaultPolicy()); } else { logger.info("Updated default Direct TCP options from system property {}: {}", DEFAULT_OPTIONS_PROPERTY_NAME, options); DEFAULT_OPTIONS = options; } } } private int bufferPageSize; private Duration connectionAcquisitionTimeout; private boolean connectionEndpointRediscoveryEnabled; private Duration connectTimeout; private Duration idleChannelTimeout; private Duration idleChannelTimerResolution; private Duration idleEndpointTimeout; private int maxBufferCapacity; private int maxChannelsPerEndpoint; private int maxRequestsPerChannel; private int maxConcurrentRequestsPerEndpointOverride; private Duration receiveHangDetectionTime; private Duration tcpNetworkRequestTimeout; private Duration requestTimerResolution; private Duration sendHangDetectionTime; private Duration shutdownTimeout; private int threadCount; private UserAgentContainer userAgent; private boolean channelAcquisitionContextEnabled; private int ioThreadPriority; private int tcpKeepIntvl; private int tcpKeepIdle; private boolean preferTcpNative; private Duration sslHandshakeTimeoutMinDuration; private int transientTimeoutDetectionThreshold; public Builder(ConnectionPolicy connectionPolicy) { this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize; this.connectionAcquisitionTimeout = DEFAULT_OPTIONS.connectionAcquisitionTimeout; this.connectionEndpointRediscoveryEnabled = connectionPolicy.isTcpConnectionEndpointRediscoveryEnabled(); this.connectTimeout = connectionPolicy.getConnectTimeout(); this.idleChannelTimeout = connectionPolicy.getIdleTcpConnectionTimeout(); this.idleChannelTimerResolution = DEFAULT_OPTIONS.idleChannelTimerResolution; this.idleEndpointTimeout = connectionPolicy.getIdleTcpEndpointTimeout(); this.maxBufferCapacity = DEFAULT_OPTIONS.maxBufferCapacity; this.maxChannelsPerEndpoint = connectionPolicy.getMaxConnectionsPerEndpoint(); this.maxRequestsPerChannel = connectionPolicy.getMaxRequestsPerConnection(); this.maxConcurrentRequestsPerEndpointOverride = DEFAULT_OPTIONS.maxConcurrentRequestsPerEndpointOverride; this.receiveHangDetectionTime = DEFAULT_OPTIONS.receiveHangDetectionTime; this.tcpNetworkRequestTimeout = connectionPolicy.getTcpNetworkRequestTimeout(); this.requestTimerResolution = DEFAULT_OPTIONS.requestTimerResolution; this.sendHangDetectionTime = DEFAULT_OPTIONS.sendHangDetectionTime; this.shutdownTimeout = DEFAULT_OPTIONS.shutdownTimeout; this.threadCount = DEFAULT_OPTIONS.threadCount; this.userAgent = DEFAULT_OPTIONS.userAgent; this.channelAcquisitionContextEnabled = DEFAULT_OPTIONS.channelAcquisitionContextEnabled; this.ioThreadPriority = DEFAULT_OPTIONS.ioThreadPriority; this.tcpKeepIntvl = DEFAULT_OPTIONS.tcpKeepIntvl; this.tcpKeepIdle = DEFAULT_OPTIONS.tcpKeepIdle; this.preferTcpNative = DEFAULT_OPTIONS.preferTcpNative; this.sslHandshakeTimeoutMinDuration = DEFAULT_OPTIONS.sslHandshakeTimeoutMinDuration; this.transientTimeoutDetectionThreshold = DEFAULT_OPTIONS.transientTimeoutDetectionThreshold; } public Builder bufferPageSize(final int value) { checkArgument(value >= 4096 && (value & (value - 1)) == 0, "expected value to be a power of 2 >= 4096, not %s", value); this.bufferPageSize = value; return this; } public Options build() { checkState(this.bufferPageSize <= this.maxBufferCapacity, "expected bufferPageSize (%s) <= maxBufferCapacity (%s)", this.bufferPageSize, this.maxBufferCapacity); return new Options(this); } public Builder connectionAcquisitionTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.connectionAcquisitionTimeout = value.compareTo(Duration.ZERO) < 0 ? Duration.ZERO : value; return this; } public Builder connectionEndpointRediscoveryEnabled(final boolean value) { this.connectionEndpointRediscoveryEnabled = value; return this; } public Builder connectionTimeout(final Duration value) { checkArgument(value == null || value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.connectTimeout = value; return this; } public Builder idleChannelTimeout(final Duration value) { checkNotNull(value, "expected non-null value"); this.idleChannelTimeout = value; return this; } public Builder idleChannelTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) <= 0, "expected positive value, not %s", value); this.idleChannelTimerResolution = value; return this; } public Builder idleEndpointTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.idleEndpointTimeout = value; return this; } public Builder maxBufferCapacity(final int value) { checkArgument(value > 0 && (value & (value - 1)) == 0, "expected positive value, not %s", value); this.maxBufferCapacity = value; return this; } public Builder maxChannelsPerEndpoint(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxChannelsPerEndpoint = value; return this; } public Builder maxRequestsPerChannel(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxRequestsPerChannel = value; return this; } public Builder maxConcurrentRequestsPerEndpointOverride(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.maxConcurrentRequestsPerEndpointOverride = value; return this; } public Builder receiveHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.receiveHangDetectionTime = value; return this; } public Builder tcpNetworkRequestTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.tcpNetworkRequestTimeout = value; return this; } public Builder requestTimerResolution(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.requestTimerResolution = value; return this; } public Builder sendHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.sendHangDetectionTime = value; return this; } public Builder shutdownTimeout(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", value); this.shutdownTimeout = value; return this; } public Builder threadCount(final int value) { checkArgument(value > 0, "expected positive value, not %s", value); this.threadCount = value; return this; } public Builder userAgent(final UserAgentContainer value) { checkNotNull(value, "expected non-null value"); this.userAgent = value; return this; } } } static final class JsonSerializer extends StdSerializer<RntbdTransportClient> { private static final long serialVersionUID = 1007663695768825670L; JsonSerializer() { super(RntbdTransportClient.class); } @Override public void serialize( final RntbdTransportClient value, final JsonGenerator generator, final SerializerProvider provider ) throws IOException { generator.writeStartObject(); generator.writeNumberField("id", value.id()); generator.writeBooleanField("isClosed", value.isClosed()); generator.writeObjectField("configuration", value.endpointProvider.config()); generator.writeObjectFieldStart("serviceEndpoints"); generator.writeNumberField("count", value.endpointCount()); generator.writeArrayFieldStart("items"); for (final Iterator<RntbdEndpoint> iterator = value.endpointProvider.list().iterator(); iterator.hasNext(); ) { generator.writeObject(iterator.next()); } generator.writeEndArray(); generator.writeEndObject(); generator.writeEndObject(); } } }
```suggestion LongRunningOperationStatus matchStatus = SUCCESSFULLY_COMPLETED; int[] invocationCount = new int[1]; invocationCount[0] = -1; ```
public void waitUntilShouldPollToCompletion() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = SUCCESSFULLY_COMPLETED; int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(matchStatus, poller.waitUntil(matchStatus).getStatus()); assertEquals(2, invocationCount[0]); }
public void waitUntilShouldPollToCompletion() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = SUCCESSFULLY_COMPLETED; int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(matchStatus, poller.waitUntil(matchStatus).getStatus()); assertEquals(2, invocationCount[0]); }
class SimpleSyncPollerTests { @Mock private Function<PollingContext<Response>, Response> activationOperation; @Mock private Function<PollingContext<Response>, PollResponse<Response>> activationOperationWithResponse; @Mock private Function<PollingContext<Response>, PollResponse<Response>> pollOperation; @Mock private Function<PollingContext<Response>, CertificateOutput> fetchResultOperation; @Mock private BiFunction<PollingContext<Response>, PollResponse<Response>, Response> cancelOperation; private AutoCloseable openMocks; @BeforeEach public void beforeTest() { this.openMocks = MockitoAnnotations.openMocks(this); } @AfterEach public void afterTest() throws Exception { openMocks.close(); Mockito.framework().clearInlineMock(this); } @Test public void noPollingForSynchronouslyCompletedActivationInSyncPollerTest() { int[] activationCallCount = new int[1]; when(activationOperationWithResponse.apply(any())) .thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { activationCallCount[0]++; return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("ActivationDone")); }); SyncPoller<Response, CertificateOutput> syncPoller = new SimpleSyncPoller<>(Duration.ofMillis(10), activationOperationWithResponse, pollOperation, cancelOperation, fetchResultOperation); when(pollOperation.apply(any())).thenThrow( new RuntimeException("Polling shouldn't happen for synchronously completed activation.")); try { PollResponse<Response> response = syncPoller.waitForCompletion(Duration.ofSeconds(1)); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); assertEquals(1, activationCallCount[0]); } catch (Exception e) { fail("SyncPoller did not complete on activation", e); } } @Test public void syncPollerConstructorPollIntervalZero() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ZERO, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNegative() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(-1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( null, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncConstructorActivationOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), null, pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), null, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorCancelOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, null, fetchResultOperation)); } @Test public void syncPollerConstructorFetchResultOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, null)); } @Test public void syncPollerShouldCallActivationFromConstructor() { Boolean[] activationCalled = new Boolean[1]; activationCalled[0] = false; when(activationOperation.apply(any())).thenAnswer((Answer<Response>) invocationOnMock -> { activationCalled[0] = true; return new Response("ActivationDone"); }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>(Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); Assertions.assertTrue(activationCalled[0]); } @Test public void eachPollShouldReceiveLastPollResponse() { when(activationOperation.apply(any())).thenReturn(new Response("A")); when(pollOperation.apply(any())).thenAnswer((Answer<?>) invocation -> { assertEquals(1, invocation.getArguments().length); Assertions.assertTrue(invocation.getArguments()[0] instanceof PollingContext); PollingContext<Response> pollingContext = (PollingContext<Response>) invocation.getArguments()[0]; Assertions.assertNotNull(pollingContext.getActivationResponse()); Assertions.assertNotNull(pollingContext.getLatestResponse()); PollResponse<Response> latestResponse = pollingContext.getLatestResponse(); Assertions.assertNotNull(latestResponse); PollResponse<Response> nextResponse = new PollResponse<>(IN_PROGRESS, new Response(latestResponse.getValue().toString() + "A"), Duration.ofMillis(10)); return nextResponse; }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: AA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: AAA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: Response: AAAA")); } @Test public void waitForCompletionShouldReturnTerminalPollResponse() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(response2.getValue().getResponse(), poller.waitForCompletion().getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); } @Test public void getResultShouldPollUntilCompletionAndFetchResult() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after terminal response"); } }); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); assertEquals(2, invocationCount[0]); } @Test public void getResultShouldNotPollOnCompletedPoller() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { Assertions.assertTrue(true, "A Poll after completion should be called"); return null; }); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); } @Test public void waitUntilShouldPollAfterMatchingStatus() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = LongRunningOperationStatus.fromString("OTHER_1", false); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(2, invocationCount[0]); } @Test public void verifyExceptionPropagationFromPollingOperationSyncPoller() { final Response activationResponse = new Response("Foo"); when(activationOperation.apply(any())).thenReturn(activationResponse); final AtomicReference<Integer> cnt = new AtomicReference<>(0); pollOperation = (pollingContext) -> { cnt.getAndSet(cnt.get() + 1); if (cnt.get() <= 2) { return new PollResponse<>(IN_PROGRESS, new Response("1")); } else if (cnt.get() == 3) { throw new RuntimeException("Polling operation failed!"); } else if (cnt.get() == 4) { return new PollResponse<>(IN_PROGRESS, new Response("2")); } else { return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("3")); } }; SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); RuntimeException exception = assertThrows(RuntimeException.class, poller::getFinalResult); assertTrue(exception.getMessage().contains("Polling operation failed!")); } @Test public void testPollerFluxError() throws InterruptedException { IllegalArgumentException expectedException = new IllegalArgumentException(); PollerFlux<String, String> pollerFlux = error(expectedException); CountDownLatch countDownLatch = new CountDownLatch(1); pollerFlux.subscribe( response -> Assertions.fail("Did not expect a response"), ex -> { countDownLatch.countDown(); Assertions.assertSame(expectedException, ex); }, () -> Assertions.fail("Did not expect the flux to complete") ); boolean completed = countDownLatch.await(1, TimeUnit.SECONDS); Assertions.assertTrue(completed); } @Test public static class Response { private final String response; public Response(String response) { this.response = response; } public String getResponse() { return response; } @Override public String toString() { return "Response: " + response; } } public static class CertificateOutput { String name; public CertificateOutput(String certName) { name = certName; } public String getName() { return name; } } }
class SimpleSyncPollerTests { @Mock private Function<PollingContext<Response>, Response> activationOperation; @Mock private Function<PollingContext<Response>, PollResponse<Response>> activationOperationWithResponse; @Mock private Function<PollingContext<Response>, PollResponse<Response>> pollOperation; @Mock private Function<PollingContext<Response>, CertificateOutput> fetchResultOperation; @Mock private BiFunction<PollingContext<Response>, PollResponse<Response>, Response> cancelOperation; private AutoCloseable openMocks; @BeforeEach public void beforeTest() { this.openMocks = MockitoAnnotations.openMocks(this); } @AfterEach public void afterTest() throws Exception { openMocks.close(); Mockito.framework().clearInlineMock(this); } @Test public void noPollingForSynchronouslyCompletedActivationInSyncPollerTest() { int[] activationCallCount = new int[1]; when(activationOperationWithResponse.apply(any())) .thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { activationCallCount[0]++; return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("ActivationDone")); }); SyncPoller<Response, CertificateOutput> syncPoller = new SimpleSyncPoller<>(Duration.ofMillis(10), activationOperationWithResponse, pollOperation, cancelOperation, fetchResultOperation); when(pollOperation.apply(any())).thenThrow( new RuntimeException("Polling shouldn't happen for synchronously completed activation.")); try { PollResponse<Response> response = syncPoller.waitForCompletion(Duration.ofSeconds(1)); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); assertEquals(1, activationCallCount[0]); } catch (Exception e) { fail("SyncPoller did not complete on activation", e); } } @Test public void syncPollerConstructorPollIntervalZero() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ZERO, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNegative() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(-1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( null, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncConstructorActivationOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), null, pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), null, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorCancelOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, null, fetchResultOperation)); } @Test public void syncPollerConstructorFetchResultOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, null)); } @Test public void syncPollerShouldCallActivationFromConstructor() { Boolean[] activationCalled = new Boolean[1]; activationCalled[0] = false; when(activationOperation.apply(any())).thenAnswer((Answer<Response>) invocationOnMock -> { activationCalled[0] = true; return new Response("ActivationDone"); }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>(Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); Assertions.assertTrue(activationCalled[0]); } @Test public void eachPollShouldReceiveLastPollResponse() { when(activationOperation.apply(any())).thenReturn(new Response("A")); when(pollOperation.apply(any())).thenAnswer((Answer<?>) invocation -> { assertEquals(1, invocation.getArguments().length); Assertions.assertTrue(invocation.getArguments()[0] instanceof PollingContext); PollingContext<Response> pollingContext = (PollingContext<Response>) invocation.getArguments()[0]; Assertions.assertNotNull(pollingContext.getActivationResponse()); Assertions.assertNotNull(pollingContext.getLatestResponse()); PollResponse<Response> latestResponse = pollingContext.getLatestResponse(); Assertions.assertNotNull(latestResponse); PollResponse<Response> nextResponse = new PollResponse<>(IN_PROGRESS, new Response(latestResponse.getValue().toString() + "A"), Duration.ofMillis(10)); return nextResponse; }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: AA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: AAA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: Response: AAAA")); } @Test public void waitForCompletionShouldReturnTerminalPollResponse() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(response2.getValue().getResponse(), poller.waitForCompletion().getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); } @Test public void getResultShouldPollUntilCompletionAndFetchResult() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after terminal response"); } }); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); assertEquals(2, invocationCount[0]); } @Test public void getResultShouldNotPollOnCompletedPoller() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { Assertions.assertTrue(true, "A Poll after completion should be called"); return null; }); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); } @Test public void waitUntilShouldPollAfterMatchingStatus() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = LongRunningOperationStatus.fromString("OTHER_1", false); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(2, invocationCount[0]); } @Test public void verifyExceptionPropagationFromPollingOperationSyncPoller() { final Response activationResponse = new Response("Foo"); when(activationOperation.apply(any())).thenReturn(activationResponse); final AtomicReference<Integer> cnt = new AtomicReference<>(0); pollOperation = (pollingContext) -> { cnt.getAndSet(cnt.get() + 1); if (cnt.get() <= 2) { return new PollResponse<>(IN_PROGRESS, new Response("1")); } else if (cnt.get() == 3) { throw new RuntimeException("Polling operation failed!"); } else if (cnt.get() == 4) { return new PollResponse<>(IN_PROGRESS, new Response("2")); } else { return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("3")); } }; SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); RuntimeException exception = assertThrows(RuntimeException.class, poller::getFinalResult); assertTrue(exception.getMessage().contains("Polling operation failed!")); } @Test public void testPollerFluxError() throws InterruptedException { IllegalArgumentException expectedException = new IllegalArgumentException(); PollerFlux<String, String> pollerFlux = error(expectedException); CountDownLatch countDownLatch = new CountDownLatch(1); pollerFlux.subscribe( response -> Assertions.fail("Did not expect a response"), ex -> { countDownLatch.countDown(); Assertions.assertSame(expectedException, ex); }, () -> Assertions.fail("Did not expect the flux to complete") ); boolean completed = countDownLatch.await(1, TimeUnit.SECONDS); Assertions.assertTrue(completed); } @Test public static class Response { private final String response; public Response(String response) { this.response = response; } public String getResponse() { return response; } @Override public String toString() { return "Response: " + response; } } public static class CertificateOutput { String name; public CertificateOutput(String certName) { name = certName; } public String getName() { return name; } } }
should be 2?
public void waitUntilShouldPollToCompletion() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = SUCCESSFULLY_COMPLETED; int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(matchStatus, poller.waitUntil(matchStatus).getStatus()); assertEquals(2, invocationCount[0]); }
new Response("1"), Duration.ofMillis(10));
public void waitUntilShouldPollToCompletion() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = SUCCESSFULLY_COMPLETED; int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(matchStatus, poller.waitUntil(matchStatus).getStatus()); assertEquals(2, invocationCount[0]); }
class SimpleSyncPollerTests { @Mock private Function<PollingContext<Response>, Response> activationOperation; @Mock private Function<PollingContext<Response>, PollResponse<Response>> activationOperationWithResponse; @Mock private Function<PollingContext<Response>, PollResponse<Response>> pollOperation; @Mock private Function<PollingContext<Response>, CertificateOutput> fetchResultOperation; @Mock private BiFunction<PollingContext<Response>, PollResponse<Response>, Response> cancelOperation; private AutoCloseable openMocks; @BeforeEach public void beforeTest() { this.openMocks = MockitoAnnotations.openMocks(this); } @AfterEach public void afterTest() throws Exception { openMocks.close(); Mockito.framework().clearInlineMock(this); } @Test public void noPollingForSynchronouslyCompletedActivationInSyncPollerTest() { int[] activationCallCount = new int[1]; when(activationOperationWithResponse.apply(any())) .thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { activationCallCount[0]++; return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("ActivationDone")); }); SyncPoller<Response, CertificateOutput> syncPoller = new SimpleSyncPoller<>(Duration.ofMillis(10), activationOperationWithResponse, pollOperation, cancelOperation, fetchResultOperation); when(pollOperation.apply(any())).thenThrow( new RuntimeException("Polling shouldn't happen for synchronously completed activation.")); try { PollResponse<Response> response = syncPoller.waitForCompletion(Duration.ofSeconds(1)); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); assertEquals(1, activationCallCount[0]); } catch (Exception e) { fail("SyncPoller did not complete on activation", e); } } @Test public void syncPollerConstructorPollIntervalZero() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ZERO, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNegative() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(-1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( null, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncConstructorActivationOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), null, pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), null, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorCancelOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, null, fetchResultOperation)); } @Test public void syncPollerConstructorFetchResultOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, null)); } @Test public void syncPollerShouldCallActivationFromConstructor() { Boolean[] activationCalled = new Boolean[1]; activationCalled[0] = false; when(activationOperation.apply(any())).thenAnswer((Answer<Response>) invocationOnMock -> { activationCalled[0] = true; return new Response("ActivationDone"); }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>(Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); Assertions.assertTrue(activationCalled[0]); } @Test public void eachPollShouldReceiveLastPollResponse() { when(activationOperation.apply(any())).thenReturn(new Response("A")); when(pollOperation.apply(any())).thenAnswer((Answer<?>) invocation -> { assertEquals(1, invocation.getArguments().length); Assertions.assertTrue(invocation.getArguments()[0] instanceof PollingContext); PollingContext<Response> pollingContext = (PollingContext<Response>) invocation.getArguments()[0]; Assertions.assertNotNull(pollingContext.getActivationResponse()); Assertions.assertNotNull(pollingContext.getLatestResponse()); PollResponse<Response> latestResponse = pollingContext.getLatestResponse(); Assertions.assertNotNull(latestResponse); PollResponse<Response> nextResponse = new PollResponse<>(IN_PROGRESS, new Response(latestResponse.getValue().toString() + "A"), Duration.ofMillis(10)); return nextResponse; }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: AA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: AAA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: Response: AAAA")); } @Test public void waitForCompletionShouldReturnTerminalPollResponse() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(response2.getValue().getResponse(), poller.waitForCompletion().getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); } @Test public void getResultShouldPollUntilCompletionAndFetchResult() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after terminal response"); } }); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); assertEquals(2, invocationCount[0]); } @Test public void getResultShouldNotPollOnCompletedPoller() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { Assertions.assertTrue(true, "A Poll after completion should be called"); return null; }); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); } @Test public void waitUntilShouldPollAfterMatchingStatus() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = LongRunningOperationStatus.fromString("OTHER_1", false); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(2, invocationCount[0]); } @Test public void verifyExceptionPropagationFromPollingOperationSyncPoller() { final Response activationResponse = new Response("Foo"); when(activationOperation.apply(any())).thenReturn(activationResponse); final AtomicReference<Integer> cnt = new AtomicReference<>(0); pollOperation = (pollingContext) -> { cnt.getAndSet(cnt.get() + 1); if (cnt.get() <= 2) { return new PollResponse<>(IN_PROGRESS, new Response("1")); } else if (cnt.get() == 3) { throw new RuntimeException("Polling operation failed!"); } else if (cnt.get() == 4) { return new PollResponse<>(IN_PROGRESS, new Response("2")); } else { return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("3")); } }; SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); RuntimeException exception = assertThrows(RuntimeException.class, poller::getFinalResult); assertTrue(exception.getMessage().contains("Polling operation failed!")); } @Test public void testPollerFluxError() throws InterruptedException { IllegalArgumentException expectedException = new IllegalArgumentException(); PollerFlux<String, String> pollerFlux = error(expectedException); CountDownLatch countDownLatch = new CountDownLatch(1); pollerFlux.subscribe( response -> Assertions.fail("Did not expect a response"), ex -> { countDownLatch.countDown(); Assertions.assertSame(expectedException, ex); }, () -> Assertions.fail("Did not expect the flux to complete") ); boolean completed = countDownLatch.await(1, TimeUnit.SECONDS); Assertions.assertTrue(completed); } @Test public static class Response { private final String response; public Response(String response) { this.response = response; } public String getResponse() { return response; } @Override public String toString() { return "Response: " + response; } } public static class CertificateOutput { String name; public CertificateOutput(String certName) { name = certName; } public String getName() { return name; } } }
class SimpleSyncPollerTests { @Mock private Function<PollingContext<Response>, Response> activationOperation; @Mock private Function<PollingContext<Response>, PollResponse<Response>> activationOperationWithResponse; @Mock private Function<PollingContext<Response>, PollResponse<Response>> pollOperation; @Mock private Function<PollingContext<Response>, CertificateOutput> fetchResultOperation; @Mock private BiFunction<PollingContext<Response>, PollResponse<Response>, Response> cancelOperation; private AutoCloseable openMocks; @BeforeEach public void beforeTest() { this.openMocks = MockitoAnnotations.openMocks(this); } @AfterEach public void afterTest() throws Exception { openMocks.close(); Mockito.framework().clearInlineMock(this); } @Test public void noPollingForSynchronouslyCompletedActivationInSyncPollerTest() { int[] activationCallCount = new int[1]; when(activationOperationWithResponse.apply(any())) .thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { activationCallCount[0]++; return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("ActivationDone")); }); SyncPoller<Response, CertificateOutput> syncPoller = new SimpleSyncPoller<>(Duration.ofMillis(10), activationOperationWithResponse, pollOperation, cancelOperation, fetchResultOperation); when(pollOperation.apply(any())).thenThrow( new RuntimeException("Polling shouldn't happen for synchronously completed activation.")); try { PollResponse<Response> response = syncPoller.waitForCompletion(Duration.ofSeconds(1)); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); assertEquals(1, activationCallCount[0]); } catch (Exception e) { fail("SyncPoller did not complete on activation", e); } } @Test public void syncPollerConstructorPollIntervalZero() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ZERO, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNegative() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(-1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( null, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncConstructorActivationOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), null, pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), null, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorCancelOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, null, fetchResultOperation)); } @Test public void syncPollerConstructorFetchResultOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, null)); } @Test public void syncPollerShouldCallActivationFromConstructor() { Boolean[] activationCalled = new Boolean[1]; activationCalled[0] = false; when(activationOperation.apply(any())).thenAnswer((Answer<Response>) invocationOnMock -> { activationCalled[0] = true; return new Response("ActivationDone"); }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>(Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); Assertions.assertTrue(activationCalled[0]); } @Test public void eachPollShouldReceiveLastPollResponse() { when(activationOperation.apply(any())).thenReturn(new Response("A")); when(pollOperation.apply(any())).thenAnswer((Answer<?>) invocation -> { assertEquals(1, invocation.getArguments().length); Assertions.assertTrue(invocation.getArguments()[0] instanceof PollingContext); PollingContext<Response> pollingContext = (PollingContext<Response>) invocation.getArguments()[0]; Assertions.assertNotNull(pollingContext.getActivationResponse()); Assertions.assertNotNull(pollingContext.getLatestResponse()); PollResponse<Response> latestResponse = pollingContext.getLatestResponse(); Assertions.assertNotNull(latestResponse); PollResponse<Response> nextResponse = new PollResponse<>(IN_PROGRESS, new Response(latestResponse.getValue().toString() + "A"), Duration.ofMillis(10)); return nextResponse; }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: AA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: AAA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: Response: AAAA")); } @Test public void waitForCompletionShouldReturnTerminalPollResponse() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(response2.getValue().getResponse(), poller.waitForCompletion().getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); } @Test public void getResultShouldPollUntilCompletionAndFetchResult() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after terminal response"); } }); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); assertEquals(2, invocationCount[0]); } @Test public void getResultShouldNotPollOnCompletedPoller() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { Assertions.assertTrue(true, "A Poll after completion should be called"); return null; }); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); } @Test public void waitUntilShouldPollAfterMatchingStatus() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = LongRunningOperationStatus.fromString("OTHER_1", false); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(2, invocationCount[0]); } @Test public void verifyExceptionPropagationFromPollingOperationSyncPoller() { final Response activationResponse = new Response("Foo"); when(activationOperation.apply(any())).thenReturn(activationResponse); final AtomicReference<Integer> cnt = new AtomicReference<>(0); pollOperation = (pollingContext) -> { cnt.getAndSet(cnt.get() + 1); if (cnt.get() <= 2) { return new PollResponse<>(IN_PROGRESS, new Response("1")); } else if (cnt.get() == 3) { throw new RuntimeException("Polling operation failed!"); } else if (cnt.get() == 4) { return new PollResponse<>(IN_PROGRESS, new Response("2")); } else { return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("3")); } }; SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); RuntimeException exception = assertThrows(RuntimeException.class, poller::getFinalResult); assertTrue(exception.getMessage().contains("Polling operation failed!")); } @Test public void testPollerFluxError() throws InterruptedException { IllegalArgumentException expectedException = new IllegalArgumentException(); PollerFlux<String, String> pollerFlux = error(expectedException); CountDownLatch countDownLatch = new CountDownLatch(1); pollerFlux.subscribe( response -> Assertions.fail("Did not expect a response"), ex -> { countDownLatch.countDown(); Assertions.assertSame(expectedException, ex); }, () -> Assertions.fail("Did not expect the flux to complete") ); boolean completed = countDownLatch.await(1, TimeUnit.SECONDS); Assertions.assertTrue(completed); } @Test public static class Response { private final String response; public Response(String response) { this.response = response; } public String getResponse() { return response; } @Override public String toString() { return "Response: " + response; } } public static class CertificateOutput { String name; public CertificateOutput(String certName) { name = certName; } public String getName() { return name; } } }
2?
public void waitUntilShouldPollToCompletion() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = SUCCESSFULLY_COMPLETED; int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(matchStatus, poller.waitUntil(matchStatus).getStatus()); assertEquals(2, invocationCount[0]); }
new Response("1"), Duration.ofMillis(10));
public void waitUntilShouldPollToCompletion() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = SUCCESSFULLY_COMPLETED; int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(matchStatus, poller.waitUntil(matchStatus).getStatus()); assertEquals(2, invocationCount[0]); }
class SimpleSyncPollerTests { @Mock private Function<PollingContext<Response>, Response> activationOperation; @Mock private Function<PollingContext<Response>, PollResponse<Response>> activationOperationWithResponse; @Mock private Function<PollingContext<Response>, PollResponse<Response>> pollOperation; @Mock private Function<PollingContext<Response>, CertificateOutput> fetchResultOperation; @Mock private BiFunction<PollingContext<Response>, PollResponse<Response>, Response> cancelOperation; private AutoCloseable openMocks; @BeforeEach public void beforeTest() { this.openMocks = MockitoAnnotations.openMocks(this); } @AfterEach public void afterTest() throws Exception { openMocks.close(); Mockito.framework().clearInlineMock(this); } @Test public void noPollingForSynchronouslyCompletedActivationInSyncPollerTest() { int[] activationCallCount = new int[1]; when(activationOperationWithResponse.apply(any())) .thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { activationCallCount[0]++; return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("ActivationDone")); }); SyncPoller<Response, CertificateOutput> syncPoller = new SimpleSyncPoller<>(Duration.ofMillis(10), activationOperationWithResponse, pollOperation, cancelOperation, fetchResultOperation); when(pollOperation.apply(any())).thenThrow( new RuntimeException("Polling shouldn't happen for synchronously completed activation.")); try { PollResponse<Response> response = syncPoller.waitForCompletion(Duration.ofSeconds(1)); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); assertEquals(1, activationCallCount[0]); } catch (Exception e) { fail("SyncPoller did not complete on activation", e); } } @Test public void syncPollerConstructorPollIntervalZero() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ZERO, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNegative() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(-1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( null, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncConstructorActivationOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), null, pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), null, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorCancelOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, null, fetchResultOperation)); } @Test public void syncPollerConstructorFetchResultOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, null)); } @Test public void syncPollerShouldCallActivationFromConstructor() { Boolean[] activationCalled = new Boolean[1]; activationCalled[0] = false; when(activationOperation.apply(any())).thenAnswer((Answer<Response>) invocationOnMock -> { activationCalled[0] = true; return new Response("ActivationDone"); }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>(Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); Assertions.assertTrue(activationCalled[0]); } @Test public void eachPollShouldReceiveLastPollResponse() { when(activationOperation.apply(any())).thenReturn(new Response("A")); when(pollOperation.apply(any())).thenAnswer((Answer<?>) invocation -> { assertEquals(1, invocation.getArguments().length); Assertions.assertTrue(invocation.getArguments()[0] instanceof PollingContext); PollingContext<Response> pollingContext = (PollingContext<Response>) invocation.getArguments()[0]; Assertions.assertNotNull(pollingContext.getActivationResponse()); Assertions.assertNotNull(pollingContext.getLatestResponse()); PollResponse<Response> latestResponse = pollingContext.getLatestResponse(); Assertions.assertNotNull(latestResponse); PollResponse<Response> nextResponse = new PollResponse<>(IN_PROGRESS, new Response(latestResponse.getValue().toString() + "A"), Duration.ofMillis(10)); return nextResponse; }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: AA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: AAA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: Response: AAAA")); } @Test public void waitForCompletionShouldReturnTerminalPollResponse() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(response2.getValue().getResponse(), poller.waitForCompletion().getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); } @Test public void getResultShouldPollUntilCompletionAndFetchResult() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after terminal response"); } }); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); assertEquals(2, invocationCount[0]); } @Test public void getResultShouldNotPollOnCompletedPoller() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { Assertions.assertTrue(true, "A Poll after completion should be called"); return null; }); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); } @Test public void waitUntilShouldPollAfterMatchingStatus() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = LongRunningOperationStatus.fromString("OTHER_1", false); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(2, invocationCount[0]); } @Test public void verifyExceptionPropagationFromPollingOperationSyncPoller() { final Response activationResponse = new Response("Foo"); when(activationOperation.apply(any())).thenReturn(activationResponse); final AtomicReference<Integer> cnt = new AtomicReference<>(0); pollOperation = (pollingContext) -> { cnt.getAndSet(cnt.get() + 1); if (cnt.get() <= 2) { return new PollResponse<>(IN_PROGRESS, new Response("1")); } else if (cnt.get() == 3) { throw new RuntimeException("Polling operation failed!"); } else if (cnt.get() == 4) { return new PollResponse<>(IN_PROGRESS, new Response("2")); } else { return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("3")); } }; SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); RuntimeException exception = assertThrows(RuntimeException.class, poller::getFinalResult); assertTrue(exception.getMessage().contains("Polling operation failed!")); } @Test public void testPollerFluxError() throws InterruptedException { IllegalArgumentException expectedException = new IllegalArgumentException(); PollerFlux<String, String> pollerFlux = error(expectedException); CountDownLatch countDownLatch = new CountDownLatch(1); pollerFlux.subscribe( response -> Assertions.fail("Did not expect a response"), ex -> { countDownLatch.countDown(); Assertions.assertSame(expectedException, ex); }, () -> Assertions.fail("Did not expect the flux to complete") ); boolean completed = countDownLatch.await(1, TimeUnit.SECONDS); Assertions.assertTrue(completed); } @Test public static class Response { private final String response; public Response(String response) { this.response = response; } public String getResponse() { return response; } @Override public String toString() { return "Response: " + response; } } public static class CertificateOutput { String name; public CertificateOutput(String certName) { name = certName; } public String getName() { return name; } } }
class SimpleSyncPollerTests { @Mock private Function<PollingContext<Response>, Response> activationOperation; @Mock private Function<PollingContext<Response>, PollResponse<Response>> activationOperationWithResponse; @Mock private Function<PollingContext<Response>, PollResponse<Response>> pollOperation; @Mock private Function<PollingContext<Response>, CertificateOutput> fetchResultOperation; @Mock private BiFunction<PollingContext<Response>, PollResponse<Response>, Response> cancelOperation; private AutoCloseable openMocks; @BeforeEach public void beforeTest() { this.openMocks = MockitoAnnotations.openMocks(this); } @AfterEach public void afterTest() throws Exception { openMocks.close(); Mockito.framework().clearInlineMock(this); } @Test public void noPollingForSynchronouslyCompletedActivationInSyncPollerTest() { int[] activationCallCount = new int[1]; when(activationOperationWithResponse.apply(any())) .thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { activationCallCount[0]++; return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("ActivationDone")); }); SyncPoller<Response, CertificateOutput> syncPoller = new SimpleSyncPoller<>(Duration.ofMillis(10), activationOperationWithResponse, pollOperation, cancelOperation, fetchResultOperation); when(pollOperation.apply(any())).thenThrow( new RuntimeException("Polling shouldn't happen for synchronously completed activation.")); try { PollResponse<Response> response = syncPoller.waitForCompletion(Duration.ofSeconds(1)); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); assertEquals(1, activationCallCount[0]); } catch (Exception e) { fail("SyncPoller did not complete on activation", e); } } @Test public void syncPollerConstructorPollIntervalZero() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ZERO, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNegative() { assertThrows(IllegalArgumentException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(-1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollIntervalNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( null, cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncConstructorActivationOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), null, pollOperation, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorPollOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), null, cancelOperation, fetchResultOperation)); } @Test public void syncPollerConstructorCancelOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, null, fetchResultOperation)); } @Test public void syncPollerConstructorFetchResultOperationNull() { assertThrows(NullPointerException.class, () -> new SimpleSyncPoller<>( Duration.ofSeconds(1), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, null)); } @Test public void syncPollerShouldCallActivationFromConstructor() { Boolean[] activationCalled = new Boolean[1]; activationCalled[0] = false; when(activationOperation.apply(any())).thenAnswer((Answer<Response>) invocationOnMock -> { activationCalled[0] = true; return new Response("ActivationDone"); }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>(Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); Assertions.assertTrue(activationCalled[0]); } @Test public void eachPollShouldReceiveLastPollResponse() { when(activationOperation.apply(any())).thenReturn(new Response("A")); when(pollOperation.apply(any())).thenAnswer((Answer<?>) invocation -> { assertEquals(1, invocation.getArguments().length); Assertions.assertTrue(invocation.getArguments()[0] instanceof PollingContext); PollingContext<Response> pollingContext = (PollingContext<Response>) invocation.getArguments()[0]; Assertions.assertNotNull(pollingContext.getActivationResponse()); Assertions.assertNotNull(pollingContext.getLatestResponse()); PollResponse<Response> latestResponse = pollingContext.getLatestResponse(); Assertions.assertNotNull(latestResponse); PollResponse<Response> nextResponse = new PollResponse<>(IN_PROGRESS, new Response(latestResponse.getValue().toString() + "A"), Duration.ofMillis(10)); return nextResponse; }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: AA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: AAA")); pollResponse = poller.poll(); Assertions.assertNotNull(pollResponse); Assertions.assertNotNull(pollResponse.getValue().getResponse()); Assertions.assertTrue(pollResponse.getValue() .getResponse() .equalsIgnoreCase("Response: Response: Response: AAAA")); } @Test public void waitForCompletionShouldReturnTerminalPollResponse() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(response2.getValue().getResponse(), poller.waitForCompletion().getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); } @Test public void getResultShouldPollUntilCompletionAndFetchResult() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after terminal response"); } }); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); assertEquals(2, invocationCount[0]); } @Test public void getResultShouldNotPollOnCompletedPoller() { PollResponse<Response> response0 = new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); PollResponse<Response> response1 = new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); PollResponse<Response> response2 = new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, new Response("2"), Duration.ofMillis(10)); final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); when(fetchResultOperation.apply(any())).thenReturn(new CertificateOutput("cert1")); when(pollOperation.apply(any())).thenReturn( response0, response1, response2); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitForCompletion(); Assertions.assertNotNull(pollResponse.getValue()); assertEquals(response2.getValue().getResponse(), pollResponse.getValue().getResponse()); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus()); when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { Assertions.assertTrue(true, "A Poll after completion should be called"); return null; }); CertificateOutput certificateOutput = poller.getFinalResult(); Assertions.assertNotNull(certificateOutput); assertEquals("cert1", certificateOutput.getName()); } @Test public void waitUntilShouldPollAfterMatchingStatus() { final Response activationResponse = new Response("Activated"); when(activationOperation.apply(any())).thenReturn(activationResponse); LongRunningOperationStatus matchStatus = LongRunningOperationStatus.fromString("OTHER_1", false); int[] invocationCount = new int[1]; invocationCount[0] = -1; when(pollOperation.apply(any())).thenAnswer((Answer<PollResponse<Response>>) invocationOnMock -> { invocationCount[0]++; switch (invocationCount[0]) { case 0: return new PollResponse<>(IN_PROGRESS, new Response("0"), Duration.ofMillis(10)); case 1: return new PollResponse<>(IN_PROGRESS, new Response("1"), Duration.ofMillis(10)); case 2: return new PollResponse<>(matchStatus, new Response("1"), Duration.ofMillis(10)); default: throw new RuntimeException("Poll should not be called after matching response"); } }); SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); PollResponse<Response> pollResponse = poller.waitUntil(matchStatus); assertEquals(matchStatus, pollResponse.getStatus()); assertEquals(2, invocationCount[0]); } @Test public void verifyExceptionPropagationFromPollingOperationSyncPoller() { final Response activationResponse = new Response("Foo"); when(activationOperation.apply(any())).thenReturn(activationResponse); final AtomicReference<Integer> cnt = new AtomicReference<>(0); pollOperation = (pollingContext) -> { cnt.getAndSet(cnt.get() + 1); if (cnt.get() <= 2) { return new PollResponse<>(IN_PROGRESS, new Response("1")); } else if (cnt.get() == 3) { throw new RuntimeException("Polling operation failed!"); } else if (cnt.get() == 4) { return new PollResponse<>(IN_PROGRESS, new Response("2")); } else { return new PollResponse<>(SUCCESSFULLY_COMPLETED, new Response("3")); } }; SyncPoller<Response, CertificateOutput> poller = new SimpleSyncPoller<>( Duration.ofMillis(10), cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, activationOperation.apply(cxt)), pollOperation, cancelOperation, fetchResultOperation); RuntimeException exception = assertThrows(RuntimeException.class, poller::getFinalResult); assertTrue(exception.getMessage().contains("Polling operation failed!")); } @Test public void testPollerFluxError() throws InterruptedException { IllegalArgumentException expectedException = new IllegalArgumentException(); PollerFlux<String, String> pollerFlux = error(expectedException); CountDownLatch countDownLatch = new CountDownLatch(1); pollerFlux.subscribe( response -> Assertions.fail("Did not expect a response"), ex -> { countDownLatch.countDown(); Assertions.assertSame(expectedException, ex); }, () -> Assertions.fail("Did not expect the flux to complete") ); boolean completed = countDownLatch.await(1, TimeUnit.SECONDS); Assertions.assertTrue(completed); } @Test public static class Response { private final String response; public Response(String response) { this.response = response; } public String getResponse() { return response; } @Override public String toString() { return "Response: " + response; } } public static class CertificateOutput { String name; public CertificateOutput(String certName) { name = certName; } public String getName() { return name; } } }
I am not sure if extension serves a purpose. If not, maybe leave it out so user can focus more on essential settings?
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String managedOSSnapshotName = Utils.randomResourceName(azureResourceManager, "ss-os-", 15); final String managedDataDiskSnapshotPrefix = Utils.randomResourceName(azureResourceManager, "ss-data-", 15); final String managedNewOSDiskName = Utils.randomResourceName(azureResourceManager, "ds-os-nw-", 15); final String managedNewDataDiskNamePrefix = Utils.randomResourceName(azureResourceManager, "ds-data-nw-", 15); final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; final String apacheInstallScript = "https: final String apacheInstallCommand = "bash install_apache.sh"; List<String> apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", apacheInstallScriptUris) .withPublicSetting("commandToExecute", apacheInstallCommand) .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.println("Created a Linux VM with managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.println("Deallocating VM: " + linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(managedOSSnapshotName) .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); azureResourceManager.resourceGroups().define(rgNameNew).withRegion(regionNew).create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(managedOSSnapshotName + "new") .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.println("Created managed snapshot holding OS: " + osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); int i = 0; for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(managedDataDiskSnapshotPrefix + "-" + i) .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(managedDataDiskSnapshotPrefix + "new" + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.println("Created managed snapshot holding data: " + dataSnapshotNewRegion.id()); i++; } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(managedNewOSDiskName) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.println("Created managed disk holding OS: " + osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); i = 0; for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(managedNewDataDiskNamePrefix + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.println("Created managed disk holding data: " + dataDisk.id()); i++; } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.println("Deleting OS snapshot - " + osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.println("Deleting data snapshot - " + dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.println("De-allocating the virtual machine - " + linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); System.out.println("Deleting Resource Group: " + rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); System.out.println("Deleted Resource Group: " + rgNameNew); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
.attach()
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String snapshotCopiedSuffix = "-snp-copied"; final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.printf("Created a Linux VM with managed OS and data disks: %s %n", linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.printf("Deallocating VM: %s %n", linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(osDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(osDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.printf("Created managed snapshot holding OS: %s %n", osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(dataDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(dataDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.printf("Created managed snapshot holding data: %s %n", dataSnapshotNewRegion.id()); } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(osSnapshotNewRegion.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.printf("Created managed disk holding OS: %s %n", osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(dataSnapshot.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.printf("Created managed disk holding data: %s %n", dataDisk.id()); } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.printf("Deleting OS snapshot - %s %n", osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Deleting data snapshot - %s %n", dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.printf("De-allocating the virtual machine - %s %n", linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { System.out.printf("Deleting Resource Group: %s %n", rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.printf("Deleting Resource Group: %s %n", rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
If possible use a later version.
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String managedOSSnapshotName = Utils.randomResourceName(azureResourceManager, "ss-os-", 15); final String managedDataDiskSnapshotPrefix = Utils.randomResourceName(azureResourceManager, "ss-data-", 15); final String managedNewOSDiskName = Utils.randomResourceName(azureResourceManager, "ds-os-nw-", 15); final String managedNewDataDiskNamePrefix = Utils.randomResourceName(azureResourceManager, "ds-data-nw-", 15); final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; final String apacheInstallScript = "https: final String apacheInstallCommand = "bash install_apache.sh"; List<String> apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", apacheInstallScriptUris) .withPublicSetting("commandToExecute", apacheInstallCommand) .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.println("Created a Linux VM with managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.println("Deallocating VM: " + linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(managedOSSnapshotName) .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); azureResourceManager.resourceGroups().define(rgNameNew).withRegion(regionNew).create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(managedOSSnapshotName + "new") .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.println("Created managed snapshot holding OS: " + osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); int i = 0; for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(managedDataDiskSnapshotPrefix + "-" + i) .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(managedDataDiskSnapshotPrefix + "new" + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.println("Created managed snapshot holding data: " + dataSnapshotNewRegion.id()); i++; } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(managedNewOSDiskName) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.println("Created managed disk holding OS: " + osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); i = 0; for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(managedNewDataDiskNamePrefix + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.println("Created managed disk holding data: " + dataDisk.id()); i++; } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.println("Deleting OS snapshot - " + osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.println("Deleting data snapshot - " + dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.println("De-allocating the virtual machine - " + linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); System.out.println("Deleting Resource Group: " + rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); System.out.println("Deleted Resource Group: " + rgNameNew); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String snapshotCopiedSuffix = "-snp-copied"; final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.printf("Created a Linux VM with managed OS and data disks: %s %n", linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.printf("Deallocating VM: %s %n", linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(osDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(osDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.printf("Created managed snapshot holding OS: %s %n", osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(dataDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(dataDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.printf("Created managed snapshot holding data: %s %n", dataSnapshotNewRegion.id()); } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(osSnapshotNewRegion.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.printf("Created managed disk holding OS: %s %n", osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(dataSnapshot.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.printf("Created managed disk holding data: %s %n", dataDisk.id()); } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.printf("Deleting OS snapshot - %s %n", osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Deleting data snapshot - %s %n", dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.printf("De-allocating the virtual machine - %s %n", linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { System.out.printf("Deleting Resource Group: %s %n", rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.printf("Deleting Resource Group: %s %n", rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
if it is used, give a better name, at least "index".
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String managedOSSnapshotName = Utils.randomResourceName(azureResourceManager, "ss-os-", 15); final String managedDataDiskSnapshotPrefix = Utils.randomResourceName(azureResourceManager, "ss-data-", 15); final String managedNewOSDiskName = Utils.randomResourceName(azureResourceManager, "ds-os-nw-", 15); final String managedNewDataDiskNamePrefix = Utils.randomResourceName(azureResourceManager, "ds-data-nw-", 15); final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; final String apacheInstallScript = "https: final String apacheInstallCommand = "bash install_apache.sh"; List<String> apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", apacheInstallScriptUris) .withPublicSetting("commandToExecute", apacheInstallCommand) .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.println("Created a Linux VM with managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.println("Deallocating VM: " + linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(managedOSSnapshotName) .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); azureResourceManager.resourceGroups().define(rgNameNew).withRegion(regionNew).create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(managedOSSnapshotName + "new") .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.println("Created managed snapshot holding OS: " + osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); int i = 0; for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(managedDataDiskSnapshotPrefix + "-" + i) .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(managedDataDiskSnapshotPrefix + "new" + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.println("Created managed snapshot holding data: " + dataSnapshotNewRegion.id()); i++; } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(managedNewOSDiskName) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.println("Created managed disk holding OS: " + osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); i = 0; for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(managedNewDataDiskNamePrefix + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.println("Created managed disk holding data: " + dataDisk.id()); i++; } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.println("Deleting OS snapshot - " + osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.println("Deleting data snapshot - " + dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.println("De-allocating the virtual machine - " + linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); System.out.println("Deleting Resource Group: " + rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); System.out.println("Deleted Resource Group: " + rgNameNew); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
int i = 0;
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String snapshotCopiedSuffix = "-snp-copied"; final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.printf("Created a Linux VM with managed OS and data disks: %s %n", linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.printf("Deallocating VM: %s %n", linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(osDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(osDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.printf("Created managed snapshot holding OS: %s %n", osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(dataDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(dataDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.printf("Created managed snapshot holding data: %s %n", dataSnapshotNewRegion.id()); } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(osSnapshotNewRegion.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.printf("Created managed disk holding OS: %s %n", osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(dataSnapshot.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.printf("Created managed disk holding data: %s %n", dataDisk.id()); } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.printf("Deleting OS snapshot - %s %n", osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Deleting data snapshot - %s %n", dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.printf("De-allocating the virtual machine - %s %n", linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { System.out.printf("Deleting Resource Group: %s %n", rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.printf("Deleting Resource Group: %s %n", rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
though I am not sure if that is really needed. disk.name + suffix (one suffix for snapshot another for copied snapshot) seems enough?
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String managedOSSnapshotName = Utils.randomResourceName(azureResourceManager, "ss-os-", 15); final String managedDataDiskSnapshotPrefix = Utils.randomResourceName(azureResourceManager, "ss-data-", 15); final String managedNewOSDiskName = Utils.randomResourceName(azureResourceManager, "ds-os-nw-", 15); final String managedNewDataDiskNamePrefix = Utils.randomResourceName(azureResourceManager, "ds-data-nw-", 15); final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; final String apacheInstallScript = "https: final String apacheInstallCommand = "bash install_apache.sh"; List<String> apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", apacheInstallScriptUris) .withPublicSetting("commandToExecute", apacheInstallCommand) .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.println("Created a Linux VM with managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.println("Deallocating VM: " + linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(managedOSSnapshotName) .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); azureResourceManager.resourceGroups().define(rgNameNew).withRegion(regionNew).create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(managedOSSnapshotName + "new") .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.println("Created managed snapshot holding OS: " + osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); int i = 0; for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(managedDataDiskSnapshotPrefix + "-" + i) .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(managedDataDiskSnapshotPrefix + "new" + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.println("Created managed snapshot holding data: " + dataSnapshotNewRegion.id()); i++; } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(managedNewOSDiskName) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.println("Created managed disk holding OS: " + osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); i = 0; for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(managedNewDataDiskNamePrefix + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.println("Created managed disk holding data: " + dataDisk.id()); i++; } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.println("Deleting OS snapshot - " + osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.println("Deleting data snapshot - " + dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.println("De-allocating the virtual machine - " + linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); System.out.println("Deleting Resource Group: " + rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); System.out.println("Deleted Resource Group: " + rgNameNew); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
int i = 0;
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String snapshotCopiedSuffix = "-snp-copied"; final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.printf("Created a Linux VM with managed OS and data disks: %s %n", linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.printf("Deallocating VM: %s %n", linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(osDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(osDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.printf("Created managed snapshot holding OS: %s %n", osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(dataDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(dataDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.printf("Created managed snapshot holding data: %s %n", dataSnapshotNewRegion.id()); } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(osSnapshotNewRegion.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.printf("Created managed disk holding OS: %s %n", osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(dataSnapshot.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.printf("Created managed disk holding data: %s %n", dataDisk.id()); } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.printf("Deleting OS snapshot - %s %n", osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Deleting data snapshot - %s %n", dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.printf("De-allocating the virtual machine - %s %n", linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { System.out.printf("Deleting Resource Group: %s %n", rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.printf("Deleting Resource Group: %s %n", rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
maybe not print this line. the call is "beginDelete" so here it is not yet deleted.
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String managedOSSnapshotName = Utils.randomResourceName(azureResourceManager, "ss-os-", 15); final String managedDataDiskSnapshotPrefix = Utils.randomResourceName(azureResourceManager, "ss-data-", 15); final String managedNewOSDiskName = Utils.randomResourceName(azureResourceManager, "ds-os-nw-", 15); final String managedNewDataDiskNamePrefix = Utils.randomResourceName(azureResourceManager, "ds-data-nw-", 15); final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; final String apacheInstallScript = "https: final String apacheInstallCommand = "bash install_apache.sh"; List<String> apacheInstallScriptUris = new ArrayList<>(); apacheInstallScriptUris.add(apacheInstallScript); try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .defineNewExtension("CustomScriptForLinux") .withPublisher("Microsoft.OSTCExtensions") .withType("CustomScriptForLinux") .withVersion("1.4") .withMinorVersionAutoUpgrade() .withPublicSetting("fileUris", apacheInstallScriptUris) .withPublicSetting("commandToExecute", apacheInstallCommand) .attach() .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.println("Created a Linux VM with managed OS and data disks: " + linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.println("Deallocating VM: " + linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(managedOSSnapshotName) .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); azureResourceManager.resourceGroups().define(rgNameNew).withRegion(regionNew).create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(managedOSSnapshotName + "new") .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.println("Created managed snapshot holding OS: " + osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); int i = 0; for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(managedDataDiskSnapshotPrefix + "-" + i) .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(managedDataDiskSnapshotPrefix + "new" + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.println("Created managed snapshot holding data: " + dataSnapshotNewRegion.id()); i++; } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(managedNewOSDiskName) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.println("Created managed disk holding OS: " + osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); i = 0; for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(managedNewDataDiskNamePrefix + "-" + i) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.println("Created managed disk holding data: " + dataDisk.id()); i++; } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.println("Deleting OS snapshot - " + osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.println("Deleting data snapshot - " + dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.println("De-allocating the virtual machine - " + linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { try { System.out.println("Deleting Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); System.out.println("Deleting Resource Group: " + rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); System.out.println("Deleted Resource Group: " + rgNameNew); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
System.out.println("Deleted Resource Group: " + rgNameNew);
public static boolean runSample(AzureResourceManager azureResourceManager) { final String linuxVMName1 = Utils.randomResourceName(azureResourceManager, "VM1", 15); final String linuxVMName2 = Utils.randomResourceName(azureResourceManager, "VM2", 15); final String snapshotCopiedSuffix = "-snp-copied"; final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String rgNameNew = Utils.randomResourceName(azureResourceManager, "rgCOMV", 15); final String publicIpDnsLabel = Utils.randomResourceName(azureResourceManager, "pip", 15); final String userName = "tirekicker"; final String sshPublicKey = Utils.sshPublicKey(); final Region region = Region.US_WEST; final Region regionNew = Region.US_EAST; try { System.out.println("Creating a un-managed Linux VM"); VirtualMachine linuxVM = azureResourceManager.virtualMachines().define(linuxVMName1) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIpDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS) .withRootUsername(userName) .withSsh(sshPublicKey) .withNewDataDisk(100) .withNewDataDisk(100, 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); System.out.printf("Created a Linux VM with managed OS and data disks: %s %n", linuxVM.id()); Utils.print(linuxVM); Disk osDisk = azureResourceManager.disks().getById(linuxVM.osDiskId()); List<Disk> dataDisks = new ArrayList<>(); for (VirtualMachineDataDisk disk : linuxVM.dataDisks().values()) { Disk dataDisk = azureResourceManager.disks().getById(disk.id()); dataDisks.add(dataDisk); } System.out.printf("Deallocating VM: %s %n", linuxVM.id()); linuxVM.deallocate(); System.out.println("Deallocated the VM"); System.out.printf("Creating managed snapshot from the managed disk (holding specialized OS): %s %n", osDisk.id()); Snapshot osSnapshot = azureResourceManager.snapshots() .define(osDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withLinuxFromDisk(osDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region.%n", osDisk.id()); Snapshot osSnapshotNewRegion = azureResourceManager .snapshots() .define(osDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withNewResourceGroup(rgNameNew) .withDataFromSnapshot(osSnapshot) .withCopyStart() .withIncremental(true) .create(); osSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(osSnapshot.id()); System.out.printf("Created managed snapshot holding OS: %s %n", osSnapshotNewRegion.id()); List<Snapshot> dataSnapshots = new ArrayList<>(); for (Disk dataDisk : dataDisks) { System.out.printf("Creating managed snapshot from the managed disk (holding data): %s %n", dataDisk.id()); Snapshot dataSnapshot = azureResourceManager.snapshots() .define(dataDisk.name() + "-snp") .withRegion(region) .withExistingResourceGroup(rgName) .withDataFromDisk(dataDisk) .withIncremental(true) .create(); System.out.printf("Copying managed snapshot %s to a new region %n", dataSnapshot.id()); Snapshot dataSnapshotNewRegion = azureResourceManager .snapshots() .define(dataDisk.name() + snapshotCopiedSuffix) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withDataFromSnapshot(dataSnapshot) .withCopyStart() .withIncremental(true) .create(); dataSnapshotNewRegion.awaitCopyStartCompletion(); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); dataSnapshots.add(dataSnapshotNewRegion); System.out.printf("Created managed snapshot holding data: %s %n", dataSnapshotNewRegion.id()); } System.out.printf("Creating managed disk from the snapshot holding OS: %s %n", osSnapshotNewRegion.id()); Disk newOSDisk = azureResourceManager.disks().define(osSnapshotNewRegion.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withLinuxFromSnapshot(osSnapshotNewRegion.id()) .withSizeInGB(100) .create(); System.out.printf("Created managed disk holding OS: %s %n", osDisk.id()); List<Disk> newDataDisks = new ArrayList<>(); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Creating managed disk from the Data snapshot: %s %n", dataSnapshot.id()); Disk dataDisk = azureResourceManager.disks().define(dataSnapshot.name().replace(snapshotCopiedSuffix, "-new")) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withData() .fromSnapshot(dataSnapshot.id()) .create(); newDataDisks.add(dataDisk); System.out.printf("Created managed disk holding data: %s %n", dataDisk.id()); } System.out.println("Creating a Linux VM using specialized OS and data disks"); VirtualMachine linuxVM2 = azureResourceManager.virtualMachines().define(linuxVMName2) .withRegion(regionNew) .withExistingResourceGroup(rgNameNew) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withSpecializedOSDisk(newOSDisk, OperatingSystemTypes.LINUX) .withExistingDataDisk(newDataDisks.get(0)) .withExistingDataDisk(newDataDisks.get(1), 1, CachingTypes.READ_WRITE) .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")) .create(); Utils.print(linuxVM2); System.out.printf("Deleting OS snapshot - %s %n", osSnapshotNewRegion.id()); azureResourceManager.snapshots().deleteById(osSnapshotNewRegion.id()); System.out.println("Deleted OS snapshot"); for (Snapshot dataSnapshot : dataSnapshots) { System.out.printf("Deleting data snapshot - %s %n", dataSnapshot.id()); azureResourceManager.snapshots().deleteById(dataSnapshot.id()); System.out.println("Deleted data snapshot"); } System.out.printf("De-allocating the virtual machine - %s %n", linuxVM2.id()); linuxVM2.deallocate(); return true; } finally { System.out.printf("Deleting Resource Group: %s %n", rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.printf("Deleting Resource Group: %s %n", rgNameNew); azureResourceManager.resourceGroups().beginDeleteByName(rgNameNew); } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }
class CloneVirtualMachineToNewRegion { /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private CloneVirtualMachineToNewRegion() { } }