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
It isn't reused anywhere else so didn't bother putting it in a static variable.
static CustomFormModel getExpectedUnlabeledModel() { Map<String, CustomFormModelField> fieldMap = new HashMap<String, CustomFormModelField>() { { put("field-0", new CustomFormModelField("field-0", "Address", null)); put("field-1", new CustomFormModelField("field-1", "Charges", null)); put("field-2", new CustomFormModel...
return new CustomFormModel("95537f1b-aac4-4da8-8292-f1b93ac4c8f8", CustomFormModelStatus.READY,
static CustomFormModel getExpectedUnlabeledModel() { Map<String, CustomFormModelField> fieldMap = new HashMap<String, CustomFormModelField>() { { put("field-0", new CustomFormModelField("field-0", "Address", null)); put("field-1", new CustomFormModelField("field-1", "Charges", null)); put("field-2", new CustomFormModel...
class TestUtils { static final String INVALID_MODEL_ID = "a0a3998a-4c4affe66b7"; static final String INVALID_STATUS_MODEL_ID = "22138c4e-c4b0-4901-a0e1-6c5beb73fc1d"; static final String INVALID_RECEIPT_URL = "https: static final String INVALID_SOURCE_URL_ERROR = "Status code 400, \"{\"error\":{\"code\":\"1003\"," + "\...
class TestUtils { static final String INVALID_MODEL_ID = "a0a3998a-4c4affe66b7"; static final String INVALID_RECEIPT_URL = "https: static final String INVALID_SOURCE_URL_ERROR = "Status code 400, \"{\"error\":{\"code\":\"1003\"," + "\"message\":\"Parameter 'Source' is not a valid Uri.\"}}\""; static final String INVALI...
Why it using lro regry duration?
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
The cosmos multi location prevision is async. It will return succeeded when first location is done. This func I think is to ensure all location is succeeded.
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
Yes, but why use `getLroRetryDuration`? It should be only used for LRO, but this is not.
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
You can use `getDelayDuration` with a specified delay.
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
This is a LRO situation, just isn't a common LRO situation.
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
Long running operation to wait all location prevision complete.
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
An operation takes long time does not means that it is LRO. The specific var is used here for the `PollerFlux`. ``` public <T, U> PollerFlux<PollResult<T>, U> getLroResultAsync(Mono<SimpleResponse<Flux<ByteBuffer>>> lroInit, HttpPipeline httpPipeline...
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
Track1 is such ``` ).repeatWhen(new Func1<Observable<? extends java.lang.Void>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Void> observable) { data.set(0, data.get(0) + 5); ...
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
Done, change to `getDelayDuration`.
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
return Mono.delay(SdkContext.getLroRetryDuration());
private Mono<CosmosDBAccount> doDatabaseUpdateCreate() { final CosmosDBAccountImpl self = this; final List<Integer> data = new ArrayList<Integer>(); data.add(0); Mono<DatabaseAccountGetResultsInner> request = null; HasLocations locationParameters = null; if (isInCreateMode()) { final DatabaseAccountCreateUpdateParamete...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
class CosmosDBAccountImpl extends GroupableResourceImpl<CosmosDBAccount, DatabaseAccountGetResultsInner, CosmosDBAccountImpl, CosmosDBManager> implements CosmosDBAccount, CosmosDBAccount.Definition, CosmosDBAccount.Update { private List<FailoverPolicy> failoverPolicies; private boolean hasFailoverPolicyChanges; private...
```suggestion + " credential authentication.")); ```
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } else if (Platform.isMac()) { KeyChainAccessor keyChainAccessor...
+ " Credential authentication."));
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (RuntimeException e) { throw logger.logExceptionAs...
class VisualStudioCacheAccessor { private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); /** * Creates an instance of {@link VisualStudioCacheAccessor} */ public VisualStudioCacheAccessor() { } /** * Get the user configured settings of Visual Studio code. * @return the {@link JsonNode} h...
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern...
```suggestion new CredentialUnavailableException("Platform could not be determined for VS Code" ```
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } else if (Platform.isMac()) { KeyChainAccessor keyChainAccessor...
new CredentialUnavailableException("Platform could not be determined for VsCode"
public String getCredentials(String serviceName, String accountName) { String credential; if (Platform.isWindows()) { try { WindowsCredentialAccessor winCredAccessor = new WindowsCredentialAccessor(serviceName, accountName); credential = winCredAccessor.read(); } catch (RuntimeException e) { throw logger.logExceptionAs...
class VisualStudioCacheAccessor { private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); /** * Creates an instance of {@link VisualStudioCacheAccessor} */ public VisualStudioCacheAccessor() { } /** * Get the user configured settings of Visual Studio code. * @return the {@link JsonNode} h...
class VisualStudioCacheAccessor { private static final String PLATFORM_NOT_SUPPORTED_ERROR = "Platform could not be determined for VS Code" + " credential authentication."; private final ClientLogger logger = new ClientLogger(VisualStudioCacheAccessor.class); private static final Pattern REFRESH_TOKEN_PATTERN = Pattern...
```suggestion + " Please log in with Azure Tools for IntelliJ plugin in the IDE.")); ```
public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getKeepPassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (a...
+ " Plese login with Azure Tools for IntelliJ plugin in the IDE."));
public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod()...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final ...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final ...
KeePass
private JsonNode getCredentialFromKdbx() throws IOException { if (CoreUtils.isNullOrEmpty(keePassDatabasePath)) { throw logger.logExceptionAsError( new CredentialUnavailableException("The keePass database path is either empty or not configured." + " Please configure it on the builder. It is required to use " + "Intelli...
new CredentialUnavailableException("The keePass database path is either empty or not configured."
private JsonNode getCredentialFromKdbx() throws IOException { if (CoreUtils.isNullOrEmpty(keePassDatabasePath)) { throw logger.logExceptionAsError( new CredentialUnavailableException("The KeePass database path is either empty or not configured." + " Please configure it on the builder. It is required to use " + "Intelli...
class IntelliJCacheAccessor { private final ClientLogger logger = new ClientLogger(IntelliJCacheAccessor.class); private String keePassDatabasePath; private static final String INTELLIJ_CREDENTIAL_NOT_AVAILABLE_ERROR = "IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in th...
class IntelliJCacheAccessor { private final ClientLogger logger = new ClientLogger(IntelliJCacheAccessor.class); private String keePassDatabasePath; private static final String INTELLIJ_CREDENTIAL_NOT_AVAILABLE_ERROR = "IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in th...
KeePass
private JsonNode getCredentialFromKdbx() throws IOException { if (CoreUtils.isNullOrEmpty(keePassDatabasePath)) { throw logger.logExceptionAsError( new CredentialUnavailableException("The keePass database path is either empty or not configured." + " Please configure it on the builder. It is required to use " + "Intelli...
throw logger.logExceptionAsError(new RuntimeException("Failed to read keePass database.", e));
private JsonNode getCredentialFromKdbx() throws IOException { if (CoreUtils.isNullOrEmpty(keePassDatabasePath)) { throw logger.logExceptionAsError( new CredentialUnavailableException("The KeePass database path is either empty or not configured." + " Please configure it on the builder. It is required to use " + "Intelli...
class IntelliJCacheAccessor { private final ClientLogger logger = new ClientLogger(IntelliJCacheAccessor.class); private String keePassDatabasePath; private static final String INTELLIJ_CREDENTIAL_NOT_AVAILABLE_ERROR = "IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in th...
class IntelliJCacheAccessor { private final ClientLogger logger = new ClientLogger(IntelliJCacheAccessor.class); private String keePassDatabasePath; private static final String INTELLIJ_CREDENTIAL_NOT_AVAILABLE_ERROR = "IntelliJ Authentication not available." + " Please log in with Azure Tools for IntelliJ plugin in th...
You'll need to remove System.getEnv here.
static NetworkConfiguration createNetworkConfiguration(){ AzureTokenCredentials token = new ApplicationTokenCredentials( System.getenv("CLIENT_ID"), "72f988bf-86f1-41af-91ab-2d7cd011db47", System.getenv("APPLICATION_SECRET"), AzureEnvironment.AZURE); Azure azure = Azure.authenticate(token).withSubscription(System.geten...
System.getenv("677f962b-9abf-4423-a27b-0c2f4094dcec"),
static NetworkConfiguration createNetworkConfiguration(){ String vnetName = "AzureBatchTestVnet"; String subnetName = "AzureBatchTestSubnet"; if(isRecordMode()) { AzureTokenCredentials token = new ApplicationTokenCredentials( System.getenv("CLIENT_ID"), "72f988bf-86f1-41af-91ab-2d7cd011db47", System.getenv("APPLICATION...
class BatchIntegrationTestBase { public static final String RECORD_MODE = "RECORD"; static BatchClient batchClient; static BatchClient alternativeBatchClient; static final int MAX_LEN_ID = 64; static Logger logger; public enum AuthMode { AAD, SharedKey } private static TestBase.TestMode testMode = null; private PrintSt...
class BatchIntegrationTestBase { public static final String RECORD_MODE = "RECORD"; static BatchClient batchClient; static BatchClient alternativeBatchClient; static final int MAX_LEN_ID = 64; static Logger logger; public enum AuthMode { AAD, SharedKey } private static TestBase.TestMode testMode = null; private PrintSt...
@mssfang Following sample code will work: ```java toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); ``` but wondering it should be re-playable to support any retry: ```java toFluxByteBuffer(Mono.fromCallable(() -> new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))))...
public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_J...
new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath())));
public void beginRecognizeReceipts() throws IOException { File sourceFile = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer( new ByteArrayInputStream(Files.readAllBytes(sourceFile.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, sourceFile.length(), FormContentType.IMAGE_J...
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizer...
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizer...
Not sure if it better use if instead of assert
protected Mono<VirtualNetworkGatewayInner> createInner() { final VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final Mono<Resource> pipObservable; if (defaultIPConfig.publicIPAddressId() == null) { pipObservable = Utils .<PublicIPAddress>rootResource(ensureDefaultPipDefinition().cr...
assert creatableNetwork != null;
protected Mono<VirtualNetworkGatewayInner> createInner() { final VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final Mono<Resource> pipObservable; if (defaultIPConfig.publicIPAddressId() == null) { pipObservable = Utils .<PublicIPAddress>rootResource(ensureDefaultPipDefinition().cr...
class VirtualNetworkGatewayImpl extends GroupableParentResourceWithTagsImpl< VirtualNetworkGateway, VirtualNetworkGatewayInner, VirtualNetworkGatewayImpl, NetworkManager> implements VirtualNetworkGateway, VirtualNetworkGateway.Definition, VirtualNetworkGateway.Update { private static final String GATEWAY_SUBNET = "Gate...
class VirtualNetworkGatewayImpl extends GroupableParentResourceWithTagsImpl< VirtualNetworkGateway, VirtualNetworkGatewayInner, VirtualNetworkGatewayImpl, NetworkManager> implements VirtualNetworkGateway, VirtualNetworkGateway.Definition, VirtualNetworkGateway.Update { private static final String GATEWAY_SUBNET = "Gate...
Maybe just check not null, throw IllegalState if null?
protected Mono<VirtualNetworkGatewayInner> createInner() { final VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final Mono<Resource> pipObservable; if (defaultIPConfig.publicIPAddressId() == null) { pipObservable = Utils .<PublicIPAddress>rootResource(ensureDefaultPipDefinition().cr...
assert creatableNetwork != null;
protected Mono<VirtualNetworkGatewayInner> createInner() { final VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final Mono<Resource> pipObservable; if (defaultIPConfig.publicIPAddressId() == null) { pipObservable = Utils .<PublicIPAddress>rootResource(ensureDefaultPipDefinition().cr...
class VirtualNetworkGatewayImpl extends GroupableParentResourceWithTagsImpl< VirtualNetworkGateway, VirtualNetworkGatewayInner, VirtualNetworkGatewayImpl, NetworkManager> implements VirtualNetworkGateway, VirtualNetworkGateway.Definition, VirtualNetworkGateway.Update { private static final String GATEWAY_SUBNET = "Gate...
class VirtualNetworkGatewayImpl extends GroupableParentResourceWithTagsImpl< VirtualNetworkGateway, VirtualNetworkGatewayInner, VirtualNetworkGatewayImpl, NetworkManager> implements VirtualNetworkGateway, VirtualNetworkGateway.Definition, VirtualNetworkGateway.Update { private static final String GATEWAY_SUBNET = "Gate...
done
protected Mono<VirtualNetworkGatewayInner> createInner() { final VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final Mono<Resource> pipObservable; if (defaultIPConfig.publicIPAddressId() == null) { pipObservable = Utils .<PublicIPAddress>rootResource(ensureDefaultPipDefinition().cr...
assert creatableNetwork != null;
protected Mono<VirtualNetworkGatewayInner> createInner() { final VirtualNetworkGatewayIPConfigurationImpl defaultIPConfig = ensureDefaultIPConfig(); final Mono<Resource> pipObservable; if (defaultIPConfig.publicIPAddressId() == null) { pipObservable = Utils .<PublicIPAddress>rootResource(ensureDefaultPipDefinition().cr...
class VirtualNetworkGatewayImpl extends GroupableParentResourceWithTagsImpl< VirtualNetworkGateway, VirtualNetworkGatewayInner, VirtualNetworkGatewayImpl, NetworkManager> implements VirtualNetworkGateway, VirtualNetworkGateway.Definition, VirtualNetworkGateway.Update { private static final String GATEWAY_SUBNET = "Gate...
class VirtualNetworkGatewayImpl extends GroupableParentResourceWithTagsImpl< VirtualNetworkGateway, VirtualNetworkGatewayInner, VirtualNetworkGatewayImpl, NetworkManager> implements VirtualNetworkGateway, VirtualNetworkGateway.Definition, VirtualNetworkGateway.Update { private static final String GATEWAY_SUBNET = "Gate...
This would be Act. And the line after would be Assert.
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<...
ServiceBusReceivedMessage receivedPeekMessage = receiver.peekAt(receivedMessage.getSequenceNumber());
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(mess...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClientIntegrationTest.class); ServiceBusReceiverClient receiver; ServiceBusSenderClient sender; /** * Receiver used to clean up resources in {@link */ ServiceBusReceiverClie...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
It's Act and then Assert. For all the other ones.
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<...
ServiceBusReceivedMessage receivedPeekMessage = receiver.peekAt(receivedMessage.getSequenceNumber());
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(mess...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClientIntegrationTest.class); ServiceBusReceiverClient receiver; ServiceBusSenderClient sender; /** * Receiver used to clean up resources in {@link */ ServiceBusReceiverClie...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
Format this document. There are two spaces here.
public void setupTest(TestInfo testInfo) { logger.info("========= SET-UP [{}] =========", testInfo.getDisplayName()); testName = testInfo.getDisplayName(); TestMode mode = getTestMode(); boolean isRecord = getTestMode() == TestMode.RECORD; Assumptions.assumeTrue(getTestMode() == TestMode.RECORD); properties = new Conn...
boolean isRecord = getTestMode() == TestMode.RECORD;
public void setupTest(TestInfo testInfo) { logger.info("========= SET-UP [{}] =========", testInfo.getDisplayName()); testName = testInfo.getDisplayName(); Assumptions.assumeTrue(getTestMode() == TestMode.RECORD); properties = new ConnectionStringProperties(getConnectionString()); StepVerifier.setDefaultTimeout(TIMEOUT...
class IntegrationTestBase extends TestBase { protected static final Duration TIMEOUT = Duration.ofSeconds(75); protected static final AmqpRetryOptions RETRY_OPTIONS = new AmqpRetryOptions().setTryTimeout(TIMEOUT); protected final ClientLogger logger; private static final String PROXY_AUTHENTICATION_TYPE = "PROXY_AUTHEN...
class IntegrationTestBase extends TestBase { protected static final Duration TIMEOUT = Duration.ofSeconds(75); protected static final AmqpRetryOptions RETRY_OPTIONS = new AmqpRetryOptions().setTryTimeout(TIMEOUT); protected final ClientLogger logger; private static final String PROXY_AUTHENTICATION_TYPE = "PROXY_AUTHEN...
nit: variable name: Ite?
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<...
final IterableStream<ServiceBusReceivedMessage> messageIte = receiver.receive(1, TIMEOUT);
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(mess...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClientIntegrationTest.class); private ServiceBusReceiverClient receiver; private ServiceBusSenderClient sender; /* Sometime not all the messages are cleaned-up. This is buff...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
Is this assertion necessary? If the list was empty, the .get(0) would fail with an out of range exception. The assertion is probably `Assertions.assertEquals(1, asList.size())` before you get the first item.
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<...
assertNotNull(receivedMessage);
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(mess...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClientIntegrationTest.class); private ServiceBusReceiverClient receiver; private ServiceBusSenderClient sender; /* Sometime not all the messages are cleaned-up. This is buff...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
You should be asserting that the messages also start from that sequence number.
void peekBatchMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; sendMessage(message); sendMess...
Assertions.assertEquals(maxMessages, iterableMessages.stream().collect(Collectors.toList()).size());
void peekBatchMessagesFromSequence(MessagingEntityType entityType) { setSenderAndReceiver(entityType, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, false); final int maxMessages = 2; final int fromSequenceNumber = 1; sendMessage(message); sendMess...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClientIntegrationTest.class); private ServiceBusReceiverClient receiver; private ServiceBusSenderClient sender; /* Sometime not all the messages are cleaned-up. This is buff...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
You should also assert that the message is from that sequence number.
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<...
assertMessageEquals(receivedPeekMessage, messageId, isSessionEnabled);
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(mess...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClientIntegrationTest.class); private ServiceBusReceiverClient receiver; private ServiceBusSenderClient sender; /* Sometime not all the messages are cleaned-up. This is buff...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
Same with the comment above. If you did .get(0) and the list was empty, it would throw. This check is incorrect.
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<ServiceBusRe...
assertNotNull(receivedMessage);
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(message); final ...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClientIntegrationTest.class); private ServiceBusReceiverClient receiver; private ServiceBusSenderClient sender; /* Sometime not all the messages are cleaned-up. This is buff...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
And all other instances of it.
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<ServiceBusRe...
assertNotNull(receivedMessage);
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(message); final ...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { private final ClientLogger logger = new ClientLogger(ServiceBusReceiverClientIntegrationTest.class); private ServiceBusReceiverClient receiver; private ServiceBusSenderClient sender; /* Sometime not all the messages are cleaned-up. This is buff...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
Use logger.
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + B...
System.out.println("Removed Message sequence : " + receivedMessage.getSequenceNumber());
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + B...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
Should use placeholders so it can be lazily evaluated. http://www.slf4j.org/faq.html#logging_performance
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + B...
logger.warning("Error occurred when draining deferred messages Entity : " + receiver.getEntityPath(), e);
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + B...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
Do we need the empty set? This is done during clean up. The class will be recreated after every method.
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + B...
messagesDeferred.set(new ArrayList<>());
protected void afterTest() { final int pending = messagesPending.get(); if (pending < 1 && messagesDeferred.get().size() < 1) { dispose(receiver, sender, receiveAndDeleteReceiver); return; } if (pending > 0) { try { IterableStream<ServiceBusReceivedMessage> removedMessage = receiveAndDeleteReceiver.receive( pending + B...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
A better way is to count the number of time you go into the loop and assert at the end rather than creating the list eagerly. ```java int count = 0; for (Message m : messages) { count++; } assertEquals(2, count); ```
void receiveTwoMessagesAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); int maxMessages = 2; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); ...
for (ServiceBusReceivedMessage receivedMessage : asList) {
void receiveTwoMessagesAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); int maxMessages = 2; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); ...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
Same with other instances.
void receiveTwoMessagesAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); int maxMessages = 2; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); ...
for (ServiceBusReceivedMessage receivedMessage : asList) {
void receiveTwoMessagesAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); int maxMessages = 2; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); ...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
class ServiceBusReceiverClientIntegrationTest extends IntegrationTestBase { /* Sometime not all the messages are cleaned-up. This is buffer to ensure all the messages are cleaned-up.*/ private static final int BUFFER_MESSAGES_TO_REMOVE = 10; private final AtomicInteger messagesPending = new AtomicInteger(); private fin...
Should this throwable be logged as warning?
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme")); } return next.clone().process() .doOnNext(ht...
} catch (Throwable ignored) {
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme")); } return next.clone().process() .doOnNext(ht...
class KeyVaultCredentialPolicy implements HttpPipelinePolicy { private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String AUTHORIZATION = "Authorization"; private final ScopeTokenCache cache; /** * Creates KeyVaultCredentia...
class KeyVaultCredentialPolicy implements HttpPipelinePolicy { private final ClientLogger logger = new ClientLogger(KeyVaultCredentialPolicy.class); private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String AUTHORIZATION =...
yes, we should, will update the PR. It's not throwing now but I put it as a safeguard to ensure this version of key vault lib works with the future version of reactor-netty HTTP client when it gets addressed in the core level.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme")); } return next.clone().process() .doOnNext(ht...
} catch (Throwable ignored) {
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme")); } return next.clone().process() .doOnNext(ht...
class KeyVaultCredentialPolicy implements HttpPipelinePolicy { private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String AUTHORIZATION = "Authorization"; private final ScopeTokenCache cache; /** * Creates KeyVaultCredentia...
class KeyVaultCredentialPolicy implements HttpPipelinePolicy { private final ClientLogger logger = new ClientLogger(KeyVaultCredentialPolicy.class); private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private static final String BEARER_TOKEN_PREFIX = "Bearer "; private static final String AUTHORIZATION =...
A method returning a reactive publisher shouldn't throw exceptions. It makes chaining of reactive operators difficult as the caller will have to handle errors in 2 ways. Return Flux.error() instead.
public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream, int chunkSize) { if (chunkSize <= 0) { throw new IllegalArgumentException("'chunkSize' must be greater than 0."); } if (inputStream == null) { return Flux.empty(); } return Flux.<ByteBuffer, InputStream>generate(() -> inputStream, (stream, sink) -...
}
public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream, int chunkSize) { if (chunkSize <= 0) { return Flux.error(new IllegalArgumentException("'chunkSize' must be greater than 0.")); } if (inputStream == null) { return Flux.empty(); } return Flux.<ByteBuffer, InputStream>generate(() -> inputStream, (st...
class FluxUtil { private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(new byte[0]); /** * Checks if a type is Flux&lt;ByteBuffer&gt;. * * @param entityType the type to check * @return whether the type represents a Flux that emits ByteBuffer */ public static boolean isFluxByteBuffer(Type entityType) { if (Type...
class FluxUtil { /** * Checks if a type is Flux&lt;ByteBuffer&gt;. * * @param entityType the type to check * @return whether the type represents a Flux that emits ByteBuffer */ public static boolean isFluxByteBuffer(Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Flux.class)) { final Type innerType = Type...
Changed to `Flux.error`
public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream, int chunkSize) { if (chunkSize <= 0) { throw new IllegalArgumentException("'chunkSize' must be greater than 0."); } if (inputStream == null) { return Flux.empty(); } return Flux.<ByteBuffer, InputStream>generate(() -> inputStream, (stream, sink) -...
}
public static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream, int chunkSize) { if (chunkSize <= 0) { return Flux.error(new IllegalArgumentException("'chunkSize' must be greater than 0.")); } if (inputStream == null) { return Flux.empty(); } return Flux.<ByteBuffer, InputStream>generate(() -> inputStream, (st...
class FluxUtil { private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.wrap(new byte[0]); /** * Checks if a type is Flux&lt;ByteBuffer&gt;. * * @param entityType the type to check * @return whether the type represents a Flux that emits ByteBuffer */ public static boolean isFluxByteBuffer(Type entityType) { if (Type...
class FluxUtil { /** * Checks if a type is Flux&lt;ByteBuffer&gt;. * * @param entityType the type to check * @return whether the type represents a Flux that emits ByteBuffer */ public static boolean isFluxByteBuffer(Type entityType) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Flux.class)) { final Type innerType = Type...
`!part.trim().isEmpty()` ?
private static String getValueFromIdByName(String id, String name) { if (id == null) { return null; } Iterable<String> iterable = Arrays.asList(id.split("/")); Iterator<String> itr = iterable.iterator(); while (itr.hasNext()) { String part = itr.next(); if (part != null && !part.trim().equals("")) { if (part.equalsIgno...
if (part != null && !part.trim().equals("")) {
private static String getValueFromIdByName(String id, String name) { if (id == null) { return null; } Iterable<String> iterable = Arrays.asList(id.split("/")); Iterator<String> itr = iterable.iterator(); while (itr.hasNext()) { String part = itr.next(); if (part != null && !part.trim().isEmpty()) { if (part.equalsIgnor...
class GalleryImageVersionImpl extends CreatableUpdatableImpl<GalleryImageVersion, GalleryImageVersionInner, GalleryImageVersionImpl> implements GalleryImageVersion, GalleryImageVersion.Definition, GalleryImageVersion.Update { private final ComputeManager manager; private String resourceGroupName; private String gallery...
class GalleryImageVersionImpl extends CreatableUpdatableImpl<GalleryImageVersion, GalleryImageVersionInner, GalleryImageVersionImpl> implements GalleryImageVersion, GalleryImageVersion.Definition, GalleryImageVersion.Update { private final ComputeManager manager; private String resourceGroupName; private String gallery...
done
private static String getValueFromIdByName(String id, String name) { if (id == null) { return null; } Iterable<String> iterable = Arrays.asList(id.split("/")); Iterator<String> itr = iterable.iterator(); while (itr.hasNext()) { String part = itr.next(); if (part != null && !part.trim().equals("")) { if (part.equalsIgno...
if (part != null && !part.trim().equals("")) {
private static String getValueFromIdByName(String id, String name) { if (id == null) { return null; } Iterable<String> iterable = Arrays.asList(id.split("/")); Iterator<String> itr = iterable.iterator(); while (itr.hasNext()) { String part = itr.next(); if (part != null && !part.trim().isEmpty()) { if (part.equalsIgnor...
class GalleryImageVersionImpl extends CreatableUpdatableImpl<GalleryImageVersion, GalleryImageVersionInner, GalleryImageVersionImpl> implements GalleryImageVersion, GalleryImageVersion.Definition, GalleryImageVersion.Update { private final ComputeManager manager; private String resourceGroupName; private String gallery...
class GalleryImageVersionImpl extends CreatableUpdatableImpl<GalleryImageVersion, GalleryImageVersionInner, GalleryImageVersionImpl> implements GalleryImageVersion, GalleryImageVersion.Definition, GalleryImageVersion.Update { private final ComputeManager manager; private String resourceGroupName; private String gallery...
I think this todo could be removed, since the proxy is inside http client now.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByt...
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( bod...
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private final TokenCredential credential; /** * Initialize a provider registration policy with a credential that's authorized * to register the provider. * ...
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private final TokenCredential credential; private final AzureProfile profile; /** * Initialize a provider registration policy with a credential that's autho...
I think pipeline builder is more clear
public void beforeTest(TestInfo testInfo) throws IOException { this.testInfo = testInfo; String testMothodName = testInfo.getTestMethod().get().getName(); printThreadInfo(String.format("%s: %s", "beforeTest", testMothodName)); final String skipMessage = shouldCancelTest(isPlaybackMode()); Assumptions.assumeTrue(skipMes...
retryPolicies.add(new HttpLoggingPolicy(httpLogOptions));
public void beforeTest(TestInfo testInfo) throws IOException { this.testInfo = testInfo; String testMothodName = testInfo.getTestMethod().get().getName(); printThreadInfo(String.format("%s: %s", "beforeTest", testMothodName)); final String skipMessage = shouldCancelTest(isPlaybackMode()); Assumptions.assumeTrue(skipMes...
class TestBase { private PrintStream out; private String baseUri; protected SdkContext sdkContext = new SdkContext(); public String generateRandomResourceName(String prefix, int maxLen) { return sdkContext.randomResourceName(prefix, maxLen); } protected enum RunCondition { MOCK_ONLY, LIVE_ONLY, BOTH } public enum TestM...
class TestBase { private PrintStream out; private String baseUri; protected SdkContext sdkContext = new SdkContext(); private AuthFile authFile; private AzureProfile profile; public String generateRandomResourceName(String prefix, int maxLen) { return sdkContext.randomResourceName(prefix, maxLen); } protected enum RunC...
same as above, if profile, why defaultsubs? what's defaultsubs?
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByt...
.withDefaultSubscription();
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( bod...
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private final TokenCredential credential; private final AzureProfile profile; /** * Initialize a provider registration policy with a credential that's autho...
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private final TokenCredential credential; private final AzureProfile profile; /** * Initialize a provider registration policy with a credential that's autho...
At first step, the users can create instance for `ResourceManager.Authenticated` without subscription id. Next step, they can use `withSubscription(id)` pass subs id into profile. In another case, they can use `withDefaultSubscription()` if profile already contains subs id.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByt...
.withDefaultSubscription();
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( bod...
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private final TokenCredential credential; private final AzureProfile profile; /** * Initialize a provider registration policy with a credential that's autho...
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private final TokenCredential credential; private final AzureProfile profile; /** * Initialize a provider registration policy with a credential that's autho...
Prefer not to have a `null` environment from start.
public AzureEnvironment environment() { if (this.environment == null) { this.environment = AzureEnvironment.AZURE; } return environment; }
}
public AzureEnvironment environment() { return environment; }
class AzureProfile { private String tenantId; private String subscriptionId; private AzureEnvironment environment; private final Configuration configuration = Configuration.getGlobalConfiguration(); /** * Creates AzureProfile instance with Azure environment. * * @param environment the Azure environment */ public AzureP...
class AzureProfile { private String tenantId; private String subscriptionId; private final AzureEnvironment environment; /** * Creates AzureProfile instance with Azure environment. The global environment is {@link AzureEnvironment * The tenant ID and subscription ID can be set via environment variables. The environment...
Maybe do a throw if `subscriptionId` is null in profile? If user really want to provide a null `subscriptionId`, we would like them to do it explicitly in `withSubscription(String subscriptionId)`. (or we should not allow `null` subscriptionId at all?) Also when will `CloudException` happen? It is scheduled to be dele...
public Azure withDefaultSubscription() throws CloudException { return new Azure(httpPipeline, profile, this); }
return new Azure(httpPipeline, profile, this);
public Azure withDefaultSubscription() { if (profile.subscriptionId() == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Please specify the subscription ID for resource management.")); } return new Azure(httpPipeline, profile, this); }
class AuthenticatedImpl implements Authenticated { private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRbacManager; private SdkContext sdkContext; private AuthenticatedImpl(HttpPipeline...
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
Keep this in order for default subs. Meanwhile add a with default tenant like it. Since these two could be null in profile. I think it more friendly than all need user to add.
public Providers providers() { return resourceManager.providers(); }
}
public Providers providers() { return resourceManager.providers(); }
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
Seems no need to clone it?
public AzureProfile(AzureEnvironment environment, boolean loadEnvironmentVariables) { Objects.requireNonNull(environment); if (loadEnvironmentVariables) { Configuration configuration = Configuration.getGlobalConfiguration().clone(); this.tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); this.subscri...
Configuration configuration = Configuration.getGlobalConfiguration().clone();
public AzureProfile(AzureEnvironment environment, boolean loadEnvironmentVariables) { Objects.requireNonNull(environment); this.environment = environment; if (loadEnvironmentVariables) { Configuration configuration = Configuration.getGlobalConfiguration(); this.tenantId = configuration.get(Configuration.PROPERTY_AZURE_...
class AzureProfile { private String tenantId; private String subscriptionId; private AzureEnvironment environment; /** * Creates AzureProfile instance with Azure environment. The global environment is {@link AzureEnvironment * The tenant ID and subscription ID can be set via environment variables. The environment varia...
class AzureProfile { private String tenantId; private String subscriptionId; private final AzureEnvironment environment; /** * Creates AzureProfile instance with Azure environment. The global environment is {@link AzureEnvironment * The tenant ID and subscription ID can be set via environment variables. The environment...
Why don't remove it?
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByt...
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { return next.process().flatMap( response -> { if (!isResponseSuccessful(response)) { HttpResponse bufferedResponse = response.buffer(); return FluxUtil.collectBytesInByteBufferStream(bufferedResponse.getBody()).flatMap( bod...
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private final TokenCredential credential; /** * Initialize a provider registration policy with a credential that's authorized * to register the provider. * ...
class ProviderRegistrationPolicy implements HttpPipelinePolicy { private static final String MISSING_SUBSCRIPTION_REGISTRATION = "MissingSubscriptionRegistration"; private final TokenCredential credential; private final AzureProfile profile; /** * Initialize a provider registration policy with a credential that's autho...
Personally I kind of against this code. It might just pick a wrong subscription id and mess things up, without user knowing anything. If there is only 1 subscription, this might be a good guess. If there is more than 1, it almost 100% wrong.
public Providers providers() { return resourceManager.providers(); }
}
public Providers providers() { return resourceManager.providers(); }
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
em, I'm not sure how many user will use only one subs for every credential. Like me, my auth will always be only one subs. Ok to remove it as I think it may be many beginner use the code in sample and will not set subs when call the default subs.
public Providers providers() { return resourceManager.providers(); }
}
public Providers providers() { return resourceManager.providers(); }
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
Yes, file usually only have one, but that is already coded in that file (and we kind of deprecate file for now). Our tenant actually got 10+ subIds, and I think you can list all of them in this stage. Maybe we can add e.g. `withSingleSubscription` if requirement arise (but still prefer only do this if there is only 1 ...
public Providers providers() { return resourceManager.providers(); }
}
public Providers providers() { return resourceManager.providers(); }
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
No, My auth will always list one subs from azure, since I only add one subs permission to one service principal, it will not list other subs. I think we could use `withProfileSubscription` and `withFirstSubscriptionFetched` to distinguish if we want. Sometimes the `withDefaultSubscription` is a little strange.
public Providers providers() { return resourceManager.providers(); }
}
public Providers providers() { return resourceManager.providers(); }
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
class AuthenticatedImpl implements Authenticated { private final ClientLogger logger = new ClientLogger(AuthenticatedImpl.class); private final HttpPipeline httpPipeline; private final AzureProfile profile; private final ResourceManager.Authenticated resourceManagerAuthenticated; private final GraphRbacManager graphRba...
The sequence number can be 0 if it is in the beginning of stream.
void nonSessionScheduleMessage(MessagingEntityType entityType) { setSenderAndReceiver(entityType); final Instant scheduledEnqueueTime = Instant.now().plusSeconds(10); final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBus...
Assertions.assertTrue(sequenceNumber > 0);
void nonSessionScheduleMessage(MessagingEntityType entityType) { setSenderAndReceiver(entityType); final Instant scheduledEnqueueTime = Instant.now().plusSeconds(10); final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBus...
class ServiceBusSenderClientIntegrationTest extends IntegrationTestBase { private ServiceBusSenderClient sender; private ServiceBusReceiverAsyncClient receiver; private final AtomicInteger messagesPending = new AtomicInteger(); ServiceBusSenderClientIntegrationTest() { super(new ClientLogger(ServiceBusSenderAsyncClient...
class ServiceBusSenderClientIntegrationTest extends IntegrationTestBase { private ServiceBusSenderClient sender; private ServiceBusReceiverAsyncClient receiver; private final AtomicInteger messagesPending = new AtomicInteger(); ServiceBusSenderClientIntegrationTest() { super(new ClientLogger(ServiceBusSenderAsyncClient...
If this succeeds, you'll want to decrement messages pending.
void nonSessionCancelScheduleMessage(MessagingEntityType entityType) { setSenderAndReceiver(entityType); final Instant scheduledEnqueueTime = Instant.now().plusSeconds(20); final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServ...
sender.cancelScheduledMessage(sequenceNumber);
void nonSessionCancelScheduleMessage(MessagingEntityType entityType) { setSenderAndReceiver(entityType); final Instant scheduledEnqueueTime = Instant.now().plusSeconds(20); final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServ...
class ServiceBusSenderClientIntegrationTest extends IntegrationTestBase { private ServiceBusSenderClient sender; private ServiceBusReceiverAsyncClient receiver; private final AtomicInteger messagesPending = new AtomicInteger(); ServiceBusSenderClientIntegrationTest() { super(new ClientLogger(ServiceBusSenderAsyncClient...
class ServiceBusSenderClientIntegrationTest extends IntegrationTestBase { private ServiceBusSenderClient sender; private ServiceBusReceiverAsyncClient receiver; private final AtomicInteger messagesPending = new AtomicInteger(); ServiceBusSenderClientIntegrationTest() { super(new ClientLogger(ServiceBusSenderAsyncClient...
I am changing it to >=0 but When I try to send first message to a Queue, it always start from 1. But SB docs says that after reaching to max, it can roll over to zero.
void nonSessionScheduleMessage(MessagingEntityType entityType) { setSenderAndReceiver(entityType); final Instant scheduledEnqueueTime = Instant.now().plusSeconds(10); final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBus...
Assertions.assertTrue(sequenceNumber > 0);
void nonSessionScheduleMessage(MessagingEntityType entityType) { setSenderAndReceiver(entityType); final Instant scheduledEnqueueTime = Instant.now().plusSeconds(10); final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBus...
class ServiceBusSenderClientIntegrationTest extends IntegrationTestBase { private ServiceBusSenderClient sender; private ServiceBusReceiverAsyncClient receiver; private final AtomicInteger messagesPending = new AtomicInteger(); ServiceBusSenderClientIntegrationTest() { super(new ClientLogger(ServiceBusSenderAsyncClient...
class ServiceBusSenderClientIntegrationTest extends IntegrationTestBase { private ServiceBusSenderClient sender; private ServiceBusReceiverAsyncClient receiver; private final AtomicInteger messagesPending = new AtomicInteger(); ServiceBusSenderClientIntegrationTest() { super(new ClientLogger(ServiceBusSenderAsyncClient...
It might be more readable if you have one setter per line.
public Field build() { return new Field().setName(super.getName()).setType(super.getDataType()).setSearchable(true) .setKey(super.isKey()).setSortable(super.isSortable()).setFilterable(super.isFilterable()) .setHidden(super.isHidden()).setFacetable(super.isFacetable()).setAnalyzer(this.analyzer) .setSearchAnalyzer(this...
.setSynonymMaps(this.synonymMaps);
public Field build() { return new Field() .setName(super.getName()) .setType(super.getDataType()) .setSearchable(true) .setKey(super.isKey()) .setSortable(super.isSortable()) .setFilterable(super.isFilterable()) .setHidden(super.isHidden()) .setFacetable(super.isFacetable()) .setAnalyzer(this.analyzer) .setSearchAnalyz...
class SearchableField extends SimpleField { private AnalyzerName analyzer; private AnalyzerName searchAnalyzer; private AnalyzerName indexAnalyzer; private List<String> synonymMaps; /** * Initializes a new instance of the {@link SearchableField} class. * * @param name The name of the field, which must be unique within ...
class SearchableField extends SimpleField { private AnalyzerName analyzer; private AnalyzerName searchAnalyzer; private AnalyzerName indexAnalyzer; private List<String> synonymMapNames; /** * Initializes a new instance of the {@link SearchableField} class. * * @param name The name of the field, which must be unique wit...
Could you put a TODO note with the created isssue to track the inconsistent behavior we were seeing.
static void validateAccountProperties(AccountProperties actualAccountProperties) { assertNotNull(actualAccountProperties.getCustomModelLimit()); assertNotNull(actualAccountProperties.getCustomModelCount()); }
assertNotNull(actualAccountProperties.getCustomModelLimit());
static void validateAccountProperties(AccountProperties actualAccountProperties) { assertNotNull(actualAccountProperties.getCustomModelLimit()); assertNotNull(actualAccountProperties.getCustomModelCount()); }
class FormTrainingClientTestBase extends TestBase { static final String FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL"; static final String FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"; static final String AZURE_FO...
class FormTrainingClientTestBase extends TestBase { static final String FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL"; static final String FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"; static final String AZURE_FO...
Can we add an actual exception message if we ever run into this issue in production.
private static Type getComponentOrElementType(Type arrayOrListType, ClientLogger logger) { if (arrayOrListType.getClass().isArray()) { return arrayOrListType.getClass().getComponentType(); } if (isList(arrayOrListType)) { ParameterizedType pt = (ParameterizedType) arrayOrListType; return pt.getActualTypeArguments()[0];...
throw logger.logExceptionAsError(new RuntimeException("Should not be there"));
private static Type getComponentOrElementType(Type arrayOrListType, ClientLogger logger) { if (arrayOrListType.getClass().isArray()) { return arrayOrListType.getClass().getComponentType(); } if (isList(arrayOrListType)) { ParameterizedType pt = (ParameterizedType) arrayOrListType; return pt.getActualTypeArguments()[0];...
class chain from {@code modelClass}
class chain from {@code modelClass}
"Collection type is not supported." rather than first person pronouns like "We"
private static Type getComponentOrElementType(Type arrayOrListType, ClientLogger logger) { if (arrayOrListType.getClass().isArray()) { return arrayOrListType.getClass().getComponentType(); } if (isList(arrayOrListType)) { ParameterizedType pt = (ParameterizedType) arrayOrListType; return pt.getActualTypeArguments()[0];...
throw logger.logExceptionAsError(new RuntimeException("We currently do not support the collection type: "
private static Type getComponentOrElementType(Type arrayOrListType, ClientLogger logger) { if (arrayOrListType.getClass().isArray()) { return arrayOrListType.getClass().getComponentType(); } if (isList(arrayOrListType)) { ParameterizedType pt = (ParameterizedType) arrayOrListType; return pt.getActualTypeArguments()[0];...
class chain from {@code modelClass}
class chain from {@code modelClass}
This is easier to read as: `return type.getClass().isArray() || isList(type);`
private static boolean isArrayOrList(Type type) { if (type.getClass().isArray()) { return true; } return isList(type); }
if (type.getClass().isArray()) {
private static boolean isArrayOrList(Type type) { return type.getClass().isArray() || isList(type); }
class chain from {@code modelClass}
class chain from {@code modelClass}
I'm a fan of bailing out of a method early. I think it makes it easier to read and the actual logic isn't shifted to the right with a ton of spaces if there are nested if-statements. It's a personal preference. You can leave as-is if you want. ``` if (!(type instanceof ParameterizedType)) { return false; } Type ra...
private static boolean isList(Type type) { if (type instanceof ParameterizedType) { Type rawType = ((ParameterizedType) type).getRawType(); return List.class.isAssignableFrom((Class<?>) rawType); } return false; }
return false;
private static boolean isList(Type type) { if (!(type instanceof ParameterizedType)) { return false; } Type rawType = ((ParameterizedType) type).getRawType(); return List.class.isAssignableFrom((Class<?>) rawType); }
class chain from {@code modelClass}
class chain from {@code modelClass}
Have you tried `Collections.sort(fields, (o1, o2) -> {})`? It'll save you from having to turn this from a list to a stream, then back into a list.
private List<Field> sortByFieldName(List<Field> fields) { return fields.stream().sorted((o1, o2) -> o1.getName().compareTo(o2.getName())).collect(Collectors.toList()); }
return fields.stream().sorted((o1, o2) -> o1.getName().compareTo(o2.getName())).collect(Collectors.toList());
private List<Field> sortByFieldName(List<Field> fields) { Collections.sort(fields, Comparator.comparing(Field::getName)); return fields; }
class FieldBuilderTest { @Test public void hotelComparison() { List<Field> actualFields = sortByFieldName(FieldBuilder.build(Hotel.class)); List<Field> expectedFields = sortByFieldName(buildHotelFields()); assertListFieldEquals(expectedFields, actualFields); } @Test public void hotelSearchableThrowException() { Excepti...
class FieldBuilderTest { @Test public void hotelComparison() { List<Field> actualFields = sortByFieldName(FieldBuilder.build(Hotel.class)); List<Field> expectedFields = sortByFieldName(buildHotelFields()); assertListFieldEquals(expectedFields, actualFields); } @Test public void hotelSearchableThrowException() { Excepti...
Nit: "The name of *the* field cannot be null"
protected FieldBase(String name, DataType dataType) { if (CoreUtils.isNullOrEmpty(name)) { throw logger.logExceptionAsError(new IllegalArgumentException("The name of field cannot be null")); } this.dataType = Objects.requireNonNull(dataType, "'dataType' cannot be null."); this.name = name; }
throw logger.logExceptionAsError(new IllegalArgumentException("The name of field cannot be null"));
protected FieldBase(String name, DataType dataType) { if (CoreUtils.isNullOrEmpty(name)) { throw logger.logExceptionAsError(new IllegalArgumentException("The name of the field cannot be null")); } this.dataType = Objects.requireNonNull(dataType, "'dataType' cannot be null."); this.name = name; }
class FieldBase { private final ClientLogger logger = new ClientLogger(FieldBase.class); private final String name; private final DataType dataType; /** * Initializes a new instance of the {@link FieldBase} class. * @param name The name of the field, which must be unique within the index or parent field. * @param dataT...
class FieldBase { private final ClientLogger logger = new ClientLogger(FieldBase.class); private final String name; private final DataType dataType; /** * Initializes a new instance of the {@link FieldBase} class. * @param name The name of the field, which must be unique within the index or parent field. * @param dataT...
The default behavior mentioned in the JavaDoc does not match the code?
public void processEventBatch(EventBatchContext eventBatchContext) { throw logger.logExceptionAsError(new UnsupportedOperationException("Processing event batch not implemented")); }
throw logger.logExceptionAsError(new UnsupportedOperationException("Processing event batch not implemented"));
public void processEventBatch(EventBatchContext eventBatchContext) { throw logger.logExceptionAsError(new UnsupportedOperationException("Processing event batch not implemented")); }
class PartitionProcessor { private final ClientLogger logger = new ClientLogger(PartitionProcessor.class); /** * This method is called when this {@link EventProcessorClient} takes ownership of a new partition and before any * events from this partition are received. * * @param initializationContext The initialization c...
class PartitionProcessor { private final ClientLogger logger = new ClientLogger(PartitionProcessor.class); /** * This method is called when this {@link EventProcessorClient} takes ownership of a new partition and before any * events from this partition are received. * * @param initializationContext The initialization c...
Updated the javadoc.
public void processEventBatch(EventBatchContext eventBatchContext) { throw logger.logExceptionAsError(new UnsupportedOperationException("Processing event batch not implemented")); }
throw logger.logExceptionAsError(new UnsupportedOperationException("Processing event batch not implemented"));
public void processEventBatch(EventBatchContext eventBatchContext) { throw logger.logExceptionAsError(new UnsupportedOperationException("Processing event batch not implemented")); }
class PartitionProcessor { private final ClientLogger logger = new ClientLogger(PartitionProcessor.class); /** * This method is called when this {@link EventProcessorClient} takes ownership of a new partition and before any * events from this partition are received. * * @param initializationContext The initialization c...
class PartitionProcessor { private final ClientLogger logger = new ClientLogger(PartitionProcessor.class); /** * This method is called when this {@link EventProcessorClient} takes ownership of a new partition and before any * events from this partition are received. * * @param initializationContext The initialization c...
we should not check the exact number but not null should be the better way. Create a bug issue: #9269
static void validateAccountProperties(AccountProperties actualAccountProperties) { assertNotNull(actualAccountProperties.getCustomModelLimit()); assertNotNull(actualAccountProperties.getCustomModelCount()); }
assertNotNull(actualAccountProperties.getCustomModelLimit());
static void validateAccountProperties(AccountProperties actualAccountProperties) { assertNotNull(actualAccountProperties.getCustomModelLimit()); assertNotNull(actualAccountProperties.getCustomModelCount()); }
class FormTrainingClientTestBase extends TestBase { static final String FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL"; static final String FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"; static final String AZURE_FO...
class FormTrainingClientTestBase extends TestBase { static final String FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL"; static final String FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL = "FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"; static final String AZURE_FO...
The check `map.containsKey(ManagementConstants.SESSION_STATE)` : Does not have value if we do it after we already try to get `sessionState`. Either this check should be before or not required because `sessionState == null` will be sufficient.
public Mono<byte[]> getSessionState() { if (!isSessionEnabled) { return monoError(logger, new IllegalStateException("Cannot get session state for non-session management node")); } return isAuthorized(ManagementConstants.OPERATION_GET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createM...
logger.info("sessionId[{}]. Does not have a session state.", sessionId);
public Mono<byte[]> getSessionState() { if (!isSessionEnabled) { return monoError(logger, new IllegalStateException("Cannot get session state for non-session management node")); } return isAuthorized(ManagementConstants.OPERATION_GET_SESSION_STATE).then(createChannel.flatMap(channel -> { final Message message = createM...
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createChannel; private final String fullyQualifiedNamespace; private final ClientL...
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createChannel; private final String fullyQualifiedNamespace; private final ClientL...
Are we going to add these API in `ServiceBusReceiverClient` . Also will we add integration test for this ?
public Mono<Instant> renewSessionLock(String sessionId) { if (!isSessionReceiver) { return monoError(logger, new IllegalStateException("Cannot renew session lock on a non-session receiver.")); } else { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType, sessionId)) .fl...
if (!isSessionReceiver) {
public Mono<Instant> renewSessionLock(String sessionId) { if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "renewSessionLock"))); } else if (!isSessionReceiver) { return monoError(logger, new IllegalStateException("Cannot renew session lock o...
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private fi...
class ServiceBusReceiverAsyncClient implements AutoCloseable { private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions(); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private fi...
Why the assertion here? It's not testing our code
void sendMessageList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messageList = new ArrayList<>(); IntStream.range(0, count).forEach(index -> { final ServiceBusMessage message = new ServiceBusMessage(contents); Assertions.assertTrue(messageList.add(messag...
Assertions.assertTrue(messageList.add(message));
void sendMessageList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString(), contents); when(asyncSender.send(messages)).thenReturn(Mono.empty()); sender.send(messages); verify(asyncSend...
class ServiceBusSenderClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private ServiceBusSenderAsyncClient asyncSender; @Captor private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor; @Captor private ArgumentCaptor<List<S...
class ServiceBusSenderClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private ServiceBusSenderAsyncClient asyncSender; @Captor private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor; @Captor private ArgumentCaptor<List<S...
Does message need to be fully qualified
void sendMessagesList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messageList = new ArrayList<>(); IntStream.range(0, count).forEach(index -> { final ServiceBusMessage message = new ServiceBusMessage(contents); Assertions.assertTrue(messageList.add(messa...
Assertions.assertEquals(count, messagesSent.size());
void sendMessagesList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString()); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(s...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
Why an assertion here?
void sendMessagesList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messageList = new ArrayList<>(); IntStream.range(0, count).forEach(index -> { final ServiceBusMessage message = new ServiceBusMessage(contents); Assertions.assertTrue(messageList.add(messa...
Assertions.assertTrue(messageList.add(message));
void sendMessagesList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString()); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(s...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
Yes, so the changefeed feature relies on the existence of this special container that the service creates. All the blobs we read for this feature are in this container.
private Mono<Boolean> validateChangefeed() { return this.client.exists() .flatMap(exists -> { if (exists == null || !exists) { return FluxUtil.monoError(logger, new RuntimeException("Changefeed has not been enabled for " + "this account.")); } return Mono.just(true); }); }
+ "this account."));
private Mono<Boolean> validateChangefeed() { return this.client.exists() .flatMap(exists -> { if (exists == null || !exists) { return FluxUtil.monoError(logger, new RuntimeException("Changefeed has not been enabled for " + "this account.")); } return Mono.just(true); }); }
class Changefeed { private final ClientLogger logger = new ClientLogger(Changefeed.class); private static final String SEGMENT_PREFIX = "idx/segments/"; private static final String METADATA_SEGMENT_PATH = "meta/segments.json"; private static final ObjectMapper mapper = new ObjectMapper(); private final BlobContainerAsy...
class Changefeed { private final ClientLogger logger = new ClientLogger(Changefeed.class); private static final String SEGMENT_PREFIX = "idx/segments/"; private static final String METADATA_SEGMENT_PATH = "meta/segments.json"; private static final ObjectMapper MAPPER = new ObjectMapper(); private final BlobContainerAsy...
there is also `never()` => `times(0)`
void sendMessagesListExceedSize() { final int count = 4; final Mono<Integer> linkMaxSize = Mono.just(1); final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final ServiceBusMessage[] messages = new ServiceBusMessage[count]; IntStream.range(0, count).forEach(index -> { messages[index] = new ServiceBusMessage(contents...
verify(sendLink, times(0)).send(anyList());
void sendMessagesListExceedSize() { final int count = 4; final Mono<Integer> linkMaxSize = Mono.just(1); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString()); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.jus...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
Why not `for (int i = 0; i < messages.length; i++)`? I don't see any added benefit creating this IntStream.
void sendMessageList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final ServiceBusMessage[] messages = new ServiceBusMessage[count]; IntStream.range(0, count).forEach(index -> { messages[index] = new ServiceBusMessage(contents).setSessionId(UUID.randomUUID().toString()); }); when(asyn...
IntStream.range(0, count).forEach(index -> {
void sendMessageList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString(), contents); when(asyncSender.send(messages)).thenReturn(Mono.empty()); sender.send(messages); verify(asyncSend...
class ServiceBusSenderClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private ServiceBusSenderAsyncClient asyncSender; @Captor private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor; @Captor private ArgumentCaptor<Servic...
class ServiceBusSenderClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private ServiceBusSenderAsyncClient asyncSender; @Captor private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor; @Captor private ArgumentCaptor<List<S...
Why not `for (int i = 0; i < messages.length; i++)`? I don't see any added benefit creating this IntStream.
void sendMessagesListExceedSize() { final int count = 4; final Mono<Integer> linkMaxSize = Mono.just(1); final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final ServiceBusMessage[] messages = new ServiceBusMessage[count]; IntStream.range(0, count).forEach(index -> { messages[index] = new ServiceBusMessage(contents...
IntStream.range(0, count).forEach(index -> {
void sendMessagesListExceedSize() { final int count = 4; final Mono<Integer> linkMaxSize = Mono.just(1); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString()); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.jus...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
Why not `for (int i = 0; i < messages.length; i++)`? I don't see any added benefit creating this IntStream.
void sendMessagesList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final ServiceBusMessage[] messages = new ServiceBusMessage[count]; IntStream.range(0, count).forEach(index -> { messages[index] = new ServiceBusMessage(contents).setMessageId(UUID.randomUUID().toString()); }); when(con...
IntStream.range(0, count).forEach(index -> {
void sendMessagesList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString()); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(s...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorCont...
There's a helper method that does all this: `TestUtils.getServiceBusMessages(3, id).toArray()`
void sendMessageList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final ServiceBusMessage[] messages = new ServiceBusMessage[count]; IntStream.range(0, count).forEach(index -> { messages[index] = new ServiceBusMessage(contents).setSessionId(UUID.randomUUID().toString()); }); when(asyn...
IntStream.range(0, count).forEach(index -> {
void sendMessageList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString(), contents); when(asyncSender.send(messages)).thenReturn(Mono.empty()); sender.send(messages); verify(asyncSend...
class ServiceBusSenderClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private ServiceBusSenderAsyncClient asyncSender; @Captor private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor; @Captor private ArgumentCaptor<Servic...
class ServiceBusSenderClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private ServiceBusSenderAsyncClient asyncSender; @Captor private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor; @Captor private ArgumentCaptor<List<S...
This should return `monoError(logger, new NullPointerException("'messages' cannot be null.");` rather than throwing. There are other instances that I need to look at and fix. It's odd when async operations throw instead of returning the terminal error state.
public Mono<Void> send(Iterable<ServiceBusMessage> messages) { Objects.requireNonNull(messages, "'messages' cannot be null."); return createBatch().flatMap(messageBatch -> { messages.forEach(message -> messageBatch.tryAdd(message)); return send(messageBatch); }); }
Objects.requireNonNull(messages, "'messages' cannot be null.");
public Mono<Void> send(Iterable<ServiceBusMessage> messages) { if (Objects.isNull(messages)) { return monoError(logger, new NullPointerException("'messages' cannot be null.")); } return createBatch().flatMap(messageBatch -> { messages.forEach(message -> messageBatch.tryAdd(message)); return send(messageBatch); }); }
class ServiceBusSenderAsyncClient implements AutoCloseable { /** * The default maximum allowable size, in bytes, for a batch to be sent. */ static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024; private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions(); private final ClientLogger logger...
class ServiceBusSenderAsyncClient implements AutoCloseable { /** * The default maximum allowable size, in bytes, for a batch to be sent. */ static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024; private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions(); private final ClientLogger logger...
why is the language just set to english? it seems that no matter what you pass in for language, your language is just going to be english
public TextDocumentInput(String id, String text) { this.id = id; this.text = text; this.language = "en"; }
this.language = "en";
public TextDocumentInput(String id, String text) { this.id = id; this.text = text; }
class TextDocumentInput { /* * A unique, non-empty document identifier. */ private final String id; /* * The document to process. */ private final String text; /* * (Optional) This is the 2 letter ISO 639-1 representation of a language. * For example, use "en" for English; "es" for Spanish etc. If not set, use * "en" f...
class TextDocumentInput { /* * A unique, non-empty document identifier. */ private final String id; /* * The document to process. */ private final String text; /* * (Optional) This is the 2 letter ISO 639-1 representation of a language. * For example, use "en" for English; "es" for Spanish etc. If not set, use * "en" f...
COuld consider adding a `setLanguage` here ?
public void recognizeLinkedEntitiesBatchMaxOverload() { List<TextDocumentInput> textDocumentInputs = Arrays.asList( new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park."), new TextDocumentInput("2", "Mount Shasta has lenticular clouds.") ); textAnalyticsClient.recognizeLinkedEntitiesBatch(textDocum...
new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park."),
public void recognizeLinkedEntitiesBatchMaxOverload() { List<TextDocumentInput> textDocumentInputs = Arrays.asList( new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.").setLanguage("en"), new TextDocumentInput("2", "Mount Shasta has lenticular clouds.").setLanguage("en") ); textAnalyticsClient.re...
class TextAnalyticsClientJavaDocCodeSnippets { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for creating a {@link TextAnalyticsClient} with pipeline */ public void createTextAnalyticsClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBu...
class TextAnalyticsClientJavaDocCodeSnippets { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for creating a {@link TextAnalyticsClient} with pipeline */ public void createTextAnalyticsClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBu...
Would it help to assert the warning and confirm result has the expected result + warnings?
public void recognizeEntitiesForFaultyText() { StepVerifier.create(client.recognizeEntities("!@ .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete(); }
.assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext()))
public void recognizeEntitiesForFaultyText() { StepVerifier.create(client.recognizeEntities("!@ .assertNext(result -> assertFalse(result.getWarnings().iterator().hasNext())) .verifyComplete(); }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
it will be good to check the status code and error code?
public void recognizeEntitiesTooManyDocuments() { recognizeEntitiesTooManyDocumentsRunner(inputs -> { StepVerifier.create(client.recognizeEntitiesBatch(inputs)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass())); }); }
.verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()));
public void recognizeEntitiesTooManyDocuments() { recognizeEntitiesTooManyDocumentsRunner(inputs -> { StepVerifier.create(client.recognizeEntitiesBatch(inputs)) .verifyErrorSatisfies(ex -> { HttpResponseException exception = (HttpResponseException) ex; assertEquals(HttpResponseException.class, exception.getClass()); as...
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
Use `this` consistently. Here one is using `this` and another is not: `this.secretKeys` and `secretKeys`
public String get(final String property) { Assert.hasText(property, "property should contain text."); final String secretName = getKeyVaultSecretName(property); if (this.secretKeys == null || secretKeys.size() == 0) { refreshPropertyNames(); } if (this.propertyNames.contains(secretName)) { final KeyVaultSecret secret =...
if (this.secretKeys == null || secretKeys.size() == 0) {
public String get(final String property) { Assert.hasText(property, "property should contain text."); final String secretName = getKeyVaultSecretName(property); if (this.secretKeys == null || secretKeys.size() == 0) { refreshPropertyNames(); } if (this.propertyNames.contains(secretName)) { final KeyVaultSecret secret =...
class KeyVaultOperation { private final long cacheRefreshIntervalInMs; private final List<String> secretKeys; private final Object refreshLock = new Object(); private final SecretClient keyVaultClient; private final String vaultUri; private ArrayList<String> propertyNames = new ArrayList<>(); private String[] propertyN...
class KeyVaultOperation { private final long cacheRefreshIntervalInMs; private final List<String> secretKeys; private final Object refreshLock = new Object(); private final SecretClient secretClient; private final String vaultUri; private ArrayList<String> propertyNames = new ArrayList<>(); private String[] propertyNam...
Sorry I was wrong when I suggested this, I didn't realize that this TextDocumentInput constructor didn't take language. I'm confused though: it looks like in [master](https://github.com/Azure/azure-sdk-for-java/blob/fcdaff1ebc84a6f660f94c54038c2c34fef76e0c/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azur...
public TextDocumentInput(String id, String text) { this.id = id; this.text = text; }
}
public TextDocumentInput(String id, String text) { this.id = id; this.text = text; }
class TextDocumentInput { /* * A unique, non-empty document identifier. */ private final String id; /* * The document to process. */ private final String text; /* * (Optional) This is the 2 letter ISO 639-1 representation of a language. * For example, use "en" for English; "es" for Spanish etc. If not set, use * "en" f...
class TextDocumentInput { /* * A unique, non-empty document identifier. */ private final String id; /* * The document to process. */ private final String text; /* * (Optional) This is the 2 letter ISO 639-1 representation of a language. * For example, use "en" for English; "es" for Spanish etc. If not set, use * "en" f...
if in the future, the default lanauge is change to 'es`. we need to update it to `es`. Since service team take default value in service side, we should not add what they are maintaining here. So keep no-assigned in SDK should be an better idea.
public TextDocumentInput(String id, String text) { this.id = id; this.text = text; }
}
public TextDocumentInput(String id, String text) { this.id = id; this.text = text; }
class TextDocumentInput { /* * A unique, non-empty document identifier. */ private final String id; /* * The document to process. */ private final String text; /* * (Optional) This is the 2 letter ISO 639-1 representation of a language. * For example, use "en" for English; "es" for Spanish etc. If not set, use * "en" f...
class TextDocumentInput { /* * A unique, non-empty document identifier. */ private final String id; /* * The document to process. */ private final String text; /* * (Optional) This is the 2 letter ISO 639-1 representation of a language. * For example, use "en" for English; "es" for Spanish etc. If not set, use * "en" f...
Do you really need a lock? Can declaring `propertyNamesArr` as volatile be sufficient?
public String[] list() { try { this.rwLock.readLock().lock(); return propertyNamesArr; } finally { this.rwLock.readLock().unlock(); } }
}
public String[] list() { try { this.rwLock.readLock().lock(); return propertyNamesArr; } finally { this.rwLock.readLock().unlock(); } }
class KeyVaultOperation { private final long cacheRefreshIntervalInMs; private final List<String> secretKeys; private final Object refreshLock = new Object(); private final SecretClient keyVaultClient; private final String vaultUri; private ArrayList<String> propertyNames = new ArrayList<>(); private String[] propertyN...
class KeyVaultOperation { private final long cacheRefreshIntervalInMs; private final List<String> secretKeys; private final Object refreshLock = new Object(); private final SecretClient secretClient; private final String vaultUri; private ArrayList<String> propertyNames = new ArrayList<>(); private String[] propertyNam...
Yes, the write method `fillSecretsList` could be called from multiple threads simultaneously when refreshing `propertyNames`.
public String[] list() { try { this.rwLock.readLock().lock(); return propertyNamesArr; } finally { this.rwLock.readLock().unlock(); } }
}
public String[] list() { try { this.rwLock.readLock().lock(); return propertyNamesArr; } finally { this.rwLock.readLock().unlock(); } }
class KeyVaultOperation { private final long cacheRefreshIntervalInMs; private final List<String> secretKeys; private final Object refreshLock = new Object(); private final SecretClient keyVaultClient; private final String vaultUri; private ArrayList<String> propertyNames = new ArrayList<>(); private String[] propertyN...
class KeyVaultOperation { private final long cacheRefreshIntervalInMs; private final List<String> secretKeys; private final Object refreshLock = new Object(); private final SecretClient secretClient; private final String vaultUri; private ArrayList<String> propertyNames = new ArrayList<>(); private String[] propertyNam...
done.
public String get(final String property) { Assert.hasText(property, "property should contain text."); final String secretName = getKeyVaultSecretName(property); if (this.secretKeys == null || secretKeys.size() == 0) { refreshPropertyNames(); } if (this.propertyNames.contains(secretName)) { final KeyVaultSecret secret =...
if (this.secretKeys == null || secretKeys.size() == 0) {
public String get(final String property) { Assert.hasText(property, "property should contain text."); final String secretName = getKeyVaultSecretName(property); if (this.secretKeys == null || secretKeys.size() == 0) { refreshPropertyNames(); } if (this.propertyNames.contains(secretName)) { final KeyVaultSecret secret =...
class KeyVaultOperation { private final long cacheRefreshIntervalInMs; private final List<String> secretKeys; private final Object refreshLock = new Object(); private final SecretClient keyVaultClient; private final String vaultUri; private ArrayList<String> propertyNames = new ArrayList<>(); private String[] propertyN...
class KeyVaultOperation { private final long cacheRefreshIntervalInMs; private final List<String> secretKeys; private final Object refreshLock = new Object(); private final SecretClient secretClient; private final String vaultUri; private ArrayList<String> propertyNames = new ArrayList<>(); private String[] propertyNam...
Can you add that the other copy is when we write it to the pool? Just so we don't forget what we mean later?
Flux<ByteBuffer> write(ByteBuffer buf) { /* TODO (gapra): Investigate if there is way to avoid copying the data twice since this may result in lower perf. */ /* Deep copy the buffer. This is required to ensure integrity of data. */ ByteBuffer cachedBuffer = ByteBuffer.allocate(buf.remaining()).put(buf); cachedBuffer.fl...
/* TODO (gapra): Investigate if there is way to avoid copying the data twice since this may result in lower perf. */
Flux<ByteBuffer> write(ByteBuffer buf) { /* TODO (gapra): Investigate if there is way to avoid copying the data twice since this may result in lower perf. The other copy is when we write the buffer to the pool */ /* Deep copy the buffer. This is required to ensure integrity of data. */ ByteBuffer cachedBuffer = ByteBuf...
class PayloadSizeGate { private final long threshold; private long size = 0; private Queue<ByteBuffer> byteBuffers = new LinkedList<>(); /** * Creates a new instance of PayloadSizeGate * @param threshold Number of bytes up to which data is buffered. */ PayloadSizeGate(long threshold) { this.threshold = threshold; } /**...
class PayloadSizeGate { private final long threshold; private long size = 0; private Queue<ByteBuffer> byteBuffers = new LinkedList<>(); /** * Creates a new instance of PayloadSizeGate * @param threshold Number of bytes up to which data is buffered. */ PayloadSizeGate(long threshold) { this.threshold = threshold; } /**...
Ups. My bad. I think there isn't double copy now as copying was removed buffer pool - hence regression. For future. Maybe it would be good to extract copying part to separate component that's inserted into Flux transform early in the process - so that it's more explicit (as we apparently quite depend on that).
Flux<ByteBuffer> write(ByteBuffer buf) { /* TODO (gapra): Investigate if there is way to avoid copying the data twice since this may result in lower perf. The other copy is when we write the buffer to the pool */ /* Deep copy the buffer. This is required to ensure integrity of data. */ ByteBuffer cachedBuffer = ByteBuf...
cachedBuffer.flip();
Flux<ByteBuffer> write(ByteBuffer buf) { /* TODO (gapra): Investigate if there is way to avoid copying the data twice since this may result in lower perf. The other copy is when we write the buffer to the pool */ /* Deep copy the buffer. This is required to ensure integrity of data. */ ByteBuffer cachedBuffer = ByteBuf...
class PayloadSizeGate { private final long threshold; private long size = 0; private Queue<ByteBuffer> byteBuffers = new LinkedList<>(); /** * Creates a new instance of PayloadSizeGate * @param threshold Number of bytes up to which data is buffered. */ PayloadSizeGate(long threshold) { this.threshold = threshold; } /**...
class PayloadSizeGate { private final long threshold; private long size = 0; private Queue<ByteBuffer> byteBuffers = new LinkedList<>(); /** * Creates a new instance of PayloadSizeGate * @param threshold Number of bytes up to which data is buffered. */ PayloadSizeGate(long threshold) { this.threshold = threshold; } /**...
https://github.com/Azure/azure-sdk-for-java/issues/10639
Flux<ByteBuffer> write(ByteBuffer buf) { /* TODO (gapra): Investigate if there is way to avoid copying the data twice since this may result in lower perf. The other copy is when we write the buffer to the pool */ /* Deep copy the buffer. This is required to ensure integrity of data. */ ByteBuffer cachedBuffer = ByteBuf...
cachedBuffer.flip();
Flux<ByteBuffer> write(ByteBuffer buf) { /* TODO (gapra): Investigate if there is way to avoid copying the data twice since this may result in lower perf. The other copy is when we write the buffer to the pool */ /* Deep copy the buffer. This is required to ensure integrity of data. */ ByteBuffer cachedBuffer = ByteBuf...
class PayloadSizeGate { private final long threshold; private long size = 0; private Queue<ByteBuffer> byteBuffers = new LinkedList<>(); /** * Creates a new instance of PayloadSizeGate * @param threshold Number of bytes up to which data is buffered. */ PayloadSizeGate(long threshold) { this.threshold = threshold; } /**...
class PayloadSizeGate { private final long threshold; private long size = 0; private Queue<ByteBuffer> byteBuffers = new LinkedList<>(); /** * Creates a new instance of PayloadSizeGate * @param threshold Number of bytes up to which data is buffered. */ PayloadSizeGate(long threshold) { this.threshold = threshold; } /**...
just curious, is this issue happens due to one of these operators eagerly subscribing? or something else?
static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[...
return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> {
static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[...
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less tha...
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less tha...
I see the state variables were getting shared across subscriptions on request content.
static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[...
return Flux.concat(bbFlux, Flux.just(VALIDATION_BUFFER)).handle((buffer, sink) -> {
static Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.getBody(); if (bbFlux == null) { return Flux.empty(); } long expectedLength = Long.parseLong(request.getHeaders().getValue("Content-Length")); return Flux.defer(() -> { final long[] currentTotalLength = new long[...
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less tha...
class RestProxy implements InvocationHandler { private static final ByteBuffer VALIDATION_BUFFER = ByteBuffer.allocate(0); private static final String BODY_TOO_LARGE = "Request body emitted %d bytes, more than the expected %d bytes."; private static final String BODY_TOO_SMALL = "Request body emitted %d bytes, less tha...
What does it do? 1GB is quite high threshold .
private void subscribeToData() { this.data .onBackpressureBuffer(Constants.GB) .subscribe( byteBuffer -> { this.buffer = new ByteArrayInputStream(FluxUtil.byteBufferToArray(byteBuffer)); lock.lock(); try { this.waitingForData = false; dataAvailable.signal(); } finally { lock.unlock(); } }, throwable -> { if (throwable ...
.onBackpressureBuffer(Constants.GB)
private void subscribeToData() { this.data .onBackpressureBuffer() .subscribe( byteBuffer -> { this.buffer = new ByteArrayInputStream(FluxUtil.byteBufferToArray(byteBuffer)); lock.lock(); try { this.waitingForData = false; dataAvailable.signal(); } finally { lock.unlock(); } }, throwable -> { if (throwable instanceof I...
class FluxInputStream extends InputStream { private ClientLogger logger = new ClientLogger(FluxInputStream.class); private Flux<ByteBuffer> data; private Subscription subscription; private ByteArrayInputStream buffer; private boolean subscribed; private boolean fluxComplete; private boolean waitingForData; /* The follo...
class FluxInputStream extends InputStream { private ClientLogger logger = new ClientLogger(FluxInputStream.class); private Flux<ByteBuffer> data; private Subscription subscription; private ByteArrayInputStream buffer; private boolean subscribed; private boolean fluxComplete; private boolean waitingForData; /* The follo...
Would be better to validate the error message as well as that is what we will use to debug issues. ```java StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "4"))) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof UnexpectedLengthExcep...
public void unexpectedBodyLength() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http: .setBody(EXPECTED); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "4"))) .verifyError(UnexpectedLengthException.class); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Len...
.verifyError(UnexpectedLengthException.class);
public void unexpectedBodyLength() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http: .setBody(EXPECTED); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "4"))) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof UnexpectedLengthException); assertEquals("Reque...
class RestProxyTests { private static final byte[] EXPECTED = new byte[] { 0, 1, 2, 3, 4 }; @Test public void emptyRequestBody() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http: StepVerifier.create(RestProxy.validateLength(httpRequest)) .verifyComplete(); } @Test public void expectedBodyLength() { Htt...
class RestProxyTests { private static final byte[] EXPECTED = new byte[]{0, 1, 2, 3, 4}; @Test public void emptyRequestBody() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http: StepVerifier.create(RestProxy.validateLength(httpRequest)) .verifyComplete(); } @Test public void expectedBodyLength() { HttpRe...
Added
public void unexpectedBodyLength() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http: .setBody(EXPECTED); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "4"))) .verifyError(UnexpectedLengthException.class); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Len...
.verifyError(UnexpectedLengthException.class);
public void unexpectedBodyLength() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http: .setBody(EXPECTED); StepVerifier.create(collectRequest(httpRequest.setHeader("Content-Length", "4"))) .verifyErrorSatisfies(throwable -> { assertTrue(throwable instanceof UnexpectedLengthException); assertEquals("Reque...
class RestProxyTests { private static final byte[] EXPECTED = new byte[] { 0, 1, 2, 3, 4 }; @Test public void emptyRequestBody() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http: StepVerifier.create(RestProxy.validateLength(httpRequest)) .verifyComplete(); } @Test public void expectedBodyLength() { Htt...
class RestProxyTests { private static final byte[] EXPECTED = new byte[]{0, 1, 2, 3, 4}; @Test public void emptyRequestBody() { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http: StepVerifier.create(RestProxy.validateLength(httpRequest)) .verifyComplete(); } @Test public void expectedBodyLength() { HttpRe...
Please randomize at least part of it (I think Tanyi used the `randomeResourceName` for this purpose. May worth put to Util class if needed in more places).
public static boolean runSample(Azure azure) { final String linuxVMName = azure.sdkContext().randomResourceName("VM1", 15); final String rgName = azure.sdkContext().randomResourceName("rgCOMV", 15); final String userName = "tirekicker"; final String password = "12NewPA$$w0rd!"; final Region region = Region.US_WEST; try...
final String password = "12NewPA$$w0rd!";
public static boolean runSample(Azure azure) { final String linuxVMName = azure.sdkContext().randomResourceName("VM1", 15); final String rgName = azure.sdkContext().randomResourceName("rgCOMV", 15); final String userName = "tirekicker"; final String password = "12NewPA$$w0rd!"; final Region region = Region.US_WEST; try...
class ConvertVirtualMachineToManagedDisks { /** * Main function which runs the actual sample. * * @param azure 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 = ne...
class ConvertVirtualMachineToManagedDisks { /** * Main function which runs the actual sample. * * @param azure 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 = ne...
Here https://github.com/Azure/azure-libraries-for-java/pull/863/files. Could add to utils if needed.
public static boolean runSample(Azure azure) { final String linuxVMName = azure.sdkContext().randomResourceName("VM1", 15); final String rgName = azure.sdkContext().randomResourceName("rgCOMV", 15); final String userName = "tirekicker"; final String password = "12NewPA$$w0rd!"; final Region region = Region.US_WEST; try...
final String password = "12NewPA$$w0rd!";
public static boolean runSample(Azure azure) { final String linuxVMName = azure.sdkContext().randomResourceName("VM1", 15); final String rgName = azure.sdkContext().randomResourceName("rgCOMV", 15); final String userName = "tirekicker"; final String password = "12NewPA$$w0rd!"; final Region region = Region.US_WEST; try...
class ConvertVirtualMachineToManagedDisks { /** * Main function which runs the actual sample. * * @param azure 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 = ne...
class ConvertVirtualMachineToManagedDisks { /** * Main function which runs the actual sample. * * @param azure 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 = ne...
This is in case downstream is slower for some reason than the actual upstream flow of data. We dont want to drop any bytebuffers so I think this is the way we tell Reactor don't drop anything. Perhaps the default onBackpressureBuffer() may be more appropriate here than setting it to a GB
private void subscribeToData() { this.data .onBackpressureBuffer(Constants.GB) .subscribe( byteBuffer -> { this.buffer = new ByteArrayInputStream(FluxUtil.byteBufferToArray(byteBuffer)); lock.lock(); try { this.waitingForData = false; dataAvailable.signal(); } finally { lock.unlock(); } }, throwable -> { if (throwable ...
.onBackpressureBuffer(Constants.GB)
private void subscribeToData() { this.data .onBackpressureBuffer() .subscribe( byteBuffer -> { this.buffer = new ByteArrayInputStream(FluxUtil.byteBufferToArray(byteBuffer)); lock.lock(); try { this.waitingForData = false; dataAvailable.signal(); } finally { lock.unlock(); } }, throwable -> { if (throwable instanceof I...
class FluxInputStream extends InputStream { private ClientLogger logger = new ClientLogger(FluxInputStream.class); private Flux<ByteBuffer> data; private Subscription subscription; private ByteArrayInputStream buffer; private boolean subscribed; private boolean fluxComplete; private boolean waitingForData; /* The follo...
class FluxInputStream extends InputStream { private ClientLogger logger = new ClientLogger(FluxInputStream.class); private Flux<ByteBuffer> data; private Subscription subscription; private ByteArrayInputStream buffer; private boolean subscribed; private boolean fluxComplete; private boolean waitingForData; /* The follo...