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
We can set PARTITION_KEY and AzureHeaders.PARTITION_KEY with different values from SESSION_ID, and test the if converted header is as expected.
public void testServiceBusMessageHeadersSet() { Instant scheduledEnqueueInstant = Instant.now().plusSeconds(5); final OffsetDateTime scheduledEnqueueOffsetDateTime = OffsetDateTime .ofInstant(scheduledEnqueueInstant, systemDefault()) .toInstant() .atOffset(ZoneOffset.UTC); String customHeader = "custom-header"; String customHeaderValue = "custom-header-value"; Message<String> springMessage = springMessageBuilder().setHeader(PARTITION_KEY, SERVICE_BUS_SESSION_ID) .setHeader(customHeader, customHeaderValue) .setHeader(SCHEDULED_ENQUEUE_TIME, scheduledEnqueueInstant) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); Map<String, Object> applicationProperties = serviceBusMessage.getApplicationProperties(); assertNotNull(serviceBusMessage); assertNotNull(applicationProperties); assertTrue(applicationProperties.containsValue(springMessage.getHeaders().getTimestamp().toString())); assertEquals(customHeaderValue, applicationProperties.get(customHeader)); assertNull(applicationProperties.get(AzureHeaders.RAW_ID)); assertServiceBusMessageHeaders(scheduledEnqueueOffsetDateTime, serviceBusMessage); }
Message<String> springMessage = springMessageBuilder().setHeader(PARTITION_KEY, SERVICE_BUS_SESSION_ID)
public void testServiceBusMessageHeadersSet() { Instant scheduledEnqueueInstant = Instant.now().plusSeconds(5); final OffsetDateTime scheduledEnqueueOffsetDateTime = OffsetDateTime .ofInstant(scheduledEnqueueInstant, systemDefault()) .toInstant() .atOffset(ZoneOffset.UTC); String customHeader = "custom-header"; String customHeaderValue = "custom-header-value"; Message<String> springMessage = springMessageBuilder().setHeader(ServiceBusMessageHeaders.PARTITION_KEY, SERVICE_BUS_SESSION_ID) .setHeader(customHeader, customHeaderValue) .setHeader(SCHEDULED_ENQUEUE_TIME, scheduledEnqueueInstant) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); Map<String, Object> applicationProperties = serviceBusMessage.getApplicationProperties(); assertNotNull(serviceBusMessage); assertNotNull(applicationProperties); assertTrue(applicationProperties.containsValue(springMessage.getHeaders().getTimestamp().toString())); assertEquals(customHeaderValue, applicationProperties.get(customHeader)); assertNull(applicationProperties.get(AzureHeaders.RAW_ID)); assertServiceBusMessageHeaders(scheduledEnqueueOffsetDateTime, serviceBusMessage); }
class ServiceBusMessageConverterTest { private static final String PAYLOAD = "payload"; private static final String APPLICATION_JSON = "application/json"; private static final String REPLY_TO = "my-reply-to"; private static final String AZURE_MESSAGE_RAW_ID = "raw-id"; private static final String SERVICE_BUS_MESSAGE_ID = "message-id"; private static final String SERVICE_BUS_SESSION_ID = "session-id"; private static final String PARTITION_KEY = "partition-key"; private static final String SERVICE_BUS_CORRELATION_ID = "correlation-id"; private static final String SERVICE_BUS_TO = "to"; private static final String SERVICE_BUS_REPLY_TO_SESSION_ID = "reply-to-session-id"; private static final String SERVICE_BUS_PARTITION_KEY = SERVICE_BUS_REPLY_TO_SESSION_ID; private static final String SERVICE_BUS_VIA_PARTITION_KEY = "via-partition-key"; private static final Duration SERVICE_BUS_TTL = Duration.ofSeconds(1234); private final ServiceBusMessageConverter messageConverter = new ServiceBusMessageConverter(); @Mock private ServiceBusReceivedMessage receivedMessage; private AutoCloseable closeable; @BeforeEach public void setup() { this.closeable = MockitoAnnotations.openMocks(this); when(this.receivedMessage.getBody()).thenReturn(BinaryData.fromString(PAYLOAD)); } @AfterEach public void close() throws Exception { closeable.close(); } @Test public void shouldRaiseIllegalArgExceptionIfPayloadNull() { when(this.receivedMessage.getBody()).thenReturn(null); assertThrows(IllegalArgumentException.class, () -> this.messageConverter.toMessage(this.receivedMessage, byte[].class)); } @Test public void fromPayloadAsByte() { final Message<byte[]> message = MessageBuilder.withPayload(PAYLOAD.getBytes(StandardCharsets.UTF_8)).build(); final ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(message, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertArrayEquals(PAYLOAD.getBytes(), serviceBusMessage.getBody().toBytes()); } @Test public void fromPayloadAsString() { final Message<String> message = MessageBuilder.withPayload(PAYLOAD).build(); final ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(message, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertEquals(PAYLOAD, serviceBusMessage.getBody().toString()); } @Test public void fromPayloadAsUserClass() { final User user = new User(PAYLOAD); final Message<User> message = MessageBuilder.withPayload(user).build(); final ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(message, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertEquals(PAYLOAD, serviceBusMessage.getBody().toObject(User.class).getName()); } @Test public void toPayloadAsByte() { Message<byte[]> message = this.messageConverter.toMessage(receivedMessage, byte[].class); assertNotNull(message); assertArrayEquals(PAYLOAD.getBytes(), message.getPayload()); } @Test public void toPayloadAsString() { Message<String> message = this.messageConverter.toMessage(receivedMessage, String.class); assertNotNull(message); assertEquals(PAYLOAD, message.getPayload()); } @Test public void toPayloadAsUserClass() { final User user = new User(PAYLOAD); when(this.receivedMessage.getBody()).thenReturn(BinaryData.fromObject(user)); Message<User> message = this.messageConverter.toMessage(receivedMessage, User.class); assertNotNull(message); assertEquals(PAYLOAD, message.getPayload().getName()); } @Test public void testScheduledEnqueueTimeHeader() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .build(); ServiceBusMessage servicebusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertNotNull(servicebusMessage); assertNull(servicebusMessage.getScheduledEnqueueTime()); springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(SCHEDULED_ENQUEUE_MESSAGE, 5000) .build(); servicebusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertNotNull(servicebusMessage); assertNotNull(servicebusMessage.getScheduledEnqueueTime()); } @Test public void testConvertSpringNativeMessageHeaders() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(MessageHeaders.CONTENT_TYPE, APPLICATION_JSON) .setHeader(MessageHeaders.REPLY_CHANNEL, REPLY_TO) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertEquals(APPLICATION_JSON, serviceBusMessage.getContentType()); assertEquals(REPLY_TO, serviceBusMessage.getReplyTo()); when(this.receivedMessage.getBody()).thenReturn(BinaryData.fromString(PAYLOAD)); when(this.receivedMessage.getContentType()).thenReturn(APPLICATION_JSON); when(this.receivedMessage.getReplyTo()).thenReturn(REPLY_TO); Message<String> convertedSpringMessage = this.messageConverter.toMessage(this.receivedMessage, String.class); assertNotNull(convertedSpringMessage); assertEquals(APPLICATION_JSON, convertedSpringMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE)); assertEquals(REPLY_TO, convertedSpringMessage.getHeaders().get(MessageHeaders.REPLY_CHANNEL)); } @Test public void testAzureMessageHeader() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(AzureHeaders.RAW_ID, AZURE_MESSAGE_RAW_ID) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertEquals(AZURE_MESSAGE_RAW_ID, serviceBusMessage.getMessageId()); when(this.receivedMessage.getMessageId()).thenReturn(AZURE_MESSAGE_RAW_ID); Message<String> convertedSpringMessage = this.messageConverter.toMessage(this.receivedMessage, String.class); assertNotNull(convertedSpringMessage); assertEquals(AZURE_MESSAGE_RAW_ID, convertedSpringMessage.getHeaders().get(AzureHeaders.RAW_ID)); } private MessageBuilder<String> springMessageBuilder() { return MessageBuilder.withPayload(PAYLOAD) .setHeader(AzureHeaders.RAW_ID, AZURE_MESSAGE_RAW_ID) .setHeader(MESSAGE_ID, SERVICE_BUS_MESSAGE_ID) .setHeader(TIME_TO_LIVE, SERVICE_BUS_TTL) .setHeader(SESSION_ID, SERVICE_BUS_SESSION_ID) .setHeader(CORRELATION_ID, SERVICE_BUS_CORRELATION_ID) .setHeader(TO, SERVICE_BUS_TO) .setHeader(REPLY_TO_SESSION_ID, SERVICE_BUS_REPLY_TO_SESSION_ID); } private void assertServiceBusMessageHeaders(OffsetDateTime scheduledEnqueueOffsetDateTime, ServiceBusMessage serviceBusMessage) { assertEquals(SERVICE_BUS_MESSAGE_ID, serviceBusMessage.getMessageId()); assertEquals(SERVICE_BUS_TTL, serviceBusMessage.getTimeToLive()); assertEquals(scheduledEnqueueOffsetDateTime, serviceBusMessage.getScheduledEnqueueTime()); assertEquals(SERVICE_BUS_SESSION_ID, serviceBusMessage.getSessionId()); assertEquals(SERVICE_BUS_CORRELATION_ID, serviceBusMessage.getCorrelationId()); assertEquals(SERVICE_BUS_TO, serviceBusMessage.getTo()); assertEquals(SERVICE_BUS_REPLY_TO_SESSION_ID, serviceBusMessage.getReplyToSessionId()); assertEquals(SERVICE_BUS_SESSION_ID, serviceBusMessage.getPartitionKey()); } @Test @Test public void testTransformationPartitionKeyDifferentFromSessionId() { Instant scheduledEnqueueInstant = Instant.now().plusSeconds(5); final OffsetDateTime scheduledEnqueueOffsetDateTime = OffsetDateTime .ofInstant(scheduledEnqueueInstant, systemDefault()) .toInstant() .atOffset(ZoneOffset.UTC); String customHeader = "custom-header"; String customHeaderValue = "custom-header-value"; Message<String> springMessage = springMessageBuilder().setHeader(PARTITION_KEY, PARTITION_KEY) .setHeader(customHeader, customHeaderValue) .setHeader(SCHEDULED_ENQUEUE_TIME, scheduledEnqueueInstant) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); Map<String, Object> applicationProperties = serviceBusMessage.getApplicationProperties(); assertNotNull(serviceBusMessage); assertNotNull(applicationProperties); assertTrue(applicationProperties.containsValue(springMessage.getHeaders().getTimestamp().toString())); assertEquals(customHeaderValue, applicationProperties.get(customHeader)); assertNull(applicationProperties.get(AzureHeaders.RAW_ID)); assertServiceBusMessageHeaders(scheduledEnqueueOffsetDateTime, serviceBusMessage); } @Test public void testServiceBusMessageHeadersRead() { OffsetDateTime serviceBusScheduledEnqueueTime = OffsetDateTime.ofInstant(Instant.now(), systemDefault()); when(this.receivedMessage.getMessageId()).thenReturn(SERVICE_BUS_MESSAGE_ID); when(this.receivedMessage.getTimeToLive()).thenReturn(SERVICE_BUS_TTL); when(this.receivedMessage.getScheduledEnqueueTime()).thenReturn(serviceBusScheduledEnqueueTime); when(this.receivedMessage.getSessionId()).thenReturn(SERVICE_BUS_SESSION_ID); when(this.receivedMessage.getCorrelationId()).thenReturn(SERVICE_BUS_CORRELATION_ID); when(this.receivedMessage.getTo()).thenReturn(SERVICE_BUS_TO); when(this.receivedMessage.getReplyToSessionId()).thenReturn(SERVICE_BUS_REPLY_TO_SESSION_ID); when(this.receivedMessage.getPartitionKey()).thenReturn(SERVICE_BUS_PARTITION_KEY); when(this.receivedMessage.getApplicationProperties()).thenReturn(new HashMap<String, Object>() { { put(TIME_TO_LIVE, SERVICE_BUS_TTL.toString()); } }); Message<String> springMessage = this.messageConverter.toMessage(this.receivedMessage, String.class); assertNotNull(springMessage); assertEquals(SERVICE_BUS_MESSAGE_ID, springMessage.getHeaders().get(AzureHeaders.RAW_ID)); assertEquals(SERVICE_BUS_MESSAGE_ID, springMessage.getHeaders().get(MESSAGE_ID)); assertEquals(SERVICE_BUS_TTL, springMessage.getHeaders().get(TIME_TO_LIVE)); assertEquals(serviceBusScheduledEnqueueTime, springMessage.getHeaders().get(SCHEDULED_ENQUEUE_TIME)); assertEquals(SERVICE_BUS_SESSION_ID, springMessage.getHeaders().get(SESSION_ID)); assertEquals(SERVICE_BUS_CORRELATION_ID, springMessage.getHeaders().get(CORRELATION_ID)); assertEquals(SERVICE_BUS_TO, springMessage.getHeaders().get(TO)); assertEquals(SERVICE_BUS_REPLY_TO_SESSION_ID, springMessage.getHeaders().get(REPLY_TO_SESSION_ID)); assertEquals(SERVICE_BUS_PARTITION_KEY, springMessage.getHeaders().get(ServiceBusMessageHeaders.PARTITION_KEY)); } }
class ServiceBusMessageConverterTest { private static final String PAYLOAD = "payload"; private static final String APPLICATION_JSON = "application/json"; private static final String REPLY_TO = "my-reply-to"; private static final String AZURE_MESSAGE_RAW_ID = "raw-id"; private static final String SERVICE_BUS_MESSAGE_ID = "message-id"; private static final String SERVICE_BUS_SESSION_ID = "session-id"; private static final String SERVICE_BUS_MESSAGE_HEADER_PARTITION_KEY = "service-bus-message-header-partition-key"; private static final String AZURE_HEADER_PARTITION_KEY = "azure_header-partition-key"; private static final String SERVICE_BUS_CORRELATION_ID = "correlation-id"; private static final String SERVICE_BUS_TO = "to"; private static final String SERVICE_BUS_REPLY_TO_SESSION_ID = "reply-to-session-id"; private static final String SERVICE_BUS_PARTITION_KEY = SERVICE_BUS_REPLY_TO_SESSION_ID; private static final String SERVICE_BUS_VIA_PARTITION_KEY = "via-partition-key"; private static final Duration SERVICE_BUS_TTL = Duration.ofSeconds(1234); private final ServiceBusMessageConverter messageConverter = new ServiceBusMessageConverter(); @Mock private ServiceBusReceivedMessage receivedMessage; private AutoCloseable closeable; @BeforeEach public void setup() { this.closeable = MockitoAnnotations.openMocks(this); when(this.receivedMessage.getBody()).thenReturn(BinaryData.fromString(PAYLOAD)); } @AfterEach public void close() throws Exception { closeable.close(); } @Test public void shouldRaiseIllegalArgExceptionIfPayloadNull() { when(this.receivedMessage.getBody()).thenReturn(null); assertThrows(IllegalArgumentException.class, () -> this.messageConverter.toMessage(this.receivedMessage, byte[].class)); } @Test public void fromPayloadAsByte() { final Message<byte[]> message = MessageBuilder.withPayload(PAYLOAD.getBytes(StandardCharsets.UTF_8)).build(); final ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(message, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertArrayEquals(PAYLOAD.getBytes(), serviceBusMessage.getBody().toBytes()); } @Test public void fromPayloadAsString() { final Message<String> message = MessageBuilder.withPayload(PAYLOAD).build(); final ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(message, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertEquals(PAYLOAD, serviceBusMessage.getBody().toString()); } @Test public void fromPayloadAsUserClass() { final User user = new User(PAYLOAD); final Message<User> message = MessageBuilder.withPayload(user).build(); final ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(message, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertEquals(PAYLOAD, serviceBusMessage.getBody().toObject(User.class).getName()); } @Test public void toPayloadAsByte() { Message<byte[]> message = this.messageConverter.toMessage(receivedMessage, byte[].class); assertNotNull(message); assertArrayEquals(PAYLOAD.getBytes(), message.getPayload()); } @Test public void toPayloadAsString() { Message<String> message = this.messageConverter.toMessage(receivedMessage, String.class); assertNotNull(message); assertEquals(PAYLOAD, message.getPayload()); } @Test public void toPayloadAsUserClass() { final User user = new User(PAYLOAD); when(this.receivedMessage.getBody()).thenReturn(BinaryData.fromObject(user)); Message<User> message = this.messageConverter.toMessage(receivedMessage, User.class); assertNotNull(message); assertEquals(PAYLOAD, message.getPayload().getName()); } @Test public void testScheduledEnqueueTimeHeader() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .build(); ServiceBusMessage servicebusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertNotNull(servicebusMessage); assertNull(servicebusMessage.getScheduledEnqueueTime()); springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(SCHEDULED_ENQUEUE_MESSAGE, 5000) .build(); servicebusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertNotNull(servicebusMessage); assertNotNull(servicebusMessage.getScheduledEnqueueTime()); } @Test public void testConvertSpringNativeMessageHeaders() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(MessageHeaders.CONTENT_TYPE, APPLICATION_JSON) .setHeader(MessageHeaders.REPLY_CHANNEL, REPLY_TO) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertEquals(APPLICATION_JSON, serviceBusMessage.getContentType()); assertEquals(REPLY_TO, serviceBusMessage.getReplyTo()); when(this.receivedMessage.getBody()).thenReturn(BinaryData.fromString(PAYLOAD)); when(this.receivedMessage.getContentType()).thenReturn(APPLICATION_JSON); when(this.receivedMessage.getReplyTo()).thenReturn(REPLY_TO); Message<String> convertedSpringMessage = this.messageConverter.toMessage(this.receivedMessage, String.class); assertNotNull(convertedSpringMessage); assertEquals(APPLICATION_JSON, convertedSpringMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE)); assertEquals(REPLY_TO, convertedSpringMessage.getHeaders().get(MessageHeaders.REPLY_CHANNEL)); } @Test public void testAzureMessageHeader() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(AzureHeaders.RAW_ID, AZURE_MESSAGE_RAW_ID) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertNotNull(serviceBusMessage); assertEquals(AZURE_MESSAGE_RAW_ID, serviceBusMessage.getMessageId()); when(this.receivedMessage.getMessageId()).thenReturn(AZURE_MESSAGE_RAW_ID); Message<String> convertedSpringMessage = this.messageConverter.toMessage(this.receivedMessage, String.class); assertNotNull(convertedSpringMessage); assertEquals(AZURE_MESSAGE_RAW_ID, convertedSpringMessage.getHeaders().get(AzureHeaders.RAW_ID)); } private MessageBuilder<String> springMessageBuilder() { return MessageBuilder.withPayload(PAYLOAD) .setHeader(AzureHeaders.RAW_ID, AZURE_MESSAGE_RAW_ID) .setHeader(MESSAGE_ID, SERVICE_BUS_MESSAGE_ID) .setHeader(TIME_TO_LIVE, SERVICE_BUS_TTL) .setHeader(SESSION_ID, SERVICE_BUS_SESSION_ID) .setHeader(CORRELATION_ID, SERVICE_BUS_CORRELATION_ID) .setHeader(TO, SERVICE_BUS_TO) .setHeader(REPLY_TO_SESSION_ID, SERVICE_BUS_REPLY_TO_SESSION_ID); } private void assertServiceBusMessageHeaders(OffsetDateTime scheduledEnqueueOffsetDateTime, ServiceBusMessage serviceBusMessage) { assertEquals(SERVICE_BUS_MESSAGE_ID, serviceBusMessage.getMessageId()); assertEquals(SERVICE_BUS_TTL, serviceBusMessage.getTimeToLive()); assertEquals(scheduledEnqueueOffsetDateTime, serviceBusMessage.getScheduledEnqueueTime()); assertEquals(SERVICE_BUS_SESSION_ID, serviceBusMessage.getSessionId()); assertEquals(SERVICE_BUS_CORRELATION_ID, serviceBusMessage.getCorrelationId()); assertEquals(SERVICE_BUS_TO, serviceBusMessage.getTo()); assertEquals(SERVICE_BUS_REPLY_TO_SESSION_ID, serviceBusMessage.getReplyToSessionId()); assertEquals(SERVICE_BUS_SESSION_ID, serviceBusMessage.getPartitionKey()); } @Test @Test public void testServiceBusHeaderAndSssionIdPriority() { Message<String> springMessage = springMessageBuilder().setHeader(ServiceBusMessageHeaders.PARTITION_KEY, SERVICE_BUS_MESSAGE_HEADER_PARTITION_KEY) .setHeader(SESSION_ID, SERVICE_BUS_SESSION_ID) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertEquals(SERVICE_BUS_SESSION_ID, serviceBusMessage.getPartitionKey()); } @Test public void testAzureHeaderAndServiceBusHeaderAndSessionIdSetSameTime() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(ServiceBusMessageHeaders.PARTITION_KEY, SERVICE_BUS_MESSAGE_HEADER_PARTITION_KEY) .setHeader(AzureHeaders.PARTITION_KEY, AZURE_HEADER_PARTITION_KEY) .setHeader(SESSION_ID, SERVICE_BUS_SESSION_ID) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertEquals(SERVICE_BUS_SESSION_ID, serviceBusMessage.getPartitionKey()); } @Test public void testAzureHeaderAndServiceBusHeaderPriority() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(ServiceBusMessageHeaders.PARTITION_KEY, SERVICE_BUS_MESSAGE_HEADER_PARTITION_KEY) .setHeader(AzureHeaders.PARTITION_KEY, AZURE_HEADER_PARTITION_KEY) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertEquals(SERVICE_BUS_MESSAGE_HEADER_PARTITION_KEY, serviceBusMessage.getPartitionKey()); } @Test public void testAzureHeaderAndSessionIdPriority() { Message<String> springMessage = MessageBuilder.withPayload(PAYLOAD) .setHeader(AzureHeaders.PARTITION_KEY, AZURE_HEADER_PARTITION_KEY) .setHeader(SESSION_ID, SERVICE_BUS_SESSION_ID) .build(); ServiceBusMessage serviceBusMessage = this.messageConverter.fromMessage(springMessage, ServiceBusMessage.class); assertEquals(SERVICE_BUS_SESSION_ID, serviceBusMessage.getPartitionKey()); } @Test public void testServiceBusMessageHeadersRead() { OffsetDateTime serviceBusScheduledEnqueueTime = OffsetDateTime.ofInstant(Instant.now(), systemDefault()); when(this.receivedMessage.getMessageId()).thenReturn(SERVICE_BUS_MESSAGE_ID); when(this.receivedMessage.getTimeToLive()).thenReturn(SERVICE_BUS_TTL); when(this.receivedMessage.getScheduledEnqueueTime()).thenReturn(serviceBusScheduledEnqueueTime); when(this.receivedMessage.getSessionId()).thenReturn(SERVICE_BUS_SESSION_ID); when(this.receivedMessage.getCorrelationId()).thenReturn(SERVICE_BUS_CORRELATION_ID); when(this.receivedMessage.getTo()).thenReturn(SERVICE_BUS_TO); when(this.receivedMessage.getReplyToSessionId()).thenReturn(SERVICE_BUS_REPLY_TO_SESSION_ID); when(this.receivedMessage.getPartitionKey()).thenReturn(SERVICE_BUS_PARTITION_KEY); when(this.receivedMessage.getApplicationProperties()).thenReturn(new HashMap<String, Object>() { { put(TIME_TO_LIVE, SERVICE_BUS_TTL.toString()); } }); Message<String> springMessage = this.messageConverter.toMessage(this.receivedMessage, String.class); assertNotNull(springMessage); assertEquals(SERVICE_BUS_MESSAGE_ID, springMessage.getHeaders().get(AzureHeaders.RAW_ID)); assertEquals(SERVICE_BUS_MESSAGE_ID, springMessage.getHeaders().get(MESSAGE_ID)); assertEquals(SERVICE_BUS_TTL, springMessage.getHeaders().get(TIME_TO_LIVE)); assertEquals(serviceBusScheduledEnqueueTime, springMessage.getHeaders().get(SCHEDULED_ENQUEUE_TIME)); assertEquals(SERVICE_BUS_SESSION_ID, springMessage.getHeaders().get(SESSION_ID)); assertEquals(SERVICE_BUS_CORRELATION_ID, springMessage.getHeaders().get(CORRELATION_ID)); assertEquals(SERVICE_BUS_TO, springMessage.getHeaders().get(TO)); assertEquals(SERVICE_BUS_REPLY_TO_SESSION_ID, springMessage.getHeaders().get(REPLY_TO_SESSION_ID)); assertEquals(SERVICE_BUS_PARTITION_KEY, springMessage.getHeaders().get(ServiceBusMessageHeaders.PARTITION_KEY)); } }
This is missing a default #Resolved
public void run() { switch(mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; } }
case GENERATE_MODE: generate();
public void run() { switch (mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; default: logger.error("Unknown value for mode: {}", mode); break; } }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scan() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scan() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
If any of the arguments are missing will the application fail to run? If so, I'd revert back to having all parameters being required in the constructor. #Resolved
private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); }
switch (argName.toLowerCase()) {
private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNull(generator.getInputFileName(), "inputFileName"); validateNull(generator.getOutputFileName(), "outputFileName"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } } }
Given the overall changes to support both analyzing and generating separately, should `BomGenerator` become an abstract parent class with sub-classes used for analyzing and generating separately? Each could be `Runnable`s which validate their configuration on run to either proceed or error out on missing parameters. #Pending
public void run() { switch(mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; } }
case ANALYZE_MODE: validate();
public void run() { switch (mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; default: logger.error("Unknown value for mode: {}", mode); break; } }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scan() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scan() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
Could these just be ignored instead of erroring? #Resolved
private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNull(generator.getInputFileName(), "inputFileName"); validateNull(generator.getOutputFileName(), "outputFileName"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } }
validateNull(generator.getOutputFileName(), "outputFileName");
private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); } }
This could be null, should this be validated before entering the switch case? #Resolved
private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNull(generator.getInputFileName(), "inputFileName"); validateNull(generator.getOutputFileName(), "outputFileName"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } }
switch (generator.getMode()) {
private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); } }
No, mode is an optional parameter. And in the next iteration, I intend to add another optional one.
private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); }
switch (argName.toLowerCase()) {
private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNull(generator.getInputFileName(), "inputFileName"); validateNull(generator.getOutputFileName(), "outputFileName"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } } }
I expect there to be more tweaks needed in the next couple or so weeks and once we have that will redesign things.
public void run() { switch(mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; } }
case ANALYZE_MODE: validate();
public void run() { switch (mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; default: logger.error("Unknown value for mode: {}", mode); break; } }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scan() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scan() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
Same as before.
static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); }
logger.error("Failed to read the contents of the pom file: {}", fileName);
static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, expectedValues)); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, Arrays.toString(expectedValues))); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
It can't be null. There is a default value for the mode.
private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNull(generator.getInputFileName(), "inputFileName"); validateNull(generator.getOutputFileName(), "outputFileName"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } }
switch (generator.getMode()) {
private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); } }
Sure, changing it :).
private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNull(generator.getInputFileName(), "inputFileName"); validateNull(generator.getOutputFileName(), "outputFileName"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } }
validateNull(generator.getOutputFileName(), "outputFileName");
private static void validateOptions(BomGenerator generator) { switch (generator.getMode()) { case ANALYZE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); break; case GENERATE_MODE: validateNotNullOrEmpty(generator.getPomFileName(), "pomFile"); validateNotNullOrEmpty(generator.getInputFileName(), "inputFileName"); validateNotNullOrEmpty(generator.getOutputFileName(), "outputFileName"); break; } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); } }
class Main { public static void main(String[] args) { BomGenerator generator = new BomGenerator(); parseCommandLine(args, generator); generator.run(); } private static void parseCommandLine(String[] args, BomGenerator generator) { for (String arg : args) { Matcher matcher = Utils.COMMANDLINE_REGEX.matcher(arg); if (matcher.matches()) { if (matcher.groupCount() == 2) { String argName = matcher.group(1); String argValue = matcher.group(2); switch (argName.toLowerCase()) { case COMMANDLINE_INPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setInputFileName(argValue); break; case COMMANDLINE_OUTPUTFILE: validateNotNullOrEmpty(argName, argValue); generator.setOutputFileName(argValue); break; case COMMANDLINE_POMFILE: validateNotNullOrEmpty(argName, argValue); generator.setPomFileName(argValue); break; case COMMANDLINE_MODE: validateNotNullOrEmpty(argName, argValue); validateValues(argName, argValue, GENERATE_MODE, ANALYZE_MODE); generator.setMode(argValue); break; } } } } validateOptions(generator); } }
nit: `String.format("%s", array)` will print the first value in the array. It won't print all the values in the array. Given the error message here, I am assuming that this is intended to print all expected values. #Resolved
static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, expectedValues)); } }
throw new IllegalArgumentException(String.format("%s must match %s", argName, expectedValues));
static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, Arrays.toString(expectedValues))); } }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
If we cannot read the response, should we just abort the BOM generation? Can we proceed to generate a valid BOM without this dependency? #Resolved
static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); }
logger.error("Failed to read contents for {}", dependency.toString());
static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, expectedValues)); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, Arrays.toString(expectedValues))); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
Same here - we should throw an exception and not continue with generating the BOM. #Resolved
static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); }
logger.error("Failed to read the contents of the pom file: {}", fileName);
static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, expectedValues)); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, Arrays.toString(expectedValues))); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
We can generate the right BOM - we may just not be able to recognize that an external dependency is getting resolved by an external BOM we have added. The tool, takes the stance of generating the report with/without errors. So, I do not stop the analysis in case of any errors.
static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); }
logger.error("Failed to read contents for {}", dependency.toString());
static List<BomDependency> getPomFileContent(Dependency dependency) { String[] groups = STRING_SPLIT_BY_DOT.split(dependency.getGroupId()); String url = null; if(groups.length == 2) { url = "https: } else if (groups.length == 3) { url = "https: } else { throw new UnsupportedOperationException("Can't parse the external BOM file."); } HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .header("accept", "application/xml") .timeout(Duration.ofMillis(5000)) .build(); return HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if(response.statusCode() == 200) { try (InputStreamReader reader = new InputStreamReader(response.body())) { return Utils.parsePomFileContent(reader); } catch (IOException ex) { logger.error("Failed to read contents for {}", dependency.toString()); } } return null; }).join(); }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, expectedValues)); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
class Utils { public static final String COMMANDLINE_INPUTFILE = "inputfile"; public static final String COMMANDLINE_OUTPUTFILE = "outputfile"; public static final String COMMANDLINE_POMFILE = "pomfile"; public static final String COMMANDLINE_MODE = "mode"; public static final String ANALYZE_MODE = "analyze"; public static final String GENERATE_MODE = "generate"; public static final String COMMANDLINE_EXTERNALDEPENDENCIES = "externalDependencies"; public static final String COMMANDLINE_GROUPID = "groupid"; public static final Pattern COMMANDLINE_REGEX = Pattern.compile("-(.*)=(.*)"); public static final List<String> EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-spring-data-cosmos-test", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); public static final Pattern STRING_SPLIT_BY_DOT = Pattern.compile("[.]"); public static final String PROJECT_VERSION = "project.version"; public static final HashSet<String> RESOLVED_EXCLUSION_LIST = new HashSet<>(Arrays.asList( "junit-jupiter-api" )); public static final HashSet<String> IGNORE_CONFLICT_LIST = new HashSet<>(Arrays.asList( "slf4j-api" )); public static final String POM_TYPE = "pom"; private static Logger logger = LoggerFactory.getLogger(Utils.class); static void validateNotNullOrEmpty(String argValue, String argName) { if(argValue == null || argValue.isEmpty()) { throw new NullPointerException(String.format("%s can't be null", argName)); } } static void validateNull(String argValue, String argName) { if(argValue != null) { throw new IllegalArgumentException(String.format("%s should be null", argName)); } } static void validateValues(String argName, String argValue, String ... expectedValues) { if(Arrays.stream(expectedValues).noneMatch(a -> a.equals(argValue))) { throw new IllegalArgumentException(String.format("%s must match %s", argName, Arrays.toString(expectedValues))); } } static List<BomDependency> getExternalDependenciesContent(List<Dependency> dependencies) { List<BomDependency> allResolvedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { List<BomDependency> resolvedDependencies = getPomFileContent(dependency); if (resolvedDependencies != null) { allResolvedDependencies.addAll(resolvedDependencies); } } return allResolvedDependencies; } static BomDependencyNoVersion toBomDependencyNoVersion(BomDependency bomDependency) { return new BomDependencyNoVersion(bomDependency.getGroupId(), bomDependency.getArtifactId()); } static List<BomDependency> parsePomFileContent(String fileName) { try (FileReader reader = new FileReader(fileName)) { return parsePomFileContent(reader); } catch (IOException exception) { logger.error("Failed to read the contents of the pom file: {}", fileName); } return new ArrayList<>(); } static List<BomDependency> parsePomFileContent(Reader responseStream) { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(responseStream); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().map(dep -> { String version = getPropertyName(dep.getVersion()); while(model.getProperties().getProperty(version) != null) { version = getPropertyName(model.getProperties().getProperty(version)); if(version.equals(PROJECT_VERSION)) { version = model.getVersion(); } } if(version == null) { version = dep.getVersion(); } BomDependency bomDependency = new BomDependency(dep.getGroupId(), dep.getArtifactId(), version); return bomDependency; }).collect(Collectors.toList()); } catch (IOException exception) { exception.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } return null; } private static String getPropertyName(String propertyValue) { if(propertyValue.startsWith("${")) { return propertyValue.substring(2, propertyValue.length() - 1); } return propertyValue; } }
I think find a `Registered` one is better (i think it could be registered). Otherwise when all providers are registered, the test can not test anything.
public void canListAndRegisterFeature() { List<Feature> features = resourceClient.features().list().stream().collect(Collectors.toList()); Assertions.assertNotNull(features); features.stream() .filter(f -> "NotRegistered".equals(f.state())) .findFirst() .ifPresent(feature -> resourceClient.features() .register(feature.resourceProviderName(), feature.featureName())); }
.register(feature.resourceProviderName(), feature.featureName()));
public void canListAndRegisterFeature() { List<Feature> features = resourceClient.features().list().stream().collect(Collectors.toList()); Assertions.assertNotNull(features); features.stream() .filter(f -> "NotRegistered".equals(f.state())) .findFirst() .ifPresent(feature -> resourceClient.features() .register(feature.resourceProviderName(), feature.featureName())); }
class FeaturesTests extends ResourceManagementTest { @Test }
class FeaturesTests extends ResourceManagementTest { @Test }
For now most feature is NotRegistered (and we got lots of them for this test to run, we can change that after we exhausted them). BTW, if I find Registered, I cannot call unregister on it as someone may depends on that feature.
public void canListAndRegisterFeature() { List<Feature> features = resourceClient.features().list().stream().collect(Collectors.toList()); Assertions.assertNotNull(features); features.stream() .filter(f -> "NotRegistered".equals(f.state())) .findFirst() .ifPresent(feature -> resourceClient.features() .register(feature.resourceProviderName(), feature.featureName())); }
.register(feature.resourceProviderName(), feature.featureName()));
public void canListAndRegisterFeature() { List<Feature> features = resourceClient.features().list().stream().collect(Collectors.toList()); Assertions.assertNotNull(features); features.stream() .filter(f -> "NotRegistered".equals(f.state())) .findFirst() .ifPresent(feature -> resourceClient.features() .register(feature.resourceProviderName(), feature.featureName())); }
class FeaturesTests extends ResourceManagementTest { @Test }
class FeaturesTests extends ResourceManagementTest { @Test }
nit: `input.length < 1` seems a bit cryptic, also array len can never be negative, I would do `input.length == 0` ```suggestion if (input == null || input.length == 0) { ```
public Mono<byte[]> decrypt(byte[] input) { if (input == null || input.length < 1) { return Mono.empty(); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypting byte[] of size [{}] on thread [{}]", input == null ? null : input.length, Thread.currentThread().getName()); } ObjectNode itemJObj = Utils.parse(input, ObjectNode.class); assert (itemJObj != null); return initEncryptionSettingsIfNotInitializedAsync().then(Mono.defer(() -> { for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { if (StringUtils.isEmpty(includedPath.getPath()) || includedPath.getPath().charAt(0) != '/' || includedPath.getPath().lastIndexOf('/') != 0) { return Mono.error(new IllegalArgumentException("Invalid encryption path: " + includedPath.getPath())); } } List<Mono<Void>> encryptionMonoList = new ArrayList<>(); for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { String propertyName = includedPath.getPath().substring(1); JsonNode propertyValueHolder = itemJObj.get(propertyName); if (propertyValueHolder != null && !propertyValueHolder.isNull()) { Mono<Void> voidMono = this.encryptionSettings.getEncryptionSettingForPropertyAsync(propertyName, this).flatMap(settings -> { try { decryptAndSerializeProperty(settings, itemJObj, propertyValueHolder, propertyName); } catch (MicrosoftDataEncryptionException | JsonProcessingException ex) { return Mono.error(ex); } catch (IOException e) { e.printStackTrace(); } return Mono.empty(); }); encryptionMonoList.add(voidMono); } } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionMonoList).collectList(); return listMono.flatMap(aVoid -> Mono.just(EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), itemJObj))); })); }
if (input == null || input.length < 1) {
public Mono<byte[]> decrypt(byte[] input) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypting byte[] of size [{}] on thread [{}]", input == null ? null : input.length, Thread.currentThread().getName()); } if (input == null || input.length == 0) { return Mono.empty(); } ObjectNode itemJObj = Utils.parse(input, ObjectNode.class); assert (itemJObj != null); return initEncryptionSettingsIfNotInitializedAsync().then(Mono.defer(() -> { for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { if (StringUtils.isEmpty(includedPath.getPath()) || includedPath.getPath().charAt(0) != '/' || includedPath.getPath().lastIndexOf('/') != 0) { return Mono.error(new IllegalArgumentException("Invalid encryption path: " + includedPath.getPath())); } } List<Mono<Void>> encryptionMonoList = new ArrayList<>(); for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { String propertyName = includedPath.getPath().substring(1); JsonNode propertyValueHolder = itemJObj.get(propertyName); if (propertyValueHolder != null && !propertyValueHolder.isNull()) { Mono<Void> voidMono = this.encryptionSettings.getEncryptionSettingForPropertyAsync(propertyName, this).flatMap(settings -> { try { decryptAndSerializeProperty(settings, itemJObj, propertyValueHolder, propertyName); } catch (MicrosoftDataEncryptionException | JsonProcessingException ex) { return Mono.error(ex); } catch (IOException e) { e.printStackTrace(); } return Mono.empty(); }); encryptionMonoList.add(voidMono); } } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionMonoList).collectList(); return listMono.flatMap(aVoid -> Mono.just(EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), itemJObj))); })); }
class EncryptionProcessor { private final static Logger LOGGER = LoggerFactory.getLogger(EncryptionProcessor.class); private CosmosEncryptionAsyncClient encryptionCosmosClient; private CosmosAsyncContainer cosmosAsyncContainer; private EncryptionKeyStoreProvider encryptionKeyStoreProvider; private EncryptionSettings encryptionSettings; private AtomicBoolean isEncryptionSettingsInitDone; private ClientEncryptionPolicy clientEncryptionPolicy; private String containerRid; private String databaseRid; private ImplementationBridgeHelpers.CosmosContainerPropertiesHelper.CosmosContainerPropertiesAccessor cosmosContainerPropertiesAccessor; public EncryptionProcessor(CosmosAsyncContainer cosmosAsyncContainer, CosmosEncryptionAsyncClient encryptionCosmosClient) { if (cosmosAsyncContainer == null) { throw new IllegalStateException("encryptionCosmosContainer is null"); } if (encryptionCosmosClient == null) { throw new IllegalStateException("encryptionCosmosClient is null"); } this.cosmosAsyncContainer = cosmosAsyncContainer; this.encryptionCosmosClient = encryptionCosmosClient; this.isEncryptionSettingsInitDone = new AtomicBoolean(false); this.encryptionKeyStoreProvider = this.encryptionCosmosClient.getEncryptionKeyStoreProvider(); this.cosmosContainerPropertiesAccessor = ImplementationBridgeHelpers.CosmosContainerPropertiesHelper.getCosmosContainerPropertiesAccessor(); this.encryptionSettings = new EncryptionSettings(); } /** * Builds up and caches the Encryption Setting by getting the cached entries of Client Encryption Policy and the * corresponding keys. * Sets up the MDE Algorithm for encryption and decryption by initializing the KeyEncryptionKey and * ProtectedDataEncryptionKey. * * @return Mono */ public Mono<Void> initializeEncryptionSettingsAsync(boolean isRetry) { if (this.isEncryptionSettingsInitDone.get()) { throw new IllegalStateException("The Encryption Processor has already been initialized. "); } Map<String, EncryptionSettings> settingsByDekId = new ConcurrentHashMap<>(); return EncryptionBridgeInternal.getContainerPropertiesMono(this.encryptionCosmosClient, this.cosmosAsyncContainer, isRetry).flatMap(cosmosContainerProperties -> { this.containerRid = cosmosContainerProperties.getResourceId(); this.databaseRid = cosmosContainerPropertiesAccessor.getSelfLink(cosmosContainerProperties).split("/")[1]; this.encryptionSettings.setDatabaseRid(this.databaseRid); if (cosmosContainerProperties.getClientEncryptionPolicy() == null) { this.isEncryptionSettingsInitDone.set(true); return Mono.empty(); } this.clientEncryptionPolicy = cosmosContainerProperties.getClientEncryptionPolicy(); AtomicReference<Mono<List<Object>>> sequentialList = new AtomicReference<>(); List<Mono<Object>> monoList = new ArrayList<>(); this.clientEncryptionPolicy.getIncludedPaths().stream() .map(clientEncryptionIncludedPath -> clientEncryptionIncludedPath.getClientEncryptionKeyId()).distinct().forEach(clientEncryptionKeyId -> { AtomicBoolean forceRefreshClientEncryptionKey = new AtomicBoolean(false); Mono<Object> clientEncryptionPropertiesMono = EncryptionBridgeInternal.getClientEncryptionPropertiesAsync(this.encryptionCosmosClient, clientEncryptionKeyId, this.databaseRid, this.cosmosAsyncContainer, forceRefreshClientEncryptionKey.get()) .publishOn(Schedulers.boundedElastic()) .flatMap(keyProperties -> { ProtectedDataEncryptionKey protectedDataEncryptionKey; try { protectedDataEncryptionKey = this.encryptionSettings.buildProtectedDataEncryptionKey(keyProperties, this.encryptionKeyStoreProvider, clientEncryptionKeyId); } catch (Exception ex) { return Mono.error(ex); } EncryptionSettings encryptionSettings = new EncryptionSettings(); encryptionSettings.setDatabaseRid(this.databaseRid); encryptionSettings.setEncryptionSettingTimeToLive(Instant.now().plus(Duration.ofMinutes(Constants.CACHED_ENCRYPTION_SETTING_DEFAULT_DEFAULT_TTL_IN_MINUTES))); encryptionSettings.setClientEncryptionKeyId(clientEncryptionKeyId); encryptionSettings.setDataEncryptionKey(protectedDataEncryptionKey); settingsByDekId.put(clientEncryptionKeyId, encryptionSettings); return Mono.empty(); }).retryWhen(Retry.withThrowable((throwableFlux -> throwableFlux.flatMap(throwable -> { InvalidKeyException invalidKeyException = Utils.as(throwable, InvalidKeyException.class); if (invalidKeyException != null && !forceRefreshClientEncryptionKey.get()) { forceRefreshClientEncryptionKey.set(true); return Mono.delay(Duration.ZERO).flux(); } return Flux.error(throwable); })))); monoList.add(clientEncryptionPropertiesMono); }); sequentialList.set(Flux.mergeSequential(monoList).collectList()); return sequentialList.get().map(objects -> { return Mono.empty(); }); }).flatMap(ignoreVoid -> { for (ClientEncryptionIncludedPath propertyToEncrypt : clientEncryptionPolicy.getIncludedPaths()) { EncryptionType encryptionType = EncryptionType.Plaintext; switch (propertyToEncrypt.getEncryptionType()) { case CosmosEncryptionType.DETERMINISTIC: encryptionType = EncryptionType.Deterministic; break; case CosmosEncryptionType.RANDOMIZED: encryptionType = EncryptionType.Randomized; break; default: LOGGER.debug("Invalid encryption type {}", propertyToEncrypt.getEncryptionType()); break; } String propertyName = propertyToEncrypt.getPath().substring(1); try { this.encryptionSettings.setEncryptionSettingForProperty(propertyName, EncryptionSettings.create(settingsByDekId.get(propertyToEncrypt.getClientEncryptionKeyId()), encryptionType), settingsByDekId.get(propertyToEncrypt.getClientEncryptionKeyId()).getEncryptionSettingTimeToLive()); } catch (MicrosoftDataEncryptionException ex) { return Mono.error(ex); } } this.isEncryptionSettingsInitDone.set(true); return Mono.empty(); }); } public Mono<Void> initEncryptionSettingsIfNotInitializedAsync() { if (!this.isEncryptionSettingsInitDone.get()) { return initializeEncryptionSettingsAsync(false).then(Mono.empty()); } return Mono.empty(); } ClientEncryptionPolicy getClientEncryptionPolicy() { return clientEncryptionPolicy; } void setClientEncryptionPolicy(ClientEncryptionPolicy clientEncryptionPolicy) { this.clientEncryptionPolicy = clientEncryptionPolicy; } /** * Gets the container that has items which are to be encrypted. * * @return the CosmosContainer */ public CosmosAsyncContainer getCosmosAsyncContainer() { return this.cosmosAsyncContainer; } /** * Gets the encrypted cosmos client. * * @return encryptionCosmosClient */ public CosmosEncryptionAsyncClient getEncryptionCosmosClient() { return encryptionCosmosClient; } /** * Gets the provider that allows interaction with the master keys. * * @return encryptionKeyStoreProvider */ public EncryptionKeyStoreProvider getEncryptionKeyStoreProvider() { return encryptionKeyStoreProvider; } public EncryptionSettings getEncryptionSettings() { return encryptionSettings; } public Mono<byte[]> encrypt(byte[] payload) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypting byte[] of size [{}] on thread [{}]", payload == null ? null : payload.length, Thread.currentThread().getName()); } ObjectNode itemJObj = Utils.parse(payload, ObjectNode.class); assert (itemJObj != null); return initEncryptionSettingsIfNotInitializedAsync().then(Mono.defer(() -> { for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { if (StringUtils.isEmpty(includedPath.getPath()) || includedPath.getPath().charAt(0) != '/' || includedPath.getPath().lastIndexOf('/') != 0) { return Mono.error(new IllegalArgumentException("Invalid encryption path: " + includedPath.getPath())); } } List<Mono<Void>> encryptionMonoList = new ArrayList<>(); for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { String propertyName = includedPath.getPath().substring(1); JsonNode propertyValueHolder = itemJObj.get(propertyName); if (propertyValueHolder != null && !propertyValueHolder.isNull()) { Mono<Void> voidMono = this.encryptionSettings.getEncryptionSettingForPropertyAsync(propertyName, this).flatMap(settings -> { try { encryptAndSerializeProperty(settings, itemJObj, propertyValueHolder, propertyName); } catch (MicrosoftDataEncryptionException ex) { return Mono.error(ex); } return Mono.empty(); }); encryptionMonoList.add(voidMono); } } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionMonoList).collectList(); return listMono.flatMap(ignoreVoid -> Mono.just(EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), itemJObj))); })); } public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException { if (propertyValueHolder.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = propertyValueHolder.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { encryptAndSerializeValue(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), child.getKey()); } } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { for (Iterator<JsonNode> arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); } else { for (Iterator<Map.Entry<String, JsonNode>> it = nodeInArray.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { encryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), child.getKey()); } } } } } else { List<byte[]> encryptedArray = new ArrayList<>(); for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) { encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); } arrayNode.removeAll(); for (byte[] encryptedValue : encryptedArray) { arrayNode.add(encryptedValue); } } } else { encryptAndSerializeValue(encryptionSettings, objectNode, propertyValueHolder, propertyName); } } public byte[] encryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException { byte[] cipherText; byte[] cipherTextWithTypeMarker; Pair<TypeMarker, byte[]> typeMarkerPair = toByteArray(propertyValueHolder); cipherText = encryptionSettings.getAeadAes256CbcHmac256EncryptionAlgorithm().encrypt(typeMarkerPair.getRight()); cipherTextWithTypeMarker = new byte[cipherText.length + 1]; cipherTextWithTypeMarker[0] = (byte) typeMarkerPair.getLeft().getValue(); System.arraycopy(cipherText, 0, cipherTextWithTypeMarker, 1, cipherText.length); if (objectNode != null && !objectNode.isNull()) { objectNode.put(propertyName, cipherTextWithTypeMarker); } return cipherTextWithTypeMarker; } public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { if (propertyValueHolder.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = propertyValueHolder.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { decryptAndSerializeValue(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), child.getKey()); } } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { for (Iterator<JsonNode> arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); } else { for (Iterator<Map.Entry<String, JsonNode>> it = nodeInArray.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { decryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), child.getKey()); } } } } } else { List<JsonNode> decryptedArray = new ArrayList<>(); for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) { decryptedArray.add(decryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); } arrayNode.removeAll(); for (JsonNode encryptedValue : decryptedArray) { arrayNode.add(encryptedValue); } } } else { decryptAndSerializeValue(encryptionSettings, objectNode, propertyValueHolder, propertyName); } } public JsonNode decryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { byte[] cipherText; byte[] cipherTextWithTypeMarker; cipherTextWithTypeMarker = propertyValueHolder.binaryValue(); cipherText = new byte[cipherTextWithTypeMarker.length - 1]; System.arraycopy(cipherTextWithTypeMarker, 1, cipherText, 0, cipherTextWithTypeMarker.length - 1); byte[] plainText = encryptionSettings.getAeadAes256CbcHmac256EncryptionAlgorithm().decrypt(cipherText); if (objectNode != null && !objectNode.isNull()) { objectNode.set(propertyName, toJsonNode(plainText, TypeMarker.valueOf(cipherTextWithTypeMarker[0]).get())); } return toJsonNode(plainText, TypeMarker.valueOf(cipherTextWithTypeMarker[0]).get()); } public static Pair<TypeMarker, byte[]> toByteArray(JsonNode jsonNode) { try { SqlSerializerFactory sqlSerializerFactory = new SqlSerializerFactory(); switch (jsonNode.getNodeType()) { case BOOLEAN: return Pair.of(TypeMarker.BOOLEAN, sqlSerializerFactory.getDefaultSerializer(Boolean.class).serialize(jsonNode.asBoolean())); case NUMBER: if (jsonNode.isInt() || jsonNode.isLong()) { return Pair.of(TypeMarker.LONG, sqlSerializerFactory.getDefaultSerializer(Long.class).serialize(jsonNode.asLong())); } else if (jsonNode.isFloat() || jsonNode.isDouble()) { return Pair.of(TypeMarker.DOUBLE, sqlSerializerFactory.getDefaultSerializer(Double.class).serialize(jsonNode.asDouble())); } break; case STRING: return Pair.of(TypeMarker.STRING, SqlSerializerFactory.getOrCreate("varchar", -1, 0, 0, StandardCharsets.UTF_8.toString()).serialize(jsonNode.asText())); } } catch (MicrosoftDataEncryptionException ex) { throw BridgeInternal.createCosmosException("Unable to convert JSON to byte[]", ex, null, 0, null); } throw BridgeInternal.createCosmosException(0, "Invalid or Unsupported Data Type Passed " + jsonNode.getNodeType()); } public static JsonNode toJsonNode(byte[] serializedBytes, TypeMarker typeMarker) { try { SqlSerializerFactory sqlSerializerFactory = new SqlSerializerFactory(); switch (typeMarker) { case BOOLEAN: return BooleanNode.valueOf((boolean) sqlSerializerFactory.getDefaultSerializer(Boolean.class).deserialize(serializedBytes)); case LONG: return LongNode.valueOf((long) sqlSerializerFactory.getDefaultSerializer(Long.class).deserialize(serializedBytes)); case DOUBLE: return DoubleNode.valueOf((double) sqlSerializerFactory.getDefaultSerializer(Double.class).deserialize(serializedBytes)); case STRING: return TextNode.valueOf((String) SqlSerializerFactory.getOrCreate("varchar", -1, 0, 0, StandardCharsets.UTF_8.toString()).deserialize(serializedBytes)); } } catch (MicrosoftDataEncryptionException ex) { throw BridgeInternal.createCosmosException("Unable to convert byte[] to JSON", ex, null, 0, null); } throw BridgeInternal.createCosmosException(0, "Invalid or Unsupported Data Type Passed " + typeMarker); } public enum TypeMarker { NULL(1), BOOLEAN(2), DOUBLE(3), LONG(4), STRING(5); private final int value; public static Optional<TypeMarker> valueOf(int value) { return Arrays.stream(values()) .filter(legNo -> legNo.value == value) .findFirst(); } TypeMarker(int value) { this.value = value; } public int getValue() { return value; } } public String getContainerRid() { return containerRid; } public AtomicBoolean getIsEncryptionSettingsInitDone(){ return this.isEncryptionSettingsInitDone; } }
class EncryptionProcessor { private final static Logger LOGGER = LoggerFactory.getLogger(EncryptionProcessor.class); private CosmosEncryptionAsyncClient encryptionCosmosClient; private CosmosAsyncContainer cosmosAsyncContainer; private EncryptionKeyStoreProvider encryptionKeyStoreProvider; private EncryptionSettings encryptionSettings; private AtomicBoolean isEncryptionSettingsInitDone; private ClientEncryptionPolicy clientEncryptionPolicy; private String containerRid; private String databaseRid; private ImplementationBridgeHelpers.CosmosContainerPropertiesHelper.CosmosContainerPropertiesAccessor cosmosContainerPropertiesAccessor; public EncryptionProcessor(CosmosAsyncContainer cosmosAsyncContainer, CosmosEncryptionAsyncClient encryptionCosmosClient) { if (cosmosAsyncContainer == null) { throw new IllegalStateException("encryptionCosmosContainer is null"); } if (encryptionCosmosClient == null) { throw new IllegalStateException("encryptionCosmosClient is null"); } this.cosmosAsyncContainer = cosmosAsyncContainer; this.encryptionCosmosClient = encryptionCosmosClient; this.isEncryptionSettingsInitDone = new AtomicBoolean(false); this.encryptionKeyStoreProvider = this.encryptionCosmosClient.getEncryptionKeyStoreProvider(); this.cosmosContainerPropertiesAccessor = ImplementationBridgeHelpers.CosmosContainerPropertiesHelper.getCosmosContainerPropertiesAccessor(); this.encryptionSettings = new EncryptionSettings(); } /** * Builds up and caches the Encryption Setting by getting the cached entries of Client Encryption Policy and the * corresponding keys. * Sets up the MDE Algorithm for encryption and decryption by initializing the KeyEncryptionKey and * ProtectedDataEncryptionKey. * * @return Mono */ public Mono<Void> initializeEncryptionSettingsAsync(boolean isRetry) { if (this.isEncryptionSettingsInitDone.get()) { throw new IllegalStateException("The Encryption Processor has already been initialized. "); } Map<String, EncryptionSettings> settingsByDekId = new ConcurrentHashMap<>(); return EncryptionBridgeInternal.getContainerPropertiesMono(this.encryptionCosmosClient, this.cosmosAsyncContainer, isRetry).flatMap(cosmosContainerProperties -> { this.containerRid = cosmosContainerProperties.getResourceId(); this.databaseRid = cosmosContainerPropertiesAccessor.getSelfLink(cosmosContainerProperties).split("/")[1]; this.encryptionSettings.setDatabaseRid(this.databaseRid); if (cosmosContainerProperties.getClientEncryptionPolicy() == null) { this.isEncryptionSettingsInitDone.set(true); return Mono.empty(); } this.clientEncryptionPolicy = cosmosContainerProperties.getClientEncryptionPolicy(); AtomicReference<Mono<List<Object>>> sequentialList = new AtomicReference<>(); List<Mono<Object>> monoList = new ArrayList<>(); this.clientEncryptionPolicy.getIncludedPaths().stream() .map(clientEncryptionIncludedPath -> clientEncryptionIncludedPath.getClientEncryptionKeyId()).distinct().forEach(clientEncryptionKeyId -> { AtomicBoolean forceRefreshClientEncryptionKey = new AtomicBoolean(false); Mono<Object> clientEncryptionPropertiesMono = EncryptionBridgeInternal.getClientEncryptionPropertiesAsync(this.encryptionCosmosClient, clientEncryptionKeyId, this.databaseRid, this.cosmosAsyncContainer, forceRefreshClientEncryptionKey.get()) .publishOn(Schedulers.boundedElastic()) .flatMap(keyProperties -> { ProtectedDataEncryptionKey protectedDataEncryptionKey; try { protectedDataEncryptionKey = this.encryptionSettings.buildProtectedDataEncryptionKey(keyProperties, this.encryptionKeyStoreProvider, clientEncryptionKeyId); } catch (Exception ex) { return Mono.error(ex); } EncryptionSettings encryptionSettings = new EncryptionSettings(); encryptionSettings.setDatabaseRid(this.databaseRid); encryptionSettings.setEncryptionSettingTimeToLive(Instant.now().plus(Duration.ofMinutes(Constants.CACHED_ENCRYPTION_SETTING_DEFAULT_DEFAULT_TTL_IN_MINUTES))); encryptionSettings.setClientEncryptionKeyId(clientEncryptionKeyId); encryptionSettings.setDataEncryptionKey(protectedDataEncryptionKey); settingsByDekId.put(clientEncryptionKeyId, encryptionSettings); return Mono.empty(); }).retryWhen(Retry.withThrowable((throwableFlux -> throwableFlux.flatMap(throwable -> { InvalidKeyException invalidKeyException = Utils.as(throwable, InvalidKeyException.class); if (invalidKeyException != null && !forceRefreshClientEncryptionKey.get()) { forceRefreshClientEncryptionKey.set(true); return Mono.delay(Duration.ZERO).flux(); } return Flux.error(throwable); })))); monoList.add(clientEncryptionPropertiesMono); }); sequentialList.set(Flux.mergeSequential(monoList).collectList()); return sequentialList.get().map(objects -> { return Mono.empty(); }); }).flatMap(ignoreVoid -> { for (ClientEncryptionIncludedPath propertyToEncrypt : clientEncryptionPolicy.getIncludedPaths()) { EncryptionType encryptionType = EncryptionType.Plaintext; switch (propertyToEncrypt.getEncryptionType()) { case CosmosEncryptionType.DETERMINISTIC: encryptionType = EncryptionType.Deterministic; break; case CosmosEncryptionType.RANDOMIZED: encryptionType = EncryptionType.Randomized; break; default: LOGGER.debug("Invalid encryption type {}", propertyToEncrypt.getEncryptionType()); break; } String propertyName = propertyToEncrypt.getPath().substring(1); try { this.encryptionSettings.setEncryptionSettingForProperty(propertyName, EncryptionSettings.create(settingsByDekId.get(propertyToEncrypt.getClientEncryptionKeyId()), encryptionType), settingsByDekId.get(propertyToEncrypt.getClientEncryptionKeyId()).getEncryptionSettingTimeToLive()); } catch (MicrosoftDataEncryptionException ex) { return Mono.error(ex); } } this.isEncryptionSettingsInitDone.set(true); return Mono.empty(); }); } public Mono<Void> initEncryptionSettingsIfNotInitializedAsync() { if (!this.isEncryptionSettingsInitDone.get()) { return initializeEncryptionSettingsAsync(false).then(Mono.empty()); } return Mono.empty(); } ClientEncryptionPolicy getClientEncryptionPolicy() { return clientEncryptionPolicy; } void setClientEncryptionPolicy(ClientEncryptionPolicy clientEncryptionPolicy) { this.clientEncryptionPolicy = clientEncryptionPolicy; } /** * Gets the container that has items which are to be encrypted. * * @return the CosmosContainer */ public CosmosAsyncContainer getCosmosAsyncContainer() { return this.cosmosAsyncContainer; } /** * Gets the encrypted cosmos client. * * @return encryptionCosmosClient */ public CosmosEncryptionAsyncClient getEncryptionCosmosClient() { return encryptionCosmosClient; } /** * Gets the provider that allows interaction with the master keys. * * @return encryptionKeyStoreProvider */ public EncryptionKeyStoreProvider getEncryptionKeyStoreProvider() { return encryptionKeyStoreProvider; } public EncryptionSettings getEncryptionSettings() { return encryptionSettings; } public Mono<byte[]> encrypt(byte[] payload) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypting byte[] of size [{}] on thread [{}]", payload == null ? null : payload.length, Thread.currentThread().getName()); } ObjectNode itemJObj = Utils.parse(payload, ObjectNode.class); assert (itemJObj != null); return initEncryptionSettingsIfNotInitializedAsync().then(Mono.defer(() -> { for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { if (StringUtils.isEmpty(includedPath.getPath()) || includedPath.getPath().charAt(0) != '/' || includedPath.getPath().lastIndexOf('/') != 0) { return Mono.error(new IllegalArgumentException("Invalid encryption path: " + includedPath.getPath())); } } List<Mono<Void>> encryptionMonoList = new ArrayList<>(); for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { String propertyName = includedPath.getPath().substring(1); JsonNode propertyValueHolder = itemJObj.get(propertyName); if (propertyValueHolder != null && !propertyValueHolder.isNull()) { Mono<Void> voidMono = this.encryptionSettings.getEncryptionSettingForPropertyAsync(propertyName, this).flatMap(settings -> { try { encryptAndSerializeProperty(settings, itemJObj, propertyValueHolder, propertyName); } catch (MicrosoftDataEncryptionException ex) { return Mono.error(ex); } return Mono.empty(); }); encryptionMonoList.add(voidMono); } } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionMonoList).collectList(); return listMono.flatMap(ignoreVoid -> Mono.just(EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), itemJObj))); })); } public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException { if (propertyValueHolder.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = propertyValueHolder.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { encryptAndSerializeValue(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), child.getKey()); } } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { for (Iterator<JsonNode> arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); } else { for (Iterator<Map.Entry<String, JsonNode>> it = nodeInArray.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { encryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), child.getKey()); } } } } } else { List<byte[]> encryptedArray = new ArrayList<>(); for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) { encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); } arrayNode.removeAll(); for (byte[] encryptedValue : encryptedArray) { arrayNode.add(encryptedValue); } } } else { encryptAndSerializeValue(encryptionSettings, objectNode, propertyValueHolder, propertyName); } } public byte[] encryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException { byte[] cipherText; byte[] cipherTextWithTypeMarker; Pair<TypeMarker, byte[]> typeMarkerPair = toByteArray(propertyValueHolder); cipherText = encryptionSettings.getAeadAes256CbcHmac256EncryptionAlgorithm().encrypt(typeMarkerPair.getRight()); cipherTextWithTypeMarker = new byte[cipherText.length + 1]; cipherTextWithTypeMarker[0] = (byte) typeMarkerPair.getLeft().getValue(); System.arraycopy(cipherText, 0, cipherTextWithTypeMarker, 1, cipherText.length); if (objectNode != null && !objectNode.isNull()) { objectNode.put(propertyName, cipherTextWithTypeMarker); } return cipherTextWithTypeMarker; } public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { if (propertyValueHolder.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = propertyValueHolder.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { decryptAndSerializeValue(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), child.getKey()); } } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { for (Iterator<JsonNode> arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); } else { for (Iterator<Map.Entry<String, JsonNode>> it = nodeInArray.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { decryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), child.getKey()); } } } } } else { List<JsonNode> decryptedArray = new ArrayList<>(); for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) { decryptedArray.add(decryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); } arrayNode.removeAll(); for (JsonNode encryptedValue : decryptedArray) { arrayNode.add(encryptedValue); } } } else { decryptAndSerializeValue(encryptionSettings, objectNode, propertyValueHolder, propertyName); } } public JsonNode decryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { byte[] cipherText; byte[] cipherTextWithTypeMarker; cipherTextWithTypeMarker = propertyValueHolder.binaryValue(); cipherText = new byte[cipherTextWithTypeMarker.length - 1]; System.arraycopy(cipherTextWithTypeMarker, 1, cipherText, 0, cipherTextWithTypeMarker.length - 1); byte[] plainText = encryptionSettings.getAeadAes256CbcHmac256EncryptionAlgorithm().decrypt(cipherText); if (objectNode != null && !objectNode.isNull()) { objectNode.set(propertyName, toJsonNode(plainText, TypeMarker.valueOf(cipherTextWithTypeMarker[0]).get())); } return toJsonNode(plainText, TypeMarker.valueOf(cipherTextWithTypeMarker[0]).get()); } public static Pair<TypeMarker, byte[]> toByteArray(JsonNode jsonNode) { try { SqlSerializerFactory sqlSerializerFactory = new SqlSerializerFactory(); switch (jsonNode.getNodeType()) { case BOOLEAN: return Pair.of(TypeMarker.BOOLEAN, sqlSerializerFactory.getDefaultSerializer(Boolean.class).serialize(jsonNode.asBoolean())); case NUMBER: if (jsonNode.isInt() || jsonNode.isLong()) { return Pair.of(TypeMarker.LONG, sqlSerializerFactory.getDefaultSerializer(Long.class).serialize(jsonNode.asLong())); } else if (jsonNode.isFloat() || jsonNode.isDouble()) { return Pair.of(TypeMarker.DOUBLE, sqlSerializerFactory.getDefaultSerializer(Double.class).serialize(jsonNode.asDouble())); } break; case STRING: return Pair.of(TypeMarker.STRING, SqlSerializerFactory.getOrCreate("varchar", -1, 0, 0, StandardCharsets.UTF_8.toString()).serialize(jsonNode.asText())); } } catch (MicrosoftDataEncryptionException ex) { throw BridgeInternal.createCosmosException("Unable to convert JSON to byte[]", ex, null, 0, null); } throw BridgeInternal.createCosmosException(0, "Invalid or Unsupported Data Type Passed " + jsonNode.getNodeType()); } public static JsonNode toJsonNode(byte[] serializedBytes, TypeMarker typeMarker) { try { SqlSerializerFactory sqlSerializerFactory = new SqlSerializerFactory(); switch (typeMarker) { case BOOLEAN: return BooleanNode.valueOf((boolean) sqlSerializerFactory.getDefaultSerializer(Boolean.class).deserialize(serializedBytes)); case LONG: return LongNode.valueOf((long) sqlSerializerFactory.getDefaultSerializer(Long.class).deserialize(serializedBytes)); case DOUBLE: return DoubleNode.valueOf((double) sqlSerializerFactory.getDefaultSerializer(Double.class).deserialize(serializedBytes)); case STRING: return TextNode.valueOf((String) SqlSerializerFactory.getOrCreate("varchar", -1, 0, 0, StandardCharsets.UTF_8.toString()).deserialize(serializedBytes)); } } catch (MicrosoftDataEncryptionException ex) { throw BridgeInternal.createCosmosException("Unable to convert byte[] to JSON", ex, null, 0, null); } throw BridgeInternal.createCosmosException(0, "Invalid or Unsupported Data Type Passed " + typeMarker); } public enum TypeMarker { NULL(1), BOOLEAN(2), DOUBLE(3), LONG(4), STRING(5); private final int value; public static Optional<TypeMarker> valueOf(int value) { return Arrays.stream(values()) .filter(legNo -> legNo.value == value) .findFirst(); } TypeMarker(int value) { this.value = value; } public int getValue() { return value; } } public String getContainerRid() { return containerRid; } public AtomicBoolean getIsEncryptionSettingsInitDone(){ return this.isEncryptionSettingsInitDone; } }
you don't need to create a new client to change `ContentResponseOnWriteEnabled`. You can set `ContentResponseOnWriteEnabled` per operation. the benefit is you don't create a new client in the test . `CosmosItemRequestOptions#setContentResponseOnWriteEnabled(false)` see https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosItemRequestOptions.java#L261-L264 Generally we should try to re-use the clients when possible as client instantiation is time costly on the test. (will add more time to the test time). Not a big deal anyway.
public void createItemEncryptWithContentResponseOnWriteEnabledFalse() { CosmosAsyncClient asyncClient = null ; try { asyncClient = new CosmosClientBuilder().endpoint(TestConfigurations.HOST).key(TestConfigurations.MASTER_KEY).buildAsyncClient(); CosmosEncryptionAsyncClient encryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(asyncClient, this.encryptionKeyStoreProvider); CosmosEncryptionAsyncContainer encryptionAsyncContainer = encryptionAsyncClient.getCosmosEncryptionAsyncDatabase(cosmosAsyncDatabase.getId()).getCosmosEncryptionAsyncContainer(containerId); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = encryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); assertThat(itemResponse.getItem()).isNull(); } finally { safeClose(asyncClient); } }
asyncClient =
public void createItemEncryptWithContentResponseOnWriteEnabledFalse() { CosmosItemRequestOptions requestOptions = new CosmosItemRequestOptions(); requestOptions.setContentResponseOnWriteEnabled(false); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), requestOptions).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); assertThat(itemResponse.getItem()).isNull(); }
class EncryptionAsyncApiCrudTest extends TestSuiteBase { private CosmosAsyncClient client; private CosmosAsyncDatabase cosmosAsyncDatabase; private static final int TIMEOUT = 6000_000; private CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient; private CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase; private CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer; private CosmosEncryptionAsyncContainer encryptionContainerWithIncompatiblePolicyVersion; private EncryptionKeyWrapMetadata metadata1; private EncryptionKeyWrapMetadata metadata2; private EncryptionKeyStoreProvider encryptionKeyStoreProvider; private String containerId; @Factory(dataProvider = "clientBuilders") public EncryptionAsyncApiCrudTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"encryption"}, timeOut = SETUP_TIMEOUT) public void before_CosmosItemTest() { assertThat(this.client).isNull(); this.client = getClientBuilder().buildAsyncClient(); encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); cosmosAsyncDatabase = getSharedCosmosDatabase(this.client); cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(this.client, encryptionKeyStoreProvider); cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(cosmosAsyncDatabase); metadata1 = new EncryptionKeyWrapMetadata(encryptionKeyStoreProvider.getProviderName(), "key1", "tempmetadata1"); metadata2 = new EncryptionKeyWrapMetadata(encryptionKeyStoreProvider.getProviderName(), "key2", "tempmetadata2"); cosmosEncryptionAsyncDatabase.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata1).block(); cosmosEncryptionAsyncDatabase.createClientEncryptionKey("key2", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata2).block(); ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(getPaths()); containerId = UUID.randomUUID().toString(); CosmosContainerProperties properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionPolicy); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); ClientEncryptionPolicy clientEncryptionWithPolicyFormatVersion2 = new ClientEncryptionPolicy(getPaths()); ReflectionUtils.setPolicyFormatVersion(clientEncryptionWithPolicyFormatVersion2, 2); containerId = UUID.randomUUID().toString(); properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionWithPolicyFormatVersion2); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); encryptionContainerWithIncompatiblePolicyVersion = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); } @AfterClass(groups = {"encryption"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.client).isNotNull(); this.client.close(); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void createItemEncrypt_readItemDecrypt() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); EncryptionPojo readItem = cosmosEncryptionAsyncContainer.readItem(properties.getId(), new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(properties, readItem); properties = getItem(UUID.randomUUID().toString()); String longString = ""; for (int i = 0; i < 10000; i++) { longString += "a"; } properties.setSensitiveString(longString); itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void upsertItem_readItem() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.upsertItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); EncryptionPojo readItem = cosmosEncryptionAsyncContainer.readItem(properties.getId(), new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(properties, readItem); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItems() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItems(querySpec, cosmosQueryRequestOptions, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(properties.getId())) { validateResponse(pojo, responseItem); } } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsOnEncryptedProperties() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveLong = @sensitiveLong"); SqlQuerySpec querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", properties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", properties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveLong", properties.getSensitiveLong()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveLong", parameter3); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, cosmosQueryRequestOptions, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(properties.getId())) { validateResponse(pojo, responseItem); } } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsOnRandomizedEncryption() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveDouble = @sensitiveDouble"); SqlQuerySpec querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", properties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", properties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveDouble", properties.getSensitiveDouble()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveDouble", parameter3); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, cosmosQueryRequestOptions, EncryptionPojo.class); try { List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); fail("Query on randomized parameter should fail"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage()).contains("Path /sensitiveDouble cannot be used in the " + "query because of randomized encryption"); } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsWithContinuationTokenAndPageSize() { List<String> actualIds = new ArrayList<>(); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); String query = String.format("SELECT * from c where c.id in ('%s', '%s', '%s')", actualIds.get(0), actualIds.get(1), actualIds.get(2)); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItems(query, cosmosQueryRequestOptions, EncryptionPojo.class); do { Iterable<FeedResponse<EncryptionPojo>> feedResponseIterable = feedResponseIterator.byPage(continuationToken, 1).toIterable(); for (FeedResponse<EncryptionPojo> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while (continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } @Ignore("Ignoring it temporarily because server always returning policyFormatVersion 0") @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void incompatiblePolicyFormatVersion() { try { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); encryptionContainerWithIncompatiblePolicyVersion.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); fail("encryptionContainerWithIncompatiblePolicyVersion crud operation should fail on client encryption " + "policy " + "fetch because of policy format version greater than 1"); } catch (UnsupportedOperationException ex) { assertThat(ex.getMessage()).isEqualTo("This version of the Encryption library cannot be used with this " + "container. Please upgrade to the latest version of the same."); } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void crudQueryStaleCache() { String databaseId = UUID.randomUUID().toString(); try { createNewDatabaseWithClientEncryptionKey(databaseId); CosmosAsyncClient asyncClient = getClientBuilder().buildAsyncClient(); EncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(asyncClient, encryptionKeyStoreProvider); CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(asyncClient.getDatabase(databaseId)); String containerId = UUID.randomUUID().toString(); ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(getPaths()); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer encryptionAsyncContainerOriginal = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); EncryptionPojo encryptionPojo = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> createResponse = encryptionAsyncContainerOriginal.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); validateResponse(encryptionPojo, createResponse.getItem()); String query = String.format("SELECT * from c where c.id = '%s'", encryptionPojo.getId()); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = encryptionAsyncContainerOriginal.queryItems(querySpec, null, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); EncryptionPojo readItem = encryptionAsyncContainerOriginal.readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(encryptionPojo, readItem); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().delete().block(); createNewDatabaseWithClientEncryptionKey(databaseId); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); createResponse = encryptionAsyncContainerOriginal.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); validateResponse(encryptionPojo, createResponse.getItem()); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); ClientEncryptionPolicy policyWithOneEncryptionPolicy = new ClientEncryptionPolicy(getPathWithOneEncryptionField()); createEncryptionContainer(cosmosEncryptionAsyncDatabase, policyWithOneEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer encryptionAsyncContainerNew = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); encryptionAsyncContainerNew.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); EncryptionPojo pojoWithOneFieldEncrypted = encryptionAsyncContainerNew.getCosmosAsyncContainer().readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponseWithOneFieldEncryption(encryptionPojo, pojoWithOneFieldEncrypted); readItem = encryptionAsyncContainerOriginal.readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(encryptionPojo, readItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosItemResponse<EncryptionPojo> upsertResponse = encryptionAsyncContainerOriginal.upsertItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = upsertResponse.getItem(); validateResponse(encryptionPojo, responseItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); encryptionAsyncContainerNew = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); encryptionAsyncContainerNew.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); CosmosItemResponse<EncryptionPojo> replaceResponse = encryptionAsyncContainerOriginal.replaceItem(encryptionPojo, encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); responseItem = replaceResponse.getItem(); validateResponse(encryptionPojo, responseItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer newEncryptionAsyncContainer = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); for (int i = 0; i < 10; i++) { EncryptionPojo pojo = getItem(UUID.randomUUID().toString()); newEncryptionAsyncContainer.createItem(pojo, new PartitionKey(pojo.getMypk()), new CosmosItemRequestOptions()).block(); } feedResponseIterator = encryptionAsyncContainerOriginal.queryItems("Select * from C", null, EncryptionPojo.class); String continuationToken = null; int pageSize = 3; int finalDocumentCount = 0; do { Iterable<FeedResponse<EncryptionPojo>> feedResponseIterable = feedResponseIterator.byPage(continuationToken, pageSize).toIterable(); for (FeedResponse<EncryptionPojo> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isLessThanOrEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while (continuationToken != null); assertThat(finalDocumentCount).isEqualTo(10); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); newEncryptionAsyncContainer = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); EncryptionPojo encryptionPojoForQueryItemsOnEncryptedProperties = getItem(UUID.randomUUID().toString()); newEncryptionAsyncContainer.createItem(encryptionPojoForQueryItemsOnEncryptedProperties, new PartitionKey(encryptionPojoForQueryItemsOnEncryptedProperties.getMypk()), new CosmosItemRequestOptions()).block(); query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveLong = @sensitiveLong"); querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", encryptionPojoForQueryItemsOnEncryptedProperties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", encryptionPojoForQueryItemsOnEncryptedProperties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveLong", encryptionPojoForQueryItemsOnEncryptedProperties.getSensitiveLong()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveLong", parameter3); feedResponseIterator = encryptionAsyncContainerOriginal.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, null, EncryptionPojo.class); feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(encryptionPojoForQueryItemsOnEncryptedProperties.getId())) { validateResponse(encryptionPojoForQueryItemsOnEncryptedProperties, pojo); } } } finally { try { this.client.getDatabase(databaseId).delete().block(); } catch(Exception ex) { } } } static void validateResponse(EncryptionPojo originalItem, EncryptionPojo result) { assertThat(result.getId()).isEqualTo(originalItem.getId()); assertThat(result.getNonSensitive()).isEqualTo(originalItem.getNonSensitive()); assertThat(result.getSensitiveString()).isEqualTo(originalItem.getSensitiveString()); assertThat(result.getSensitiveInt()).isEqualTo(originalItem.getSensitiveInt()); assertThat(result.getSensitiveFloat()).isEqualTo(originalItem.getSensitiveFloat()); assertThat(result.getSensitiveLong()).isEqualTo(originalItem.getSensitiveLong()); assertThat(result.getSensitiveDouble()).isEqualTo(originalItem.getSensitiveDouble()); assertThat(result.isSensitiveBoolean()).isEqualTo(originalItem.isSensitiveBoolean()); assertThat(result.getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveIntArray()); assertThat(result.getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveStringArray()); assertThat(result.getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveString3DArray()); assertThat(result.getSensitiveNestedPojo().getId()).isEqualTo(originalItem.getSensitiveNestedPojo().getId()); assertThat(result.getSensitiveNestedPojo().getMypk()).isEqualTo(originalItem.getSensitiveNestedPojo().getMypk()); assertThat(result.getSensitiveNestedPojo().getNonSensitive()).isEqualTo(originalItem.getSensitiveNestedPojo().getNonSensitive()); assertThat(result.getSensitiveNestedPojo().getSensitiveString()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveString()); assertThat(result.getSensitiveNestedPojo().getSensitiveInt()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveInt()); assertThat(result.getSensitiveNestedPojo().getSensitiveFloat()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveFloat()); assertThat(result.getSensitiveNestedPojo().getSensitiveLong()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveLong()); assertThat(result.getSensitiveNestedPojo().getSensitiveDouble()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveDouble()); assertThat(result.getSensitiveNestedPojo().isSensitiveBoolean()).isEqualTo(originalItem.getSensitiveNestedPojo().isSensitiveBoolean()); assertThat(result.getSensitiveNestedPojo().getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveIntArray()); assertThat(result.getSensitiveNestedPojo().getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveStringArray()); assertThat(result.getSensitiveNestedPojo().getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveString3DArray()); assertThat(result.getSensitiveChildPojoList().size()).isEqualTo(originalItem.getSensitiveChildPojoList().size()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveString()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveString()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveInt()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveInt()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveFloat()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveFloat()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveLong()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveLong()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveDouble()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveDouble()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveIntArray()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveStringArray()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveString3DArray()); assertThat(result.getSensitiveChildPojo2DArray().length).isEqualTo(originalItem.getSensitiveChildPojo2DArray().length); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveString()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveString()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveInt()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveInt()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveFloat()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveFloat()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveLong()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveLong()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveDouble()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveDouble()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveIntArray()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveStringArray()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveString3DArray()); } static void validateResponseWithOneFieldEncryption(EncryptionPojo originalItem, EncryptionPojo result) { assertThat(result.getId()).isEqualTo(originalItem.getId()); assertThat(result.getNonSensitive()).isEqualTo(originalItem.getNonSensitive()); assertThat(result.getSensitiveString()).isNotEqualTo(originalItem.getSensitiveString()); assertThat(result.getSensitiveInt()).isEqualTo(originalItem.getSensitiveInt()); assertThat(result.getSensitiveFloat()).isEqualTo(originalItem.getSensitiveFloat()); assertThat(result.getSensitiveLong()).isEqualTo(originalItem.getSensitiveLong()); assertThat(result.getSensitiveDouble()).isEqualTo(originalItem.getSensitiveDouble()); assertThat(result.isSensitiveBoolean()).isEqualTo(originalItem.isSensitiveBoolean()); assertThat(result.getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveIntArray()); assertThat(result.getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveStringArray()); assertThat(result.getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveString3DArray()); } public static EncryptionPojo getItem(String documentId) { EncryptionPojo pojo = new EncryptionPojo(); pojo.setId(documentId); pojo.setMypk(documentId); pojo.setNonSensitive(UUID.randomUUID().toString()); pojo.setSensitiveString("testingString"); pojo.setSensitiveDouble(10.123); pojo.setSensitiveFloat(20.0f); pojo.setSensitiveInt(30); pojo.setSensitiveLong(1234); pojo.setSensitiveBoolean(true); EncryptionPojo nestedPojo = new EncryptionPojo(); nestedPojo.setId("nestedPojo"); nestedPojo.setMypk("nestedPojo"); nestedPojo.setSensitiveString("nestedPojo"); nestedPojo.setSensitiveDouble(10.123); nestedPojo.setSensitiveInt(123); nestedPojo.setSensitiveLong(1234); nestedPojo.setSensitiveStringArray(new String[]{"str1", "str1"}); nestedPojo.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); nestedPojo.setSensitiveBoolean(true); pojo.setSensitiveNestedPojo(nestedPojo); pojo.setSensitiveIntArray(new int[]{1, 2}); pojo.setSensitiveStringArray(new String[]{"str1", "str1"}); pojo.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); EncryptionPojo childPojo1 = new EncryptionPojo(); childPojo1.setId("childPojo1"); childPojo1.setSensitiveString("child1TestingString"); childPojo1.setSensitiveDouble(10.123); childPojo1.setSensitiveInt(123); childPojo1.setSensitiveLong(1234); childPojo1.setSensitiveBoolean(true); childPojo1.setSensitiveStringArray(new String[]{"str1", "str1"}); childPojo1.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); EncryptionPojo childPojo2 = new EncryptionPojo(); childPojo2.setId("childPojo2"); childPojo2.setSensitiveString("child2TestingString"); childPojo2.setSensitiveDouble(10.123); childPojo2.setSensitiveInt(123); childPojo2.setSensitiveLong(1234); childPojo2.setSensitiveBoolean(true); pojo.setSensitiveChildPojoList(new ArrayList<>()); pojo.getSensitiveChildPojoList().add(childPojo1); pojo.getSensitiveChildPojoList().add(childPojo2); pojo.setSensitiveChildPojo2DArray(new EncryptionPojo[][]{{childPojo1, childPojo2}, {childPojo1, childPojo2}}); return pojo; } public static class TestEncryptionKeyStoreProvider extends EncryptionKeyStoreProvider { Map<String, Integer> keyInfo = new HashMap<>(); String providerName = "TEST_KEY_STORE_PROVIDER"; @Override public String getProviderName() { return providerName; } public TestEncryptionKeyStoreProvider() { keyInfo.put("tempmetadata1", 1); keyInfo.put("tempmetadata2", 2); } @Override public byte[] unwrapKey(String s, KeyEncryptionKeyAlgorithm keyEncryptionKeyAlgorithm, byte[] encryptedBytes) { int moveBy = this.keyInfo.get(s); byte[] plainkey = new byte[encryptedBytes.length]; for (int i = 0; i < encryptedBytes.length; i++) { plainkey[i] = (byte) (encryptedBytes[i] - moveBy); } return plainkey; } @Override public byte[] wrapKey(String s, KeyEncryptionKeyAlgorithm keyEncryptionKeyAlgorithm, byte[] key) { int moveBy = this.keyInfo.get(s); byte[] encryptedBytes = new byte[key.length]; for (int i = 0; i < key.length; i++) { encryptedBytes[i] = (byte) (key[i] + moveBy); } return encryptedBytes; } @Override public byte[] sign(String s, boolean b) { return new byte[0]; } @Override public boolean verify(String s, boolean b, byte[] bytes) { return true; } } public static List<ClientEncryptionIncludedPath> getPaths() { ClientEncryptionIncludedPath includedPath1 = new ClientEncryptionIncludedPath(); includedPath1.setClientEncryptionKeyId("key1"); includedPath1.setPath("/sensitiveString"); includedPath1.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath1.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath2 = new ClientEncryptionIncludedPath(); includedPath2.setClientEncryptionKeyId("key2"); includedPath2.setPath("/nonValidPath"); includedPath2.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath2.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath3 = new ClientEncryptionIncludedPath(); includedPath3.setClientEncryptionKeyId("key1"); includedPath3.setPath("/sensitiveInt"); includedPath3.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath3.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath4 = new ClientEncryptionIncludedPath(); includedPath4.setClientEncryptionKeyId("key2"); includedPath4.setPath("/sensitiveFloat"); includedPath4.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath4.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath5 = new ClientEncryptionIncludedPath(); includedPath5.setClientEncryptionKeyId("key1"); includedPath5.setPath("/sensitiveLong"); includedPath5.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath5.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath6 = new ClientEncryptionIncludedPath(); includedPath6.setClientEncryptionKeyId("key2"); includedPath6.setPath("/sensitiveDouble"); includedPath6.setEncryptionType(CosmosEncryptionType.RANDOMIZED); includedPath6.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath7 = new ClientEncryptionIncludedPath(); includedPath7.setClientEncryptionKeyId("key1"); includedPath7.setPath("/sensitiveBoolean"); includedPath7.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath7.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath8 = new ClientEncryptionIncludedPath(); includedPath8.setClientEncryptionKeyId("key1"); includedPath8.setPath("/sensitiveNestedPojo"); includedPath8.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath8.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath9 = new ClientEncryptionIncludedPath(); includedPath9.setClientEncryptionKeyId("key1"); includedPath9.setPath("/sensitiveIntArray"); includedPath9.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath9.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath10 = new ClientEncryptionIncludedPath(); includedPath10.setClientEncryptionKeyId("key2"); includedPath10.setPath("/sensitiveString3DArray"); includedPath10.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath10.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath11 = new ClientEncryptionIncludedPath(); includedPath11.setClientEncryptionKeyId("key1"); includedPath11.setPath("/sensitiveStringArray"); includedPath11.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath11.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath12 = new ClientEncryptionIncludedPath(); includedPath12.setClientEncryptionKeyId("key1"); includedPath12.setPath("/sensitiveChildPojoList"); includedPath12.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath12.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath13 = new ClientEncryptionIncludedPath(); includedPath13.setClientEncryptionKeyId("key1"); includedPath13.setPath("/sensitiveChildPojo2DArray"); includedPath13.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath13.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); List<ClientEncryptionIncludedPath> paths = new ArrayList<>(); paths.add(includedPath1); paths.add(includedPath2); paths.add(includedPath3); paths.add(includedPath4); paths.add(includedPath5); paths.add(includedPath6); paths.add(includedPath7); paths.add(includedPath8); paths.add(includedPath9); paths.add(includedPath10); paths.add(includedPath11); paths.add(includedPath12); paths.add(includedPath13); return paths; } public static List<ClientEncryptionIncludedPath> getPathWithOneEncryptionField() { ClientEncryptionIncludedPath includedPath = new ClientEncryptionIncludedPath(); includedPath.setClientEncryptionKeyId("key1"); includedPath.setPath("/sensitiveString"); includedPath.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); List<ClientEncryptionIncludedPath> paths = new ArrayList<>(); paths.add(includedPath); return paths; } private void createEncryptionContainer(CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase, ClientEncryptionPolicy clientEncryptionPolicy, String containerId) { CosmosContainerProperties properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionPolicy); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); } private void createNewDatabaseWithClientEncryptionKey(String databaseId){ cosmosEncryptionAsyncClient.getCosmosAsyncClient().createDatabase(databaseId).block(); CosmosEncryptionAsyncDatabase encryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(databaseId); encryptionAsyncDatabase.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata1).block(); encryptionAsyncDatabase.createClientEncryptionKey("key2", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata2).block(); } private CosmosEncryptionAsyncContainer getNewEncryptionContainerProxyObject(String databaseId, String containerId) { CosmosAsyncClient client = getClientBuilder().buildAsyncClient(); EncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(client, encryptionKeyStoreProvider); CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(client.getDatabase(databaseId)); CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); return cosmosEncryptionAsyncContainer; } }
class EncryptionAsyncApiCrudTest extends TestSuiteBase { private CosmosAsyncClient client; private CosmosAsyncDatabase cosmosAsyncDatabase; private static final int TIMEOUT = 6000_000; private CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient; private CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase; private CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer; private CosmosEncryptionAsyncContainer encryptionContainerWithIncompatiblePolicyVersion; private EncryptionKeyWrapMetadata metadata1; private EncryptionKeyWrapMetadata metadata2; @Factory(dataProvider = "clientBuilders") public EncryptionAsyncApiCrudTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"encryption"}, timeOut = SETUP_TIMEOUT) public void before_CosmosItemTest() { assertThat(this.client).isNull(); this.client = getClientBuilder().buildAsyncClient(); TestEncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); cosmosAsyncDatabase = getSharedCosmosDatabase(this.client); cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(this.client, encryptionKeyStoreProvider); cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(cosmosAsyncDatabase); metadata1 = new EncryptionKeyWrapMetadata(encryptionKeyStoreProvider.getProviderName(), "key1", "tempmetadata1"); metadata2 = new EncryptionKeyWrapMetadata(encryptionKeyStoreProvider.getProviderName(), "key2", "tempmetadata2"); cosmosEncryptionAsyncDatabase.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata1).block(); cosmosEncryptionAsyncDatabase.createClientEncryptionKey("key2", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata2).block(); ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(getPaths()); String containerId = UUID.randomUUID().toString(); CosmosContainerProperties properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionPolicy); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); ClientEncryptionPolicy clientEncryptionWithPolicyFormatVersion2 = new ClientEncryptionPolicy(getPaths()); ReflectionUtils.setPolicyFormatVersion(clientEncryptionWithPolicyFormatVersion2, 2); containerId = UUID.randomUUID().toString(); properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionWithPolicyFormatVersion2); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); encryptionContainerWithIncompatiblePolicyVersion = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); } @AfterClass(groups = {"encryption"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.client).isNotNull(); this.client.close(); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void createItemEncrypt_readItemDecrypt() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); EncryptionPojo readItem = cosmosEncryptionAsyncContainer.readItem(properties.getId(), new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(properties, readItem); properties = getItem(UUID.randomUUID().toString()); String longString = ""; for (int i = 0; i < 10000; i++) { longString += "a"; } properties.setSensitiveString(longString); itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void upsertItem_readItem() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.upsertItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); EncryptionPojo readItem = cosmosEncryptionAsyncContainer.readItem(properties.getId(), new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(properties, readItem); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItems() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItems(querySpec, cosmosQueryRequestOptions, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(properties.getId())) { validateResponse(pojo, responseItem); } } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsOnEncryptedProperties() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveLong = @sensitiveLong"); SqlQuerySpec querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", properties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", properties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveLong", properties.getSensitiveLong()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveLong", parameter3); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, cosmosQueryRequestOptions, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(properties.getId())) { validateResponse(pojo, responseItem); } } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsOnRandomizedEncryption() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveDouble = @sensitiveDouble"); SqlQuerySpec querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", properties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", properties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveDouble", properties.getSensitiveDouble()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveDouble", parameter3); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, cosmosQueryRequestOptions, EncryptionPojo.class); try { List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); fail("Query on randomized parameter should fail"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage()).contains("Path /sensitiveDouble cannot be used in the " + "query because of randomized encryption"); } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsWithContinuationTokenAndPageSize() { List<String> actualIds = new ArrayList<>(); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); String query = String.format("SELECT * from c where c.id in ('%s', '%s', '%s')", actualIds.get(0), actualIds.get(1), actualIds.get(2)); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItems(query, cosmosQueryRequestOptions, EncryptionPojo.class); do { Iterable<FeedResponse<EncryptionPojo>> feedResponseIterable = feedResponseIterator.byPage(continuationToken, 1).toIterable(); for (FeedResponse<EncryptionPojo> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while (continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } @Ignore("Ignoring it temporarily because server always returning policyFormatVersion 0") @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void incompatiblePolicyFormatVersion() { try { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); encryptionContainerWithIncompatiblePolicyVersion.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); fail("encryptionContainerWithIncompatiblePolicyVersion crud operation should fail on client encryption " + "policy " + "fetch because of policy format version greater than 1"); } catch (UnsupportedOperationException ex) { assertThat(ex.getMessage()).isEqualTo("This version of the Encryption library cannot be used with this " + "container. Please upgrade to the latest version of the same."); } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void crudQueryStaleCache() { String databaseId = UUID.randomUUID().toString(); try { createNewDatabaseWithClientEncryptionKey(databaseId); CosmosAsyncClient asyncClient = getClientBuilder().buildAsyncClient(); EncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(asyncClient, encryptionKeyStoreProvider); CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(asyncClient.getDatabase(databaseId)); String containerId = UUID.randomUUID().toString(); ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(getPaths()); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer encryptionAsyncContainerOriginal = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); EncryptionPojo encryptionPojo = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> createResponse = encryptionAsyncContainerOriginal.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); validateResponse(encryptionPojo, createResponse.getItem()); String query = String.format("SELECT * from c where c.id = '%s'", encryptionPojo.getId()); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = encryptionAsyncContainerOriginal.queryItems(querySpec, null, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); EncryptionPojo readItem = encryptionAsyncContainerOriginal.readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(encryptionPojo, readItem); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().delete().block(); createNewDatabaseWithClientEncryptionKey(databaseId); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); createResponse = encryptionAsyncContainerOriginal.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); validateResponse(encryptionPojo, createResponse.getItem()); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); ClientEncryptionPolicy policyWithOneEncryptionPolicy = new ClientEncryptionPolicy(getPathWithOneEncryptionField()); createEncryptionContainer(cosmosEncryptionAsyncDatabase, policyWithOneEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer encryptionAsyncContainerNew = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); encryptionAsyncContainerNew.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); EncryptionPojo pojoWithOneFieldEncrypted = encryptionAsyncContainerNew.getCosmosAsyncContainer().readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponseWithOneFieldEncryption(encryptionPojo, pojoWithOneFieldEncrypted); readItem = encryptionAsyncContainerOriginal.readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(encryptionPojo, readItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosItemResponse<EncryptionPojo> upsertResponse = encryptionAsyncContainerOriginal.upsertItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = upsertResponse.getItem(); validateResponse(encryptionPojo, responseItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); encryptionAsyncContainerNew = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); encryptionAsyncContainerNew.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); CosmosItemResponse<EncryptionPojo> replaceResponse = encryptionAsyncContainerOriginal.replaceItem(encryptionPojo, encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); responseItem = replaceResponse.getItem(); validateResponse(encryptionPojo, responseItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer newEncryptionAsyncContainer = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); for (int i = 0; i < 10; i++) { EncryptionPojo pojo = getItem(UUID.randomUUID().toString()); newEncryptionAsyncContainer.createItem(pojo, new PartitionKey(pojo.getMypk()), new CosmosItemRequestOptions()).block(); } feedResponseIterator = encryptionAsyncContainerOriginal.queryItems("Select * from C", null, EncryptionPojo.class); String continuationToken = null; int pageSize = 3; int finalDocumentCount = 0; do { Iterable<FeedResponse<EncryptionPojo>> feedResponseIterable = feedResponseIterator.byPage(continuationToken, pageSize).toIterable(); for (FeedResponse<EncryptionPojo> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isLessThanOrEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while (continuationToken != null); assertThat(finalDocumentCount).isEqualTo(10); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); newEncryptionAsyncContainer = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); EncryptionPojo encryptionPojoForQueryItemsOnEncryptedProperties = getItem(UUID.randomUUID().toString()); newEncryptionAsyncContainer.createItem(encryptionPojoForQueryItemsOnEncryptedProperties, new PartitionKey(encryptionPojoForQueryItemsOnEncryptedProperties.getMypk()), new CosmosItemRequestOptions()).block(); query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveLong = @sensitiveLong"); querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", encryptionPojoForQueryItemsOnEncryptedProperties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", encryptionPojoForQueryItemsOnEncryptedProperties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveLong", encryptionPojoForQueryItemsOnEncryptedProperties.getSensitiveLong()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveLong", parameter3); feedResponseIterator = encryptionAsyncContainerOriginal.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, null, EncryptionPojo.class); feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(encryptionPojoForQueryItemsOnEncryptedProperties.getId())) { validateResponse(encryptionPojoForQueryItemsOnEncryptedProperties, pojo); } } } finally { try { this.client.getDatabase(databaseId).delete().block(); } catch(Exception ex) { } } } static void validateResponse(EncryptionPojo originalItem, EncryptionPojo result) { assertThat(result.getId()).isEqualTo(originalItem.getId()); assertThat(result.getNonSensitive()).isEqualTo(originalItem.getNonSensitive()); assertThat(result.getSensitiveString()).isEqualTo(originalItem.getSensitiveString()); assertThat(result.getSensitiveInt()).isEqualTo(originalItem.getSensitiveInt()); assertThat(result.getSensitiveFloat()).isEqualTo(originalItem.getSensitiveFloat()); assertThat(result.getSensitiveLong()).isEqualTo(originalItem.getSensitiveLong()); assertThat(result.getSensitiveDouble()).isEqualTo(originalItem.getSensitiveDouble()); assertThat(result.isSensitiveBoolean()).isEqualTo(originalItem.isSensitiveBoolean()); assertThat(result.getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveIntArray()); assertThat(result.getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveStringArray()); assertThat(result.getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveString3DArray()); assertThat(result.getSensitiveNestedPojo().getId()).isEqualTo(originalItem.getSensitiveNestedPojo().getId()); assertThat(result.getSensitiveNestedPojo().getMypk()).isEqualTo(originalItem.getSensitiveNestedPojo().getMypk()); assertThat(result.getSensitiveNestedPojo().getNonSensitive()).isEqualTo(originalItem.getSensitiveNestedPojo().getNonSensitive()); assertThat(result.getSensitiveNestedPojo().getSensitiveString()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveString()); assertThat(result.getSensitiveNestedPojo().getSensitiveInt()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveInt()); assertThat(result.getSensitiveNestedPojo().getSensitiveFloat()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveFloat()); assertThat(result.getSensitiveNestedPojo().getSensitiveLong()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveLong()); assertThat(result.getSensitiveNestedPojo().getSensitiveDouble()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveDouble()); assertThat(result.getSensitiveNestedPojo().isSensitiveBoolean()).isEqualTo(originalItem.getSensitiveNestedPojo().isSensitiveBoolean()); assertThat(result.getSensitiveNestedPojo().getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveIntArray()); assertThat(result.getSensitiveNestedPojo().getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveStringArray()); assertThat(result.getSensitiveNestedPojo().getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveString3DArray()); assertThat(result.getSensitiveChildPojoList().size()).isEqualTo(originalItem.getSensitiveChildPojoList().size()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveString()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveString()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveInt()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveInt()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveFloat()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveFloat()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveLong()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveLong()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveDouble()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveDouble()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveIntArray()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveStringArray()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveString3DArray()); assertThat(result.getSensitiveChildPojo2DArray().length).isEqualTo(originalItem.getSensitiveChildPojo2DArray().length); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveString()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveString()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveInt()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveInt()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveFloat()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveFloat()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveLong()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveLong()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveDouble()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveDouble()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveIntArray()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveStringArray()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveString3DArray()); } static void validateResponseWithOneFieldEncryption(EncryptionPojo originalItem, EncryptionPojo result) { assertThat(result.getId()).isEqualTo(originalItem.getId()); assertThat(result.getNonSensitive()).isEqualTo(originalItem.getNonSensitive()); assertThat(result.getSensitiveString()).isNotEqualTo(originalItem.getSensitiveString()); assertThat(result.getSensitiveInt()).isEqualTo(originalItem.getSensitiveInt()); assertThat(result.getSensitiveFloat()).isEqualTo(originalItem.getSensitiveFloat()); assertThat(result.getSensitiveLong()).isEqualTo(originalItem.getSensitiveLong()); assertThat(result.getSensitiveDouble()).isEqualTo(originalItem.getSensitiveDouble()); assertThat(result.isSensitiveBoolean()).isEqualTo(originalItem.isSensitiveBoolean()); assertThat(result.getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveIntArray()); assertThat(result.getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveStringArray()); assertThat(result.getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveString3DArray()); } public static EncryptionPojo getItem(String documentId) { EncryptionPojo pojo = new EncryptionPojo(); pojo.setId(documentId); pojo.setMypk(documentId); pojo.setNonSensitive(UUID.randomUUID().toString()); pojo.setSensitiveString("testingString"); pojo.setSensitiveDouble(10.123); pojo.setSensitiveFloat(20.0f); pojo.setSensitiveInt(30); pojo.setSensitiveLong(1234); pojo.setSensitiveBoolean(true); EncryptionPojo nestedPojo = new EncryptionPojo(); nestedPojo.setId("nestedPojo"); nestedPojo.setMypk("nestedPojo"); nestedPojo.setSensitiveString("nestedPojo"); nestedPojo.setSensitiveDouble(10.123); nestedPojo.setSensitiveInt(123); nestedPojo.setSensitiveLong(1234); nestedPojo.setSensitiveStringArray(new String[]{"str1", "str1"}); nestedPojo.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); nestedPojo.setSensitiveBoolean(true); pojo.setSensitiveNestedPojo(nestedPojo); pojo.setSensitiveIntArray(new int[]{1, 2}); pojo.setSensitiveStringArray(new String[]{"str1", "str1"}); pojo.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); EncryptionPojo childPojo1 = new EncryptionPojo(); childPojo1.setId("childPojo1"); childPojo1.setSensitiveString("child1TestingString"); childPojo1.setSensitiveDouble(10.123); childPojo1.setSensitiveInt(123); childPojo1.setSensitiveLong(1234); childPojo1.setSensitiveBoolean(true); childPojo1.setSensitiveStringArray(new String[]{"str1", "str1"}); childPojo1.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); EncryptionPojo childPojo2 = new EncryptionPojo(); childPojo2.setId("childPojo2"); childPojo2.setSensitiveString("child2TestingString"); childPojo2.setSensitiveDouble(10.123); childPojo2.setSensitiveInt(123); childPojo2.setSensitiveLong(1234); childPojo2.setSensitiveBoolean(true); pojo.setSensitiveChildPojoList(new ArrayList<>()); pojo.getSensitiveChildPojoList().add(childPojo1); pojo.getSensitiveChildPojoList().add(childPojo2); pojo.setSensitiveChildPojo2DArray(new EncryptionPojo[][]{{childPojo1, childPojo2}, {childPojo1, childPojo2}}); return pojo; } public static class TestEncryptionKeyStoreProvider extends EncryptionKeyStoreProvider { Map<String, Integer> keyInfo = new HashMap<>(); String providerName = "TEST_KEY_STORE_PROVIDER"; @Override public String getProviderName() { return providerName; } public TestEncryptionKeyStoreProvider() { keyInfo.put("tempmetadata1", 1); keyInfo.put("tempmetadata2", 2); } @Override public byte[] unwrapKey(String s, KeyEncryptionKeyAlgorithm keyEncryptionKeyAlgorithm, byte[] encryptedBytes) { int moveBy = this.keyInfo.get(s); byte[] plainkey = new byte[encryptedBytes.length]; for (int i = 0; i < encryptedBytes.length; i++) { plainkey[i] = (byte) (encryptedBytes[i] - moveBy); } return plainkey; } @Override public byte[] wrapKey(String s, KeyEncryptionKeyAlgorithm keyEncryptionKeyAlgorithm, byte[] key) { int moveBy = this.keyInfo.get(s); byte[] encryptedBytes = new byte[key.length]; for (int i = 0; i < key.length; i++) { encryptedBytes[i] = (byte) (key[i] + moveBy); } return encryptedBytes; } @Override public byte[] sign(String s, boolean b) { return new byte[0]; } @Override public boolean verify(String s, boolean b, byte[] bytes) { return true; } } public static List<ClientEncryptionIncludedPath> getPaths() { ClientEncryptionIncludedPath includedPath1 = new ClientEncryptionIncludedPath(); includedPath1.setClientEncryptionKeyId("key1"); includedPath1.setPath("/sensitiveString"); includedPath1.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath1.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath2 = new ClientEncryptionIncludedPath(); includedPath2.setClientEncryptionKeyId("key2"); includedPath2.setPath("/nonValidPath"); includedPath2.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath2.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath3 = new ClientEncryptionIncludedPath(); includedPath3.setClientEncryptionKeyId("key1"); includedPath3.setPath("/sensitiveInt"); includedPath3.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath3.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath4 = new ClientEncryptionIncludedPath(); includedPath4.setClientEncryptionKeyId("key2"); includedPath4.setPath("/sensitiveFloat"); includedPath4.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath4.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath5 = new ClientEncryptionIncludedPath(); includedPath5.setClientEncryptionKeyId("key1"); includedPath5.setPath("/sensitiveLong"); includedPath5.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath5.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath6 = new ClientEncryptionIncludedPath(); includedPath6.setClientEncryptionKeyId("key2"); includedPath6.setPath("/sensitiveDouble"); includedPath6.setEncryptionType(CosmosEncryptionType.RANDOMIZED); includedPath6.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath7 = new ClientEncryptionIncludedPath(); includedPath7.setClientEncryptionKeyId("key1"); includedPath7.setPath("/sensitiveBoolean"); includedPath7.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath7.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath8 = new ClientEncryptionIncludedPath(); includedPath8.setClientEncryptionKeyId("key1"); includedPath8.setPath("/sensitiveNestedPojo"); includedPath8.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath8.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath9 = new ClientEncryptionIncludedPath(); includedPath9.setClientEncryptionKeyId("key1"); includedPath9.setPath("/sensitiveIntArray"); includedPath9.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath9.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath10 = new ClientEncryptionIncludedPath(); includedPath10.setClientEncryptionKeyId("key2"); includedPath10.setPath("/sensitiveString3DArray"); includedPath10.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath10.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath11 = new ClientEncryptionIncludedPath(); includedPath11.setClientEncryptionKeyId("key1"); includedPath11.setPath("/sensitiveStringArray"); includedPath11.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath11.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath12 = new ClientEncryptionIncludedPath(); includedPath12.setClientEncryptionKeyId("key1"); includedPath12.setPath("/sensitiveChildPojoList"); includedPath12.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath12.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath13 = new ClientEncryptionIncludedPath(); includedPath13.setClientEncryptionKeyId("key1"); includedPath13.setPath("/sensitiveChildPojo2DArray"); includedPath13.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath13.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); List<ClientEncryptionIncludedPath> paths = new ArrayList<>(); paths.add(includedPath1); paths.add(includedPath2); paths.add(includedPath3); paths.add(includedPath4); paths.add(includedPath5); paths.add(includedPath6); paths.add(includedPath7); paths.add(includedPath8); paths.add(includedPath9); paths.add(includedPath10); paths.add(includedPath11); paths.add(includedPath12); paths.add(includedPath13); return paths; } public static List<ClientEncryptionIncludedPath> getPathWithOneEncryptionField() { ClientEncryptionIncludedPath includedPath = new ClientEncryptionIncludedPath(); includedPath.setClientEncryptionKeyId("key1"); includedPath.setPath("/sensitiveString"); includedPath.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); List<ClientEncryptionIncludedPath> paths = new ArrayList<>(); paths.add(includedPath); return paths; } private void createEncryptionContainer(CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase, ClientEncryptionPolicy clientEncryptionPolicy, String containerId) { CosmosContainerProperties properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionPolicy); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); } private void createNewDatabaseWithClientEncryptionKey(String databaseId){ cosmosEncryptionAsyncClient.getCosmosAsyncClient().createDatabase(databaseId).block(); CosmosEncryptionAsyncDatabase encryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(databaseId); encryptionAsyncDatabase.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata1).block(); encryptionAsyncDatabase.createClientEncryptionKey("key2", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata2).block(); } private CosmosEncryptionAsyncContainer getNewEncryptionContainerProxyObject(String databaseId, String containerId) { CosmosAsyncClient client = getClientBuilder().buildAsyncClient(); EncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(client, encryptionKeyStoreProvider); CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(client.getDatabase(databaseId)); CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); return cosmosEncryptionAsyncContainer; } }
done
public Mono<byte[]> decrypt(byte[] input) { if (input == null || input.length < 1) { return Mono.empty(); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypting byte[] of size [{}] on thread [{}]", input == null ? null : input.length, Thread.currentThread().getName()); } ObjectNode itemJObj = Utils.parse(input, ObjectNode.class); assert (itemJObj != null); return initEncryptionSettingsIfNotInitializedAsync().then(Mono.defer(() -> { for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { if (StringUtils.isEmpty(includedPath.getPath()) || includedPath.getPath().charAt(0) != '/' || includedPath.getPath().lastIndexOf('/') != 0) { return Mono.error(new IllegalArgumentException("Invalid encryption path: " + includedPath.getPath())); } } List<Mono<Void>> encryptionMonoList = new ArrayList<>(); for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { String propertyName = includedPath.getPath().substring(1); JsonNode propertyValueHolder = itemJObj.get(propertyName); if (propertyValueHolder != null && !propertyValueHolder.isNull()) { Mono<Void> voidMono = this.encryptionSettings.getEncryptionSettingForPropertyAsync(propertyName, this).flatMap(settings -> { try { decryptAndSerializeProperty(settings, itemJObj, propertyValueHolder, propertyName); } catch (MicrosoftDataEncryptionException | JsonProcessingException ex) { return Mono.error(ex); } catch (IOException e) { e.printStackTrace(); } return Mono.empty(); }); encryptionMonoList.add(voidMono); } } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionMonoList).collectList(); return listMono.flatMap(aVoid -> Mono.just(EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), itemJObj))); })); }
if (input == null || input.length < 1) {
public Mono<byte[]> decrypt(byte[] input) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypting byte[] of size [{}] on thread [{}]", input == null ? null : input.length, Thread.currentThread().getName()); } if (input == null || input.length == 0) { return Mono.empty(); } ObjectNode itemJObj = Utils.parse(input, ObjectNode.class); assert (itemJObj != null); return initEncryptionSettingsIfNotInitializedAsync().then(Mono.defer(() -> { for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { if (StringUtils.isEmpty(includedPath.getPath()) || includedPath.getPath().charAt(0) != '/' || includedPath.getPath().lastIndexOf('/') != 0) { return Mono.error(new IllegalArgumentException("Invalid encryption path: " + includedPath.getPath())); } } List<Mono<Void>> encryptionMonoList = new ArrayList<>(); for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { String propertyName = includedPath.getPath().substring(1); JsonNode propertyValueHolder = itemJObj.get(propertyName); if (propertyValueHolder != null && !propertyValueHolder.isNull()) { Mono<Void> voidMono = this.encryptionSettings.getEncryptionSettingForPropertyAsync(propertyName, this).flatMap(settings -> { try { decryptAndSerializeProperty(settings, itemJObj, propertyValueHolder, propertyName); } catch (MicrosoftDataEncryptionException | JsonProcessingException ex) { return Mono.error(ex); } catch (IOException e) { e.printStackTrace(); } return Mono.empty(); }); encryptionMonoList.add(voidMono); } } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionMonoList).collectList(); return listMono.flatMap(aVoid -> Mono.just(EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), itemJObj))); })); }
class EncryptionProcessor { private final static Logger LOGGER = LoggerFactory.getLogger(EncryptionProcessor.class); private CosmosEncryptionAsyncClient encryptionCosmosClient; private CosmosAsyncContainer cosmosAsyncContainer; private EncryptionKeyStoreProvider encryptionKeyStoreProvider; private EncryptionSettings encryptionSettings; private AtomicBoolean isEncryptionSettingsInitDone; private ClientEncryptionPolicy clientEncryptionPolicy; private String containerRid; private String databaseRid; private ImplementationBridgeHelpers.CosmosContainerPropertiesHelper.CosmosContainerPropertiesAccessor cosmosContainerPropertiesAccessor; public EncryptionProcessor(CosmosAsyncContainer cosmosAsyncContainer, CosmosEncryptionAsyncClient encryptionCosmosClient) { if (cosmosAsyncContainer == null) { throw new IllegalStateException("encryptionCosmosContainer is null"); } if (encryptionCosmosClient == null) { throw new IllegalStateException("encryptionCosmosClient is null"); } this.cosmosAsyncContainer = cosmosAsyncContainer; this.encryptionCosmosClient = encryptionCosmosClient; this.isEncryptionSettingsInitDone = new AtomicBoolean(false); this.encryptionKeyStoreProvider = this.encryptionCosmosClient.getEncryptionKeyStoreProvider(); this.cosmosContainerPropertiesAccessor = ImplementationBridgeHelpers.CosmosContainerPropertiesHelper.getCosmosContainerPropertiesAccessor(); this.encryptionSettings = new EncryptionSettings(); } /** * Builds up and caches the Encryption Setting by getting the cached entries of Client Encryption Policy and the * corresponding keys. * Sets up the MDE Algorithm for encryption and decryption by initializing the KeyEncryptionKey and * ProtectedDataEncryptionKey. * * @return Mono */ public Mono<Void> initializeEncryptionSettingsAsync(boolean isRetry) { if (this.isEncryptionSettingsInitDone.get()) { throw new IllegalStateException("The Encryption Processor has already been initialized. "); } Map<String, EncryptionSettings> settingsByDekId = new ConcurrentHashMap<>(); return EncryptionBridgeInternal.getContainerPropertiesMono(this.encryptionCosmosClient, this.cosmosAsyncContainer, isRetry).flatMap(cosmosContainerProperties -> { this.containerRid = cosmosContainerProperties.getResourceId(); this.databaseRid = cosmosContainerPropertiesAccessor.getSelfLink(cosmosContainerProperties).split("/")[1]; this.encryptionSettings.setDatabaseRid(this.databaseRid); if (cosmosContainerProperties.getClientEncryptionPolicy() == null) { this.isEncryptionSettingsInitDone.set(true); return Mono.empty(); } this.clientEncryptionPolicy = cosmosContainerProperties.getClientEncryptionPolicy(); AtomicReference<Mono<List<Object>>> sequentialList = new AtomicReference<>(); List<Mono<Object>> monoList = new ArrayList<>(); this.clientEncryptionPolicy.getIncludedPaths().stream() .map(clientEncryptionIncludedPath -> clientEncryptionIncludedPath.getClientEncryptionKeyId()).distinct().forEach(clientEncryptionKeyId -> { AtomicBoolean forceRefreshClientEncryptionKey = new AtomicBoolean(false); Mono<Object> clientEncryptionPropertiesMono = EncryptionBridgeInternal.getClientEncryptionPropertiesAsync(this.encryptionCosmosClient, clientEncryptionKeyId, this.databaseRid, this.cosmosAsyncContainer, forceRefreshClientEncryptionKey.get()) .publishOn(Schedulers.boundedElastic()) .flatMap(keyProperties -> { ProtectedDataEncryptionKey protectedDataEncryptionKey; try { protectedDataEncryptionKey = this.encryptionSettings.buildProtectedDataEncryptionKey(keyProperties, this.encryptionKeyStoreProvider, clientEncryptionKeyId); } catch (Exception ex) { return Mono.error(ex); } EncryptionSettings encryptionSettings = new EncryptionSettings(); encryptionSettings.setDatabaseRid(this.databaseRid); encryptionSettings.setEncryptionSettingTimeToLive(Instant.now().plus(Duration.ofMinutes(Constants.CACHED_ENCRYPTION_SETTING_DEFAULT_DEFAULT_TTL_IN_MINUTES))); encryptionSettings.setClientEncryptionKeyId(clientEncryptionKeyId); encryptionSettings.setDataEncryptionKey(protectedDataEncryptionKey); settingsByDekId.put(clientEncryptionKeyId, encryptionSettings); return Mono.empty(); }).retryWhen(Retry.withThrowable((throwableFlux -> throwableFlux.flatMap(throwable -> { InvalidKeyException invalidKeyException = Utils.as(throwable, InvalidKeyException.class); if (invalidKeyException != null && !forceRefreshClientEncryptionKey.get()) { forceRefreshClientEncryptionKey.set(true); return Mono.delay(Duration.ZERO).flux(); } return Flux.error(throwable); })))); monoList.add(clientEncryptionPropertiesMono); }); sequentialList.set(Flux.mergeSequential(monoList).collectList()); return sequentialList.get().map(objects -> { return Mono.empty(); }); }).flatMap(ignoreVoid -> { for (ClientEncryptionIncludedPath propertyToEncrypt : clientEncryptionPolicy.getIncludedPaths()) { EncryptionType encryptionType = EncryptionType.Plaintext; switch (propertyToEncrypt.getEncryptionType()) { case CosmosEncryptionType.DETERMINISTIC: encryptionType = EncryptionType.Deterministic; break; case CosmosEncryptionType.RANDOMIZED: encryptionType = EncryptionType.Randomized; break; default: LOGGER.debug("Invalid encryption type {}", propertyToEncrypt.getEncryptionType()); break; } String propertyName = propertyToEncrypt.getPath().substring(1); try { this.encryptionSettings.setEncryptionSettingForProperty(propertyName, EncryptionSettings.create(settingsByDekId.get(propertyToEncrypt.getClientEncryptionKeyId()), encryptionType), settingsByDekId.get(propertyToEncrypt.getClientEncryptionKeyId()).getEncryptionSettingTimeToLive()); } catch (MicrosoftDataEncryptionException ex) { return Mono.error(ex); } } this.isEncryptionSettingsInitDone.set(true); return Mono.empty(); }); } public Mono<Void> initEncryptionSettingsIfNotInitializedAsync() { if (!this.isEncryptionSettingsInitDone.get()) { return initializeEncryptionSettingsAsync(false).then(Mono.empty()); } return Mono.empty(); } ClientEncryptionPolicy getClientEncryptionPolicy() { return clientEncryptionPolicy; } void setClientEncryptionPolicy(ClientEncryptionPolicy clientEncryptionPolicy) { this.clientEncryptionPolicy = clientEncryptionPolicy; } /** * Gets the container that has items which are to be encrypted. * * @return the CosmosContainer */ public CosmosAsyncContainer getCosmosAsyncContainer() { return this.cosmosAsyncContainer; } /** * Gets the encrypted cosmos client. * * @return encryptionCosmosClient */ public CosmosEncryptionAsyncClient getEncryptionCosmosClient() { return encryptionCosmosClient; } /** * Gets the provider that allows interaction with the master keys. * * @return encryptionKeyStoreProvider */ public EncryptionKeyStoreProvider getEncryptionKeyStoreProvider() { return encryptionKeyStoreProvider; } public EncryptionSettings getEncryptionSettings() { return encryptionSettings; } public Mono<byte[]> encrypt(byte[] payload) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypting byte[] of size [{}] on thread [{}]", payload == null ? null : payload.length, Thread.currentThread().getName()); } ObjectNode itemJObj = Utils.parse(payload, ObjectNode.class); assert (itemJObj != null); return initEncryptionSettingsIfNotInitializedAsync().then(Mono.defer(() -> { for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { if (StringUtils.isEmpty(includedPath.getPath()) || includedPath.getPath().charAt(0) != '/' || includedPath.getPath().lastIndexOf('/') != 0) { return Mono.error(new IllegalArgumentException("Invalid encryption path: " + includedPath.getPath())); } } List<Mono<Void>> encryptionMonoList = new ArrayList<>(); for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { String propertyName = includedPath.getPath().substring(1); JsonNode propertyValueHolder = itemJObj.get(propertyName); if (propertyValueHolder != null && !propertyValueHolder.isNull()) { Mono<Void> voidMono = this.encryptionSettings.getEncryptionSettingForPropertyAsync(propertyName, this).flatMap(settings -> { try { encryptAndSerializeProperty(settings, itemJObj, propertyValueHolder, propertyName); } catch (MicrosoftDataEncryptionException ex) { return Mono.error(ex); } return Mono.empty(); }); encryptionMonoList.add(voidMono); } } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionMonoList).collectList(); return listMono.flatMap(ignoreVoid -> Mono.just(EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), itemJObj))); })); } public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException { if (propertyValueHolder.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = propertyValueHolder.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { encryptAndSerializeValue(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), child.getKey()); } } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { for (Iterator<JsonNode> arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); } else { for (Iterator<Map.Entry<String, JsonNode>> it = nodeInArray.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { encryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), child.getKey()); } } } } } else { List<byte[]> encryptedArray = new ArrayList<>(); for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) { encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); } arrayNode.removeAll(); for (byte[] encryptedValue : encryptedArray) { arrayNode.add(encryptedValue); } } } else { encryptAndSerializeValue(encryptionSettings, objectNode, propertyValueHolder, propertyName); } } public byte[] encryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException { byte[] cipherText; byte[] cipherTextWithTypeMarker; Pair<TypeMarker, byte[]> typeMarkerPair = toByteArray(propertyValueHolder); cipherText = encryptionSettings.getAeadAes256CbcHmac256EncryptionAlgorithm().encrypt(typeMarkerPair.getRight()); cipherTextWithTypeMarker = new byte[cipherText.length + 1]; cipherTextWithTypeMarker[0] = (byte) typeMarkerPair.getLeft().getValue(); System.arraycopy(cipherText, 0, cipherTextWithTypeMarker, 1, cipherText.length); if (objectNode != null && !objectNode.isNull()) { objectNode.put(propertyName, cipherTextWithTypeMarker); } return cipherTextWithTypeMarker; } public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { if (propertyValueHolder.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = propertyValueHolder.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { decryptAndSerializeValue(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), child.getKey()); } } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { for (Iterator<JsonNode> arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); } else { for (Iterator<Map.Entry<String, JsonNode>> it = nodeInArray.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { decryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), child.getKey()); } } } } } else { List<JsonNode> decryptedArray = new ArrayList<>(); for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) { decryptedArray.add(decryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); } arrayNode.removeAll(); for (JsonNode encryptedValue : decryptedArray) { arrayNode.add(encryptedValue); } } } else { decryptAndSerializeValue(encryptionSettings, objectNode, propertyValueHolder, propertyName); } } public JsonNode decryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { byte[] cipherText; byte[] cipherTextWithTypeMarker; cipherTextWithTypeMarker = propertyValueHolder.binaryValue(); cipherText = new byte[cipherTextWithTypeMarker.length - 1]; System.arraycopy(cipherTextWithTypeMarker, 1, cipherText, 0, cipherTextWithTypeMarker.length - 1); byte[] plainText = encryptionSettings.getAeadAes256CbcHmac256EncryptionAlgorithm().decrypt(cipherText); if (objectNode != null && !objectNode.isNull()) { objectNode.set(propertyName, toJsonNode(plainText, TypeMarker.valueOf(cipherTextWithTypeMarker[0]).get())); } return toJsonNode(plainText, TypeMarker.valueOf(cipherTextWithTypeMarker[0]).get()); } public static Pair<TypeMarker, byte[]> toByteArray(JsonNode jsonNode) { try { SqlSerializerFactory sqlSerializerFactory = new SqlSerializerFactory(); switch (jsonNode.getNodeType()) { case BOOLEAN: return Pair.of(TypeMarker.BOOLEAN, sqlSerializerFactory.getDefaultSerializer(Boolean.class).serialize(jsonNode.asBoolean())); case NUMBER: if (jsonNode.isInt() || jsonNode.isLong()) { return Pair.of(TypeMarker.LONG, sqlSerializerFactory.getDefaultSerializer(Long.class).serialize(jsonNode.asLong())); } else if (jsonNode.isFloat() || jsonNode.isDouble()) { return Pair.of(TypeMarker.DOUBLE, sqlSerializerFactory.getDefaultSerializer(Double.class).serialize(jsonNode.asDouble())); } break; case STRING: return Pair.of(TypeMarker.STRING, SqlSerializerFactory.getOrCreate("varchar", -1, 0, 0, StandardCharsets.UTF_8.toString()).serialize(jsonNode.asText())); } } catch (MicrosoftDataEncryptionException ex) { throw BridgeInternal.createCosmosException("Unable to convert JSON to byte[]", ex, null, 0, null); } throw BridgeInternal.createCosmosException(0, "Invalid or Unsupported Data Type Passed " + jsonNode.getNodeType()); } public static JsonNode toJsonNode(byte[] serializedBytes, TypeMarker typeMarker) { try { SqlSerializerFactory sqlSerializerFactory = new SqlSerializerFactory(); switch (typeMarker) { case BOOLEAN: return BooleanNode.valueOf((boolean) sqlSerializerFactory.getDefaultSerializer(Boolean.class).deserialize(serializedBytes)); case LONG: return LongNode.valueOf((long) sqlSerializerFactory.getDefaultSerializer(Long.class).deserialize(serializedBytes)); case DOUBLE: return DoubleNode.valueOf((double) sqlSerializerFactory.getDefaultSerializer(Double.class).deserialize(serializedBytes)); case STRING: return TextNode.valueOf((String) SqlSerializerFactory.getOrCreate("varchar", -1, 0, 0, StandardCharsets.UTF_8.toString()).deserialize(serializedBytes)); } } catch (MicrosoftDataEncryptionException ex) { throw BridgeInternal.createCosmosException("Unable to convert byte[] to JSON", ex, null, 0, null); } throw BridgeInternal.createCosmosException(0, "Invalid or Unsupported Data Type Passed " + typeMarker); } public enum TypeMarker { NULL(1), BOOLEAN(2), DOUBLE(3), LONG(4), STRING(5); private final int value; public static Optional<TypeMarker> valueOf(int value) { return Arrays.stream(values()) .filter(legNo -> legNo.value == value) .findFirst(); } TypeMarker(int value) { this.value = value; } public int getValue() { return value; } } public String getContainerRid() { return containerRid; } public AtomicBoolean getIsEncryptionSettingsInitDone(){ return this.isEncryptionSettingsInitDone; } }
class EncryptionProcessor { private final static Logger LOGGER = LoggerFactory.getLogger(EncryptionProcessor.class); private CosmosEncryptionAsyncClient encryptionCosmosClient; private CosmosAsyncContainer cosmosAsyncContainer; private EncryptionKeyStoreProvider encryptionKeyStoreProvider; private EncryptionSettings encryptionSettings; private AtomicBoolean isEncryptionSettingsInitDone; private ClientEncryptionPolicy clientEncryptionPolicy; private String containerRid; private String databaseRid; private ImplementationBridgeHelpers.CosmosContainerPropertiesHelper.CosmosContainerPropertiesAccessor cosmosContainerPropertiesAccessor; public EncryptionProcessor(CosmosAsyncContainer cosmosAsyncContainer, CosmosEncryptionAsyncClient encryptionCosmosClient) { if (cosmosAsyncContainer == null) { throw new IllegalStateException("encryptionCosmosContainer is null"); } if (encryptionCosmosClient == null) { throw new IllegalStateException("encryptionCosmosClient is null"); } this.cosmosAsyncContainer = cosmosAsyncContainer; this.encryptionCosmosClient = encryptionCosmosClient; this.isEncryptionSettingsInitDone = new AtomicBoolean(false); this.encryptionKeyStoreProvider = this.encryptionCosmosClient.getEncryptionKeyStoreProvider(); this.cosmosContainerPropertiesAccessor = ImplementationBridgeHelpers.CosmosContainerPropertiesHelper.getCosmosContainerPropertiesAccessor(); this.encryptionSettings = new EncryptionSettings(); } /** * Builds up and caches the Encryption Setting by getting the cached entries of Client Encryption Policy and the * corresponding keys. * Sets up the MDE Algorithm for encryption and decryption by initializing the KeyEncryptionKey and * ProtectedDataEncryptionKey. * * @return Mono */ public Mono<Void> initializeEncryptionSettingsAsync(boolean isRetry) { if (this.isEncryptionSettingsInitDone.get()) { throw new IllegalStateException("The Encryption Processor has already been initialized. "); } Map<String, EncryptionSettings> settingsByDekId = new ConcurrentHashMap<>(); return EncryptionBridgeInternal.getContainerPropertiesMono(this.encryptionCosmosClient, this.cosmosAsyncContainer, isRetry).flatMap(cosmosContainerProperties -> { this.containerRid = cosmosContainerProperties.getResourceId(); this.databaseRid = cosmosContainerPropertiesAccessor.getSelfLink(cosmosContainerProperties).split("/")[1]; this.encryptionSettings.setDatabaseRid(this.databaseRid); if (cosmosContainerProperties.getClientEncryptionPolicy() == null) { this.isEncryptionSettingsInitDone.set(true); return Mono.empty(); } this.clientEncryptionPolicy = cosmosContainerProperties.getClientEncryptionPolicy(); AtomicReference<Mono<List<Object>>> sequentialList = new AtomicReference<>(); List<Mono<Object>> monoList = new ArrayList<>(); this.clientEncryptionPolicy.getIncludedPaths().stream() .map(clientEncryptionIncludedPath -> clientEncryptionIncludedPath.getClientEncryptionKeyId()).distinct().forEach(clientEncryptionKeyId -> { AtomicBoolean forceRefreshClientEncryptionKey = new AtomicBoolean(false); Mono<Object> clientEncryptionPropertiesMono = EncryptionBridgeInternal.getClientEncryptionPropertiesAsync(this.encryptionCosmosClient, clientEncryptionKeyId, this.databaseRid, this.cosmosAsyncContainer, forceRefreshClientEncryptionKey.get()) .publishOn(Schedulers.boundedElastic()) .flatMap(keyProperties -> { ProtectedDataEncryptionKey protectedDataEncryptionKey; try { protectedDataEncryptionKey = this.encryptionSettings.buildProtectedDataEncryptionKey(keyProperties, this.encryptionKeyStoreProvider, clientEncryptionKeyId); } catch (Exception ex) { return Mono.error(ex); } EncryptionSettings encryptionSettings = new EncryptionSettings(); encryptionSettings.setDatabaseRid(this.databaseRid); encryptionSettings.setEncryptionSettingTimeToLive(Instant.now().plus(Duration.ofMinutes(Constants.CACHED_ENCRYPTION_SETTING_DEFAULT_DEFAULT_TTL_IN_MINUTES))); encryptionSettings.setClientEncryptionKeyId(clientEncryptionKeyId); encryptionSettings.setDataEncryptionKey(protectedDataEncryptionKey); settingsByDekId.put(clientEncryptionKeyId, encryptionSettings); return Mono.empty(); }).retryWhen(Retry.withThrowable((throwableFlux -> throwableFlux.flatMap(throwable -> { InvalidKeyException invalidKeyException = Utils.as(throwable, InvalidKeyException.class); if (invalidKeyException != null && !forceRefreshClientEncryptionKey.get()) { forceRefreshClientEncryptionKey.set(true); return Mono.delay(Duration.ZERO).flux(); } return Flux.error(throwable); })))); monoList.add(clientEncryptionPropertiesMono); }); sequentialList.set(Flux.mergeSequential(monoList).collectList()); return sequentialList.get().map(objects -> { return Mono.empty(); }); }).flatMap(ignoreVoid -> { for (ClientEncryptionIncludedPath propertyToEncrypt : clientEncryptionPolicy.getIncludedPaths()) { EncryptionType encryptionType = EncryptionType.Plaintext; switch (propertyToEncrypt.getEncryptionType()) { case CosmosEncryptionType.DETERMINISTIC: encryptionType = EncryptionType.Deterministic; break; case CosmosEncryptionType.RANDOMIZED: encryptionType = EncryptionType.Randomized; break; default: LOGGER.debug("Invalid encryption type {}", propertyToEncrypt.getEncryptionType()); break; } String propertyName = propertyToEncrypt.getPath().substring(1); try { this.encryptionSettings.setEncryptionSettingForProperty(propertyName, EncryptionSettings.create(settingsByDekId.get(propertyToEncrypt.getClientEncryptionKeyId()), encryptionType), settingsByDekId.get(propertyToEncrypt.getClientEncryptionKeyId()).getEncryptionSettingTimeToLive()); } catch (MicrosoftDataEncryptionException ex) { return Mono.error(ex); } } this.isEncryptionSettingsInitDone.set(true); return Mono.empty(); }); } public Mono<Void> initEncryptionSettingsIfNotInitializedAsync() { if (!this.isEncryptionSettingsInitDone.get()) { return initializeEncryptionSettingsAsync(false).then(Mono.empty()); } return Mono.empty(); } ClientEncryptionPolicy getClientEncryptionPolicy() { return clientEncryptionPolicy; } void setClientEncryptionPolicy(ClientEncryptionPolicy clientEncryptionPolicy) { this.clientEncryptionPolicy = clientEncryptionPolicy; } /** * Gets the container that has items which are to be encrypted. * * @return the CosmosContainer */ public CosmosAsyncContainer getCosmosAsyncContainer() { return this.cosmosAsyncContainer; } /** * Gets the encrypted cosmos client. * * @return encryptionCosmosClient */ public CosmosEncryptionAsyncClient getEncryptionCosmosClient() { return encryptionCosmosClient; } /** * Gets the provider that allows interaction with the master keys. * * @return encryptionKeyStoreProvider */ public EncryptionKeyStoreProvider getEncryptionKeyStoreProvider() { return encryptionKeyStoreProvider; } public EncryptionSettings getEncryptionSettings() { return encryptionSettings; } public Mono<byte[]> encrypt(byte[] payload) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Encrypting byte[] of size [{}] on thread [{}]", payload == null ? null : payload.length, Thread.currentThread().getName()); } ObjectNode itemJObj = Utils.parse(payload, ObjectNode.class); assert (itemJObj != null); return initEncryptionSettingsIfNotInitializedAsync().then(Mono.defer(() -> { for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { if (StringUtils.isEmpty(includedPath.getPath()) || includedPath.getPath().charAt(0) != '/' || includedPath.getPath().lastIndexOf('/') != 0) { return Mono.error(new IllegalArgumentException("Invalid encryption path: " + includedPath.getPath())); } } List<Mono<Void>> encryptionMonoList = new ArrayList<>(); for (ClientEncryptionIncludedPath includedPath : this.clientEncryptionPolicy.getIncludedPaths()) { String propertyName = includedPath.getPath().substring(1); JsonNode propertyValueHolder = itemJObj.get(propertyName); if (propertyValueHolder != null && !propertyValueHolder.isNull()) { Mono<Void> voidMono = this.encryptionSettings.getEncryptionSettingForPropertyAsync(propertyName, this).flatMap(settings -> { try { encryptAndSerializeProperty(settings, itemJObj, propertyValueHolder, propertyName); } catch (MicrosoftDataEncryptionException ex) { return Mono.error(ex); } return Mono.empty(); }); encryptionMonoList.add(voidMono); } } Mono<List<Void>> listMono = Flux.mergeSequential(encryptionMonoList).collectList(); return listMono.flatMap(ignoreVoid -> Mono.just(EncryptionUtils.serializeJsonToByteArray(EncryptionUtils.getSimpleObjectMapper(), itemJObj))); })); } public void encryptAndSerializeProperty(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException { if (propertyValueHolder.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = propertyValueHolder.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { encryptAndSerializeValue(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), child.getKey()); } } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { for (Iterator<JsonNode> arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); } else { for (Iterator<Map.Entry<String, JsonNode>> it = nodeInArray.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { encryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { encryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), child.getKey()); } } } } } else { List<byte[]> encryptedArray = new ArrayList<>(); for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) { encryptedArray.add(encryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); } arrayNode.removeAll(); for (byte[] encryptedValue : encryptedArray) { arrayNode.add(encryptedValue); } } } else { encryptAndSerializeValue(encryptionSettings, objectNode, propertyValueHolder, propertyName); } } public byte[] encryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException { byte[] cipherText; byte[] cipherTextWithTypeMarker; Pair<TypeMarker, byte[]> typeMarkerPair = toByteArray(propertyValueHolder); cipherText = encryptionSettings.getAeadAes256CbcHmac256EncryptionAlgorithm().encrypt(typeMarkerPair.getRight()); cipherTextWithTypeMarker = new byte[cipherText.length + 1]; cipherTextWithTypeMarker[0] = (byte) typeMarkerPair.getLeft().getValue(); System.arraycopy(cipherText, 0, cipherTextWithTypeMarker, 1, cipherText.length); if (objectNode != null && !objectNode.isNull()) { objectNode.put(propertyName, cipherTextWithTypeMarker); } return cipherTextWithTypeMarker; } public void decryptAndSerializeProperty(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { if (propertyValueHolder.isObject()) { for (Iterator<Map.Entry<String, JsonNode>> it = propertyValueHolder.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { decryptAndSerializeValue(encryptionSettings, (ObjectNode) propertyValueHolder, child.getValue(), child.getKey()); } } } else if (propertyValueHolder.isArray()) { ArrayNode arrayNode = (ArrayNode) propertyValueHolder; if (arrayNode.elements().next().isObject() || arrayNode.elements().next().isArray()) { for (Iterator<JsonNode> arrayIterator = arrayNode.elements(); arrayIterator.hasNext(); ) { JsonNode nodeInArray = arrayIterator.next(); if (nodeInArray.isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) null, nodeInArray, StringUtils.EMPTY); } else { for (Iterator<Map.Entry<String, JsonNode>> it = nodeInArray.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> child = it.next(); if (child.getValue().isObject() || child.getValue().isArray()) { decryptAndSerializeProperty(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), propertyName); } else if (!child.getValue().isNull()) { decryptAndSerializeValue(encryptionSettings, (ObjectNode) nodeInArray, child.getValue(), child.getKey()); } } } } } else { List<JsonNode> decryptedArray = new ArrayList<>(); for (Iterator<JsonNode> it = arrayNode.elements(); it.hasNext(); ) { decryptedArray.add(decryptAndSerializeValue(encryptionSettings, null, it.next(), StringUtils.EMPTY)); } arrayNode.removeAll(); for (JsonNode encryptedValue : decryptedArray) { arrayNode.add(encryptedValue); } } } else { decryptAndSerializeValue(encryptionSettings, objectNode, propertyValueHolder, propertyName); } } public JsonNode decryptAndSerializeValue(EncryptionSettings encryptionSettings, ObjectNode objectNode, JsonNode propertyValueHolder, String propertyName) throws MicrosoftDataEncryptionException, IOException { byte[] cipherText; byte[] cipherTextWithTypeMarker; cipherTextWithTypeMarker = propertyValueHolder.binaryValue(); cipherText = new byte[cipherTextWithTypeMarker.length - 1]; System.arraycopy(cipherTextWithTypeMarker, 1, cipherText, 0, cipherTextWithTypeMarker.length - 1); byte[] plainText = encryptionSettings.getAeadAes256CbcHmac256EncryptionAlgorithm().decrypt(cipherText); if (objectNode != null && !objectNode.isNull()) { objectNode.set(propertyName, toJsonNode(plainText, TypeMarker.valueOf(cipherTextWithTypeMarker[0]).get())); } return toJsonNode(plainText, TypeMarker.valueOf(cipherTextWithTypeMarker[0]).get()); } public static Pair<TypeMarker, byte[]> toByteArray(JsonNode jsonNode) { try { SqlSerializerFactory sqlSerializerFactory = new SqlSerializerFactory(); switch (jsonNode.getNodeType()) { case BOOLEAN: return Pair.of(TypeMarker.BOOLEAN, sqlSerializerFactory.getDefaultSerializer(Boolean.class).serialize(jsonNode.asBoolean())); case NUMBER: if (jsonNode.isInt() || jsonNode.isLong()) { return Pair.of(TypeMarker.LONG, sqlSerializerFactory.getDefaultSerializer(Long.class).serialize(jsonNode.asLong())); } else if (jsonNode.isFloat() || jsonNode.isDouble()) { return Pair.of(TypeMarker.DOUBLE, sqlSerializerFactory.getDefaultSerializer(Double.class).serialize(jsonNode.asDouble())); } break; case STRING: return Pair.of(TypeMarker.STRING, SqlSerializerFactory.getOrCreate("varchar", -1, 0, 0, StandardCharsets.UTF_8.toString()).serialize(jsonNode.asText())); } } catch (MicrosoftDataEncryptionException ex) { throw BridgeInternal.createCosmosException("Unable to convert JSON to byte[]", ex, null, 0, null); } throw BridgeInternal.createCosmosException(0, "Invalid or Unsupported Data Type Passed " + jsonNode.getNodeType()); } public static JsonNode toJsonNode(byte[] serializedBytes, TypeMarker typeMarker) { try { SqlSerializerFactory sqlSerializerFactory = new SqlSerializerFactory(); switch (typeMarker) { case BOOLEAN: return BooleanNode.valueOf((boolean) sqlSerializerFactory.getDefaultSerializer(Boolean.class).deserialize(serializedBytes)); case LONG: return LongNode.valueOf((long) sqlSerializerFactory.getDefaultSerializer(Long.class).deserialize(serializedBytes)); case DOUBLE: return DoubleNode.valueOf((double) sqlSerializerFactory.getDefaultSerializer(Double.class).deserialize(serializedBytes)); case STRING: return TextNode.valueOf((String) SqlSerializerFactory.getOrCreate("varchar", -1, 0, 0, StandardCharsets.UTF_8.toString()).deserialize(serializedBytes)); } } catch (MicrosoftDataEncryptionException ex) { throw BridgeInternal.createCosmosException("Unable to convert byte[] to JSON", ex, null, 0, null); } throw BridgeInternal.createCosmosException(0, "Invalid or Unsupported Data Type Passed " + typeMarker); } public enum TypeMarker { NULL(1), BOOLEAN(2), DOUBLE(3), LONG(4), STRING(5); private final int value; public static Optional<TypeMarker> valueOf(int value) { return Arrays.stream(values()) .filter(legNo -> legNo.value == value) .findFirst(); } TypeMarker(int value) { this.value = value; } public int getValue() { return value; } } public String getContainerRid() { return containerRid; } public AtomicBoolean getIsEncryptionSettingsInitDone(){ return this.isEncryptionSettingsInitDone; } }
done
public void createItemEncryptWithContentResponseOnWriteEnabledFalse() { CosmosAsyncClient asyncClient = null ; try { asyncClient = new CosmosClientBuilder().endpoint(TestConfigurations.HOST).key(TestConfigurations.MASTER_KEY).buildAsyncClient(); CosmosEncryptionAsyncClient encryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(asyncClient, this.encryptionKeyStoreProvider); CosmosEncryptionAsyncContainer encryptionAsyncContainer = encryptionAsyncClient.getCosmosEncryptionAsyncDatabase(cosmosAsyncDatabase.getId()).getCosmosEncryptionAsyncContainer(containerId); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = encryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); assertThat(itemResponse.getItem()).isNull(); } finally { safeClose(asyncClient); } }
asyncClient =
public void createItemEncryptWithContentResponseOnWriteEnabledFalse() { CosmosItemRequestOptions requestOptions = new CosmosItemRequestOptions(); requestOptions.setContentResponseOnWriteEnabled(false); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), requestOptions).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); assertThat(itemResponse.getItem()).isNull(); }
class EncryptionAsyncApiCrudTest extends TestSuiteBase { private CosmosAsyncClient client; private CosmosAsyncDatabase cosmosAsyncDatabase; private static final int TIMEOUT = 6000_000; private CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient; private CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase; private CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer; private CosmosEncryptionAsyncContainer encryptionContainerWithIncompatiblePolicyVersion; private EncryptionKeyWrapMetadata metadata1; private EncryptionKeyWrapMetadata metadata2; private EncryptionKeyStoreProvider encryptionKeyStoreProvider; private String containerId; @Factory(dataProvider = "clientBuilders") public EncryptionAsyncApiCrudTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"encryption"}, timeOut = SETUP_TIMEOUT) public void before_CosmosItemTest() { assertThat(this.client).isNull(); this.client = getClientBuilder().buildAsyncClient(); encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); cosmosAsyncDatabase = getSharedCosmosDatabase(this.client); cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(this.client, encryptionKeyStoreProvider); cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(cosmosAsyncDatabase); metadata1 = new EncryptionKeyWrapMetadata(encryptionKeyStoreProvider.getProviderName(), "key1", "tempmetadata1"); metadata2 = new EncryptionKeyWrapMetadata(encryptionKeyStoreProvider.getProviderName(), "key2", "tempmetadata2"); cosmosEncryptionAsyncDatabase.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata1).block(); cosmosEncryptionAsyncDatabase.createClientEncryptionKey("key2", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata2).block(); ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(getPaths()); containerId = UUID.randomUUID().toString(); CosmosContainerProperties properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionPolicy); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); ClientEncryptionPolicy clientEncryptionWithPolicyFormatVersion2 = new ClientEncryptionPolicy(getPaths()); ReflectionUtils.setPolicyFormatVersion(clientEncryptionWithPolicyFormatVersion2, 2); containerId = UUID.randomUUID().toString(); properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionWithPolicyFormatVersion2); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); encryptionContainerWithIncompatiblePolicyVersion = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); } @AfterClass(groups = {"encryption"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.client).isNotNull(); this.client.close(); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void createItemEncrypt_readItemDecrypt() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); EncryptionPojo readItem = cosmosEncryptionAsyncContainer.readItem(properties.getId(), new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(properties, readItem); properties = getItem(UUID.randomUUID().toString()); String longString = ""; for (int i = 0; i < 10000; i++) { longString += "a"; } properties.setSensitiveString(longString); itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void upsertItem_readItem() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.upsertItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); EncryptionPojo readItem = cosmosEncryptionAsyncContainer.readItem(properties.getId(), new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(properties, readItem); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItems() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItems(querySpec, cosmosQueryRequestOptions, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(properties.getId())) { validateResponse(pojo, responseItem); } } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsOnEncryptedProperties() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveLong = @sensitiveLong"); SqlQuerySpec querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", properties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", properties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveLong", properties.getSensitiveLong()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveLong", parameter3); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, cosmosQueryRequestOptions, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(properties.getId())) { validateResponse(pojo, responseItem); } } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsOnRandomizedEncryption() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveDouble = @sensitiveDouble"); SqlQuerySpec querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", properties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", properties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveDouble", properties.getSensitiveDouble()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveDouble", parameter3); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, cosmosQueryRequestOptions, EncryptionPojo.class); try { List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); fail("Query on randomized parameter should fail"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage()).contains("Path /sensitiveDouble cannot be used in the " + "query because of randomized encryption"); } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsWithContinuationTokenAndPageSize() { List<String> actualIds = new ArrayList<>(); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); String query = String.format("SELECT * from c where c.id in ('%s', '%s', '%s')", actualIds.get(0), actualIds.get(1), actualIds.get(2)); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItems(query, cosmosQueryRequestOptions, EncryptionPojo.class); do { Iterable<FeedResponse<EncryptionPojo>> feedResponseIterable = feedResponseIterator.byPage(continuationToken, 1).toIterable(); for (FeedResponse<EncryptionPojo> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while (continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } @Ignore("Ignoring it temporarily because server always returning policyFormatVersion 0") @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void incompatiblePolicyFormatVersion() { try { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); encryptionContainerWithIncompatiblePolicyVersion.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); fail("encryptionContainerWithIncompatiblePolicyVersion crud operation should fail on client encryption " + "policy " + "fetch because of policy format version greater than 1"); } catch (UnsupportedOperationException ex) { assertThat(ex.getMessage()).isEqualTo("This version of the Encryption library cannot be used with this " + "container. Please upgrade to the latest version of the same."); } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void crudQueryStaleCache() { String databaseId = UUID.randomUUID().toString(); try { createNewDatabaseWithClientEncryptionKey(databaseId); CosmosAsyncClient asyncClient = getClientBuilder().buildAsyncClient(); EncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(asyncClient, encryptionKeyStoreProvider); CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(asyncClient.getDatabase(databaseId)); String containerId = UUID.randomUUID().toString(); ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(getPaths()); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer encryptionAsyncContainerOriginal = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); EncryptionPojo encryptionPojo = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> createResponse = encryptionAsyncContainerOriginal.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); validateResponse(encryptionPojo, createResponse.getItem()); String query = String.format("SELECT * from c where c.id = '%s'", encryptionPojo.getId()); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = encryptionAsyncContainerOriginal.queryItems(querySpec, null, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); EncryptionPojo readItem = encryptionAsyncContainerOriginal.readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(encryptionPojo, readItem); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().delete().block(); createNewDatabaseWithClientEncryptionKey(databaseId); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); createResponse = encryptionAsyncContainerOriginal.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); validateResponse(encryptionPojo, createResponse.getItem()); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); ClientEncryptionPolicy policyWithOneEncryptionPolicy = new ClientEncryptionPolicy(getPathWithOneEncryptionField()); createEncryptionContainer(cosmosEncryptionAsyncDatabase, policyWithOneEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer encryptionAsyncContainerNew = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); encryptionAsyncContainerNew.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); EncryptionPojo pojoWithOneFieldEncrypted = encryptionAsyncContainerNew.getCosmosAsyncContainer().readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponseWithOneFieldEncryption(encryptionPojo, pojoWithOneFieldEncrypted); readItem = encryptionAsyncContainerOriginal.readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(encryptionPojo, readItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosItemResponse<EncryptionPojo> upsertResponse = encryptionAsyncContainerOriginal.upsertItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = upsertResponse.getItem(); validateResponse(encryptionPojo, responseItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); encryptionAsyncContainerNew = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); encryptionAsyncContainerNew.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); CosmosItemResponse<EncryptionPojo> replaceResponse = encryptionAsyncContainerOriginal.replaceItem(encryptionPojo, encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); responseItem = replaceResponse.getItem(); validateResponse(encryptionPojo, responseItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer newEncryptionAsyncContainer = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); for (int i = 0; i < 10; i++) { EncryptionPojo pojo = getItem(UUID.randomUUID().toString()); newEncryptionAsyncContainer.createItem(pojo, new PartitionKey(pojo.getMypk()), new CosmosItemRequestOptions()).block(); } feedResponseIterator = encryptionAsyncContainerOriginal.queryItems("Select * from C", null, EncryptionPojo.class); String continuationToken = null; int pageSize = 3; int finalDocumentCount = 0; do { Iterable<FeedResponse<EncryptionPojo>> feedResponseIterable = feedResponseIterator.byPage(continuationToken, pageSize).toIterable(); for (FeedResponse<EncryptionPojo> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isLessThanOrEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while (continuationToken != null); assertThat(finalDocumentCount).isEqualTo(10); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); newEncryptionAsyncContainer = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); EncryptionPojo encryptionPojoForQueryItemsOnEncryptedProperties = getItem(UUID.randomUUID().toString()); newEncryptionAsyncContainer.createItem(encryptionPojoForQueryItemsOnEncryptedProperties, new PartitionKey(encryptionPojoForQueryItemsOnEncryptedProperties.getMypk()), new CosmosItemRequestOptions()).block(); query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveLong = @sensitiveLong"); querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", encryptionPojoForQueryItemsOnEncryptedProperties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", encryptionPojoForQueryItemsOnEncryptedProperties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveLong", encryptionPojoForQueryItemsOnEncryptedProperties.getSensitiveLong()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveLong", parameter3); feedResponseIterator = encryptionAsyncContainerOriginal.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, null, EncryptionPojo.class); feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(encryptionPojoForQueryItemsOnEncryptedProperties.getId())) { validateResponse(encryptionPojoForQueryItemsOnEncryptedProperties, pojo); } } } finally { try { this.client.getDatabase(databaseId).delete().block(); } catch(Exception ex) { } } } static void validateResponse(EncryptionPojo originalItem, EncryptionPojo result) { assertThat(result.getId()).isEqualTo(originalItem.getId()); assertThat(result.getNonSensitive()).isEqualTo(originalItem.getNonSensitive()); assertThat(result.getSensitiveString()).isEqualTo(originalItem.getSensitiveString()); assertThat(result.getSensitiveInt()).isEqualTo(originalItem.getSensitiveInt()); assertThat(result.getSensitiveFloat()).isEqualTo(originalItem.getSensitiveFloat()); assertThat(result.getSensitiveLong()).isEqualTo(originalItem.getSensitiveLong()); assertThat(result.getSensitiveDouble()).isEqualTo(originalItem.getSensitiveDouble()); assertThat(result.isSensitiveBoolean()).isEqualTo(originalItem.isSensitiveBoolean()); assertThat(result.getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveIntArray()); assertThat(result.getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveStringArray()); assertThat(result.getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveString3DArray()); assertThat(result.getSensitiveNestedPojo().getId()).isEqualTo(originalItem.getSensitiveNestedPojo().getId()); assertThat(result.getSensitiveNestedPojo().getMypk()).isEqualTo(originalItem.getSensitiveNestedPojo().getMypk()); assertThat(result.getSensitiveNestedPojo().getNonSensitive()).isEqualTo(originalItem.getSensitiveNestedPojo().getNonSensitive()); assertThat(result.getSensitiveNestedPojo().getSensitiveString()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveString()); assertThat(result.getSensitiveNestedPojo().getSensitiveInt()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveInt()); assertThat(result.getSensitiveNestedPojo().getSensitiveFloat()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveFloat()); assertThat(result.getSensitiveNestedPojo().getSensitiveLong()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveLong()); assertThat(result.getSensitiveNestedPojo().getSensitiveDouble()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveDouble()); assertThat(result.getSensitiveNestedPojo().isSensitiveBoolean()).isEqualTo(originalItem.getSensitiveNestedPojo().isSensitiveBoolean()); assertThat(result.getSensitiveNestedPojo().getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveIntArray()); assertThat(result.getSensitiveNestedPojo().getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveStringArray()); assertThat(result.getSensitiveNestedPojo().getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveString3DArray()); assertThat(result.getSensitiveChildPojoList().size()).isEqualTo(originalItem.getSensitiveChildPojoList().size()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveString()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveString()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveInt()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveInt()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveFloat()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveFloat()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveLong()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveLong()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveDouble()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveDouble()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveIntArray()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveStringArray()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveString3DArray()); assertThat(result.getSensitiveChildPojo2DArray().length).isEqualTo(originalItem.getSensitiveChildPojo2DArray().length); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveString()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveString()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveInt()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveInt()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveFloat()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveFloat()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveLong()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveLong()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveDouble()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveDouble()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveIntArray()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveStringArray()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveString3DArray()); } static void validateResponseWithOneFieldEncryption(EncryptionPojo originalItem, EncryptionPojo result) { assertThat(result.getId()).isEqualTo(originalItem.getId()); assertThat(result.getNonSensitive()).isEqualTo(originalItem.getNonSensitive()); assertThat(result.getSensitiveString()).isNotEqualTo(originalItem.getSensitiveString()); assertThat(result.getSensitiveInt()).isEqualTo(originalItem.getSensitiveInt()); assertThat(result.getSensitiveFloat()).isEqualTo(originalItem.getSensitiveFloat()); assertThat(result.getSensitiveLong()).isEqualTo(originalItem.getSensitiveLong()); assertThat(result.getSensitiveDouble()).isEqualTo(originalItem.getSensitiveDouble()); assertThat(result.isSensitiveBoolean()).isEqualTo(originalItem.isSensitiveBoolean()); assertThat(result.getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveIntArray()); assertThat(result.getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveStringArray()); assertThat(result.getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveString3DArray()); } public static EncryptionPojo getItem(String documentId) { EncryptionPojo pojo = new EncryptionPojo(); pojo.setId(documentId); pojo.setMypk(documentId); pojo.setNonSensitive(UUID.randomUUID().toString()); pojo.setSensitiveString("testingString"); pojo.setSensitiveDouble(10.123); pojo.setSensitiveFloat(20.0f); pojo.setSensitiveInt(30); pojo.setSensitiveLong(1234); pojo.setSensitiveBoolean(true); EncryptionPojo nestedPojo = new EncryptionPojo(); nestedPojo.setId("nestedPojo"); nestedPojo.setMypk("nestedPojo"); nestedPojo.setSensitiveString("nestedPojo"); nestedPojo.setSensitiveDouble(10.123); nestedPojo.setSensitiveInt(123); nestedPojo.setSensitiveLong(1234); nestedPojo.setSensitiveStringArray(new String[]{"str1", "str1"}); nestedPojo.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); nestedPojo.setSensitiveBoolean(true); pojo.setSensitiveNestedPojo(nestedPojo); pojo.setSensitiveIntArray(new int[]{1, 2}); pojo.setSensitiveStringArray(new String[]{"str1", "str1"}); pojo.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); EncryptionPojo childPojo1 = new EncryptionPojo(); childPojo1.setId("childPojo1"); childPojo1.setSensitiveString("child1TestingString"); childPojo1.setSensitiveDouble(10.123); childPojo1.setSensitiveInt(123); childPojo1.setSensitiveLong(1234); childPojo1.setSensitiveBoolean(true); childPojo1.setSensitiveStringArray(new String[]{"str1", "str1"}); childPojo1.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); EncryptionPojo childPojo2 = new EncryptionPojo(); childPojo2.setId("childPojo2"); childPojo2.setSensitiveString("child2TestingString"); childPojo2.setSensitiveDouble(10.123); childPojo2.setSensitiveInt(123); childPojo2.setSensitiveLong(1234); childPojo2.setSensitiveBoolean(true); pojo.setSensitiveChildPojoList(new ArrayList<>()); pojo.getSensitiveChildPojoList().add(childPojo1); pojo.getSensitiveChildPojoList().add(childPojo2); pojo.setSensitiveChildPojo2DArray(new EncryptionPojo[][]{{childPojo1, childPojo2}, {childPojo1, childPojo2}}); return pojo; } public static class TestEncryptionKeyStoreProvider extends EncryptionKeyStoreProvider { Map<String, Integer> keyInfo = new HashMap<>(); String providerName = "TEST_KEY_STORE_PROVIDER"; @Override public String getProviderName() { return providerName; } public TestEncryptionKeyStoreProvider() { keyInfo.put("tempmetadata1", 1); keyInfo.put("tempmetadata2", 2); } @Override public byte[] unwrapKey(String s, KeyEncryptionKeyAlgorithm keyEncryptionKeyAlgorithm, byte[] encryptedBytes) { int moveBy = this.keyInfo.get(s); byte[] plainkey = new byte[encryptedBytes.length]; for (int i = 0; i < encryptedBytes.length; i++) { plainkey[i] = (byte) (encryptedBytes[i] - moveBy); } return plainkey; } @Override public byte[] wrapKey(String s, KeyEncryptionKeyAlgorithm keyEncryptionKeyAlgorithm, byte[] key) { int moveBy = this.keyInfo.get(s); byte[] encryptedBytes = new byte[key.length]; for (int i = 0; i < key.length; i++) { encryptedBytes[i] = (byte) (key[i] + moveBy); } return encryptedBytes; } @Override public byte[] sign(String s, boolean b) { return new byte[0]; } @Override public boolean verify(String s, boolean b, byte[] bytes) { return true; } } public static List<ClientEncryptionIncludedPath> getPaths() { ClientEncryptionIncludedPath includedPath1 = new ClientEncryptionIncludedPath(); includedPath1.setClientEncryptionKeyId("key1"); includedPath1.setPath("/sensitiveString"); includedPath1.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath1.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath2 = new ClientEncryptionIncludedPath(); includedPath2.setClientEncryptionKeyId("key2"); includedPath2.setPath("/nonValidPath"); includedPath2.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath2.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath3 = new ClientEncryptionIncludedPath(); includedPath3.setClientEncryptionKeyId("key1"); includedPath3.setPath("/sensitiveInt"); includedPath3.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath3.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath4 = new ClientEncryptionIncludedPath(); includedPath4.setClientEncryptionKeyId("key2"); includedPath4.setPath("/sensitiveFloat"); includedPath4.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath4.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath5 = new ClientEncryptionIncludedPath(); includedPath5.setClientEncryptionKeyId("key1"); includedPath5.setPath("/sensitiveLong"); includedPath5.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath5.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath6 = new ClientEncryptionIncludedPath(); includedPath6.setClientEncryptionKeyId("key2"); includedPath6.setPath("/sensitiveDouble"); includedPath6.setEncryptionType(CosmosEncryptionType.RANDOMIZED); includedPath6.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath7 = new ClientEncryptionIncludedPath(); includedPath7.setClientEncryptionKeyId("key1"); includedPath7.setPath("/sensitiveBoolean"); includedPath7.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath7.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath8 = new ClientEncryptionIncludedPath(); includedPath8.setClientEncryptionKeyId("key1"); includedPath8.setPath("/sensitiveNestedPojo"); includedPath8.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath8.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath9 = new ClientEncryptionIncludedPath(); includedPath9.setClientEncryptionKeyId("key1"); includedPath9.setPath("/sensitiveIntArray"); includedPath9.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath9.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath10 = new ClientEncryptionIncludedPath(); includedPath10.setClientEncryptionKeyId("key2"); includedPath10.setPath("/sensitiveString3DArray"); includedPath10.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath10.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath11 = new ClientEncryptionIncludedPath(); includedPath11.setClientEncryptionKeyId("key1"); includedPath11.setPath("/sensitiveStringArray"); includedPath11.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath11.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath12 = new ClientEncryptionIncludedPath(); includedPath12.setClientEncryptionKeyId("key1"); includedPath12.setPath("/sensitiveChildPojoList"); includedPath12.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath12.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath13 = new ClientEncryptionIncludedPath(); includedPath13.setClientEncryptionKeyId("key1"); includedPath13.setPath("/sensitiveChildPojo2DArray"); includedPath13.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath13.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); List<ClientEncryptionIncludedPath> paths = new ArrayList<>(); paths.add(includedPath1); paths.add(includedPath2); paths.add(includedPath3); paths.add(includedPath4); paths.add(includedPath5); paths.add(includedPath6); paths.add(includedPath7); paths.add(includedPath8); paths.add(includedPath9); paths.add(includedPath10); paths.add(includedPath11); paths.add(includedPath12); paths.add(includedPath13); return paths; } public static List<ClientEncryptionIncludedPath> getPathWithOneEncryptionField() { ClientEncryptionIncludedPath includedPath = new ClientEncryptionIncludedPath(); includedPath.setClientEncryptionKeyId("key1"); includedPath.setPath("/sensitiveString"); includedPath.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); List<ClientEncryptionIncludedPath> paths = new ArrayList<>(); paths.add(includedPath); return paths; } private void createEncryptionContainer(CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase, ClientEncryptionPolicy clientEncryptionPolicy, String containerId) { CosmosContainerProperties properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionPolicy); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); } private void createNewDatabaseWithClientEncryptionKey(String databaseId){ cosmosEncryptionAsyncClient.getCosmosAsyncClient().createDatabase(databaseId).block(); CosmosEncryptionAsyncDatabase encryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(databaseId); encryptionAsyncDatabase.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata1).block(); encryptionAsyncDatabase.createClientEncryptionKey("key2", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata2).block(); } private CosmosEncryptionAsyncContainer getNewEncryptionContainerProxyObject(String databaseId, String containerId) { CosmosAsyncClient client = getClientBuilder().buildAsyncClient(); EncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(client, encryptionKeyStoreProvider); CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(client.getDatabase(databaseId)); CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); return cosmosEncryptionAsyncContainer; } }
class EncryptionAsyncApiCrudTest extends TestSuiteBase { private CosmosAsyncClient client; private CosmosAsyncDatabase cosmosAsyncDatabase; private static final int TIMEOUT = 6000_000; private CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient; private CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase; private CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer; private CosmosEncryptionAsyncContainer encryptionContainerWithIncompatiblePolicyVersion; private EncryptionKeyWrapMetadata metadata1; private EncryptionKeyWrapMetadata metadata2; @Factory(dataProvider = "clientBuilders") public EncryptionAsyncApiCrudTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"encryption"}, timeOut = SETUP_TIMEOUT) public void before_CosmosItemTest() { assertThat(this.client).isNull(); this.client = getClientBuilder().buildAsyncClient(); TestEncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); cosmosAsyncDatabase = getSharedCosmosDatabase(this.client); cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(this.client, encryptionKeyStoreProvider); cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(cosmosAsyncDatabase); metadata1 = new EncryptionKeyWrapMetadata(encryptionKeyStoreProvider.getProviderName(), "key1", "tempmetadata1"); metadata2 = new EncryptionKeyWrapMetadata(encryptionKeyStoreProvider.getProviderName(), "key2", "tempmetadata2"); cosmosEncryptionAsyncDatabase.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata1).block(); cosmosEncryptionAsyncDatabase.createClientEncryptionKey("key2", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata2).block(); ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(getPaths()); String containerId = UUID.randomUUID().toString(); CosmosContainerProperties properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionPolicy); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); ClientEncryptionPolicy clientEncryptionWithPolicyFormatVersion2 = new ClientEncryptionPolicy(getPaths()); ReflectionUtils.setPolicyFormatVersion(clientEncryptionWithPolicyFormatVersion2, 2); containerId = UUID.randomUUID().toString(); properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionWithPolicyFormatVersion2); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); encryptionContainerWithIncompatiblePolicyVersion = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); } @AfterClass(groups = {"encryption"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.client).isNotNull(); this.client.close(); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void createItemEncrypt_readItemDecrypt() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); EncryptionPojo readItem = cosmosEncryptionAsyncContainer.readItem(properties.getId(), new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(properties, readItem); properties = getItem(UUID.randomUUID().toString()); String longString = ""; for (int i = 0; i < 10000; i++) { longString += "a"; } properties.setSensitiveString(longString); itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void upsertItem_readItem() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.upsertItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); EncryptionPojo readItem = cosmosEncryptionAsyncContainer.readItem(properties.getId(), new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(properties, readItem); } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItems() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItems(querySpec, cosmosQueryRequestOptions, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(properties.getId())) { validateResponse(pojo, responseItem); } } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsOnEncryptedProperties() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveLong = @sensitiveLong"); SqlQuerySpec querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", properties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", properties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveLong", properties.getSensitiveLong()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveLong", parameter3); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, cosmosQueryRequestOptions, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(properties.getId())) { validateResponse(pojo, responseItem); } } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsOnRandomizedEncryption() { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> itemResponse = cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(itemResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = itemResponse.getItem(); validateResponse(properties, responseItem); String query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveDouble = @sensitiveDouble"); SqlQuerySpec querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", properties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", properties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveDouble", properties.getSensitiveDouble()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveDouble", parameter3); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, cosmosQueryRequestOptions, EncryptionPojo.class); try { List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); fail("Query on randomized parameter should fail"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage()).contains("Path /sensitiveDouble cannot be used in the " + "query because of randomized encryption"); } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void queryItemsWithContinuationTokenAndPageSize() { List<String> actualIds = new ArrayList<>(); EncryptionPojo properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); properties = getItem(UUID.randomUUID().toString()); cosmosEncryptionAsyncContainer.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); actualIds.add(properties.getId()); String query = String.format("SELECT * from c where c.id in ('%s', '%s', '%s')", actualIds.get(0), actualIds.get(1), actualIds.get(2)); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); String continuationToken = null; int pageSize = 1; int initialDocumentCount = 3; int finalDocumentCount = 0; CosmosPagedFlux<EncryptionPojo> feedResponseIterator = cosmosEncryptionAsyncContainer.queryItems(query, cosmosQueryRequestOptions, EncryptionPojo.class); do { Iterable<FeedResponse<EncryptionPojo>> feedResponseIterable = feedResponseIterator.byPage(continuationToken, 1).toIterable(); for (FeedResponse<EncryptionPojo> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while (continuationToken != null); assertThat(finalDocumentCount).isEqualTo(initialDocumentCount); } @Ignore("Ignoring it temporarily because server always returning policyFormatVersion 0") @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void incompatiblePolicyFormatVersion() { try { EncryptionPojo properties = getItem(UUID.randomUUID().toString()); encryptionContainerWithIncompatiblePolicyVersion.createItem(properties, new PartitionKey(properties.getMypk()), new CosmosItemRequestOptions()).block(); fail("encryptionContainerWithIncompatiblePolicyVersion crud operation should fail on client encryption " + "policy " + "fetch because of policy format version greater than 1"); } catch (UnsupportedOperationException ex) { assertThat(ex.getMessage()).isEqualTo("This version of the Encryption library cannot be used with this " + "container. Please upgrade to the latest version of the same."); } } @Test(groups = {"encryption"}, timeOut = TIMEOUT) public void crudQueryStaleCache() { String databaseId = UUID.randomUUID().toString(); try { createNewDatabaseWithClientEncryptionKey(databaseId); CosmosAsyncClient asyncClient = getClientBuilder().buildAsyncClient(); EncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(asyncClient, encryptionKeyStoreProvider); CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(asyncClient.getDatabase(databaseId)); String containerId = UUID.randomUUID().toString(); ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(getPaths()); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer encryptionAsyncContainerOriginal = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); EncryptionPojo encryptionPojo = getItem(UUID.randomUUID().toString()); CosmosItemResponse<EncryptionPojo> createResponse = encryptionAsyncContainerOriginal.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); validateResponse(encryptionPojo, createResponse.getItem()); String query = String.format("SELECT * from c where c.id = '%s'", encryptionPojo.getId()); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedFlux<EncryptionPojo> feedResponseIterator = encryptionAsyncContainerOriginal.queryItems(querySpec, null, EncryptionPojo.class); List<EncryptionPojo> feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); EncryptionPojo readItem = encryptionAsyncContainerOriginal.readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(encryptionPojo, readItem); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().delete().block(); createNewDatabaseWithClientEncryptionKey(databaseId); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); createResponse = encryptionAsyncContainerOriginal.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); validateResponse(encryptionPojo, createResponse.getItem()); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); ClientEncryptionPolicy policyWithOneEncryptionPolicy = new ClientEncryptionPolicy(getPathWithOneEncryptionField()); createEncryptionContainer(cosmosEncryptionAsyncDatabase, policyWithOneEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer encryptionAsyncContainerNew = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); encryptionAsyncContainerNew.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); EncryptionPojo pojoWithOneFieldEncrypted = encryptionAsyncContainerNew.getCosmosAsyncContainer().readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponseWithOneFieldEncryption(encryptionPojo, pojoWithOneFieldEncrypted); readItem = encryptionAsyncContainerOriginal.readItem(encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions(), EncryptionPojo.class).block().getItem(); validateResponse(encryptionPojo, readItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosItemResponse<EncryptionPojo> upsertResponse = encryptionAsyncContainerOriginal.upsertItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); EncryptionPojo responseItem = upsertResponse.getItem(); validateResponse(encryptionPojo, responseItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); encryptionAsyncContainerNew = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); encryptionAsyncContainerNew.createItem(encryptionPojo, new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); CosmosItemResponse<EncryptionPojo> replaceResponse = encryptionAsyncContainerOriginal.replaceItem(encryptionPojo, encryptionPojo.getId(), new PartitionKey(encryptionPojo.getMypk()), new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); responseItem = replaceResponse.getItem(); validateResponse(encryptionPojo, responseItem); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); CosmosEncryptionAsyncContainer newEncryptionAsyncContainer = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); for (int i = 0; i < 10; i++) { EncryptionPojo pojo = getItem(UUID.randomUUID().toString()); newEncryptionAsyncContainer.createItem(pojo, new PartitionKey(pojo.getMypk()), new CosmosItemRequestOptions()).block(); } feedResponseIterator = encryptionAsyncContainerOriginal.queryItems("Select * from C", null, EncryptionPojo.class); String continuationToken = null; int pageSize = 3; int finalDocumentCount = 0; do { Iterable<FeedResponse<EncryptionPojo>> feedResponseIterable = feedResponseIterator.byPage(continuationToken, pageSize).toIterable(); for (FeedResponse<EncryptionPojo> fr : feedResponseIterable) { int resultSize = fr.getResults().size(); assertThat(resultSize).isLessThanOrEqualTo(pageSize); finalDocumentCount += fr.getResults().size(); continuationToken = fr.getContinuationToken(); } } while (continuationToken != null); assertThat(finalDocumentCount).isEqualTo(10); encryptionAsyncContainerOriginal.getCosmosAsyncContainer().delete().block(); createEncryptionContainer(cosmosEncryptionAsyncDatabase, clientEncryptionPolicy, containerId); newEncryptionAsyncContainer = getNewEncryptionContainerProxyObject(cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().getId(), containerId); EncryptionPojo encryptionPojoForQueryItemsOnEncryptedProperties = getItem(UUID.randomUUID().toString()); newEncryptionAsyncContainer.createItem(encryptionPojoForQueryItemsOnEncryptedProperties, new PartitionKey(encryptionPojoForQueryItemsOnEncryptedProperties.getMypk()), new CosmosItemRequestOptions()).block(); query = String.format("SELECT * FROM c where c.sensitiveString = @sensitiveString and c.nonSensitive =" + " " + "@nonSensitive and c.sensitiveLong = @sensitiveLong"); querySpec = new SqlQuerySpec(query); SqlParameter parameter1 = new SqlParameter("@nonSensitive", encryptionPojoForQueryItemsOnEncryptedProperties.getNonSensitive()); querySpec.getParameters().add(parameter1); SqlParameter parameter2 = new SqlParameter("@sensitiveString", encryptionPojoForQueryItemsOnEncryptedProperties.getSensitiveString()); SqlParameter parameter3 = new SqlParameter("@sensitiveLong", encryptionPojoForQueryItemsOnEncryptedProperties.getSensitiveLong()); SqlQuerySpecWithEncryption sqlQuerySpecWithEncryption = new SqlQuerySpecWithEncryption(querySpec); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveString", parameter2); sqlQuerySpecWithEncryption.addEncryptionParameter("/sensitiveLong", parameter3); feedResponseIterator = encryptionAsyncContainerOriginal.queryItemsOnEncryptedProperties(sqlQuerySpecWithEncryption, null, EncryptionPojo.class); feedResponse = feedResponseIterator.byPage().blockFirst().getResults(); assertThat(feedResponse.size()).isGreaterThanOrEqualTo(1); for (EncryptionPojo pojo : feedResponse) { if (pojo.getId().equals(encryptionPojoForQueryItemsOnEncryptedProperties.getId())) { validateResponse(encryptionPojoForQueryItemsOnEncryptedProperties, pojo); } } } finally { try { this.client.getDatabase(databaseId).delete().block(); } catch(Exception ex) { } } } static void validateResponse(EncryptionPojo originalItem, EncryptionPojo result) { assertThat(result.getId()).isEqualTo(originalItem.getId()); assertThat(result.getNonSensitive()).isEqualTo(originalItem.getNonSensitive()); assertThat(result.getSensitiveString()).isEqualTo(originalItem.getSensitiveString()); assertThat(result.getSensitiveInt()).isEqualTo(originalItem.getSensitiveInt()); assertThat(result.getSensitiveFloat()).isEqualTo(originalItem.getSensitiveFloat()); assertThat(result.getSensitiveLong()).isEqualTo(originalItem.getSensitiveLong()); assertThat(result.getSensitiveDouble()).isEqualTo(originalItem.getSensitiveDouble()); assertThat(result.isSensitiveBoolean()).isEqualTo(originalItem.isSensitiveBoolean()); assertThat(result.getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveIntArray()); assertThat(result.getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveStringArray()); assertThat(result.getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveString3DArray()); assertThat(result.getSensitiveNestedPojo().getId()).isEqualTo(originalItem.getSensitiveNestedPojo().getId()); assertThat(result.getSensitiveNestedPojo().getMypk()).isEqualTo(originalItem.getSensitiveNestedPojo().getMypk()); assertThat(result.getSensitiveNestedPojo().getNonSensitive()).isEqualTo(originalItem.getSensitiveNestedPojo().getNonSensitive()); assertThat(result.getSensitiveNestedPojo().getSensitiveString()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveString()); assertThat(result.getSensitiveNestedPojo().getSensitiveInt()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveInt()); assertThat(result.getSensitiveNestedPojo().getSensitiveFloat()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveFloat()); assertThat(result.getSensitiveNestedPojo().getSensitiveLong()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveLong()); assertThat(result.getSensitiveNestedPojo().getSensitiveDouble()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveDouble()); assertThat(result.getSensitiveNestedPojo().isSensitiveBoolean()).isEqualTo(originalItem.getSensitiveNestedPojo().isSensitiveBoolean()); assertThat(result.getSensitiveNestedPojo().getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveIntArray()); assertThat(result.getSensitiveNestedPojo().getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveStringArray()); assertThat(result.getSensitiveNestedPojo().getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveNestedPojo().getSensitiveString3DArray()); assertThat(result.getSensitiveChildPojoList().size()).isEqualTo(originalItem.getSensitiveChildPojoList().size()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveString()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveString()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveInt()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveInt()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveFloat()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveFloat()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveLong()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveLong()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveDouble()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveDouble()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveIntArray()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveStringArray()); assertThat(result.getSensitiveChildPojoList().get(0).getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveChildPojoList().get(0).getSensitiveString3DArray()); assertThat(result.getSensitiveChildPojo2DArray().length).isEqualTo(originalItem.getSensitiveChildPojo2DArray().length); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveString()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveString()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveInt()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveInt()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveFloat()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveFloat()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveLong()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveLong()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveDouble()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveDouble()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveIntArray()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveStringArray()); assertThat(result.getSensitiveChildPojo2DArray()[0][0].getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveChildPojo2DArray()[0][0].getSensitiveString3DArray()); } static void validateResponseWithOneFieldEncryption(EncryptionPojo originalItem, EncryptionPojo result) { assertThat(result.getId()).isEqualTo(originalItem.getId()); assertThat(result.getNonSensitive()).isEqualTo(originalItem.getNonSensitive()); assertThat(result.getSensitiveString()).isNotEqualTo(originalItem.getSensitiveString()); assertThat(result.getSensitiveInt()).isEqualTo(originalItem.getSensitiveInt()); assertThat(result.getSensitiveFloat()).isEqualTo(originalItem.getSensitiveFloat()); assertThat(result.getSensitiveLong()).isEqualTo(originalItem.getSensitiveLong()); assertThat(result.getSensitiveDouble()).isEqualTo(originalItem.getSensitiveDouble()); assertThat(result.isSensitiveBoolean()).isEqualTo(originalItem.isSensitiveBoolean()); assertThat(result.getSensitiveIntArray()).isEqualTo(originalItem.getSensitiveIntArray()); assertThat(result.getSensitiveStringArray()).isEqualTo(originalItem.getSensitiveStringArray()); assertThat(result.getSensitiveString3DArray()).isEqualTo(originalItem.getSensitiveString3DArray()); } public static EncryptionPojo getItem(String documentId) { EncryptionPojo pojo = new EncryptionPojo(); pojo.setId(documentId); pojo.setMypk(documentId); pojo.setNonSensitive(UUID.randomUUID().toString()); pojo.setSensitiveString("testingString"); pojo.setSensitiveDouble(10.123); pojo.setSensitiveFloat(20.0f); pojo.setSensitiveInt(30); pojo.setSensitiveLong(1234); pojo.setSensitiveBoolean(true); EncryptionPojo nestedPojo = new EncryptionPojo(); nestedPojo.setId("nestedPojo"); nestedPojo.setMypk("nestedPojo"); nestedPojo.setSensitiveString("nestedPojo"); nestedPojo.setSensitiveDouble(10.123); nestedPojo.setSensitiveInt(123); nestedPojo.setSensitiveLong(1234); nestedPojo.setSensitiveStringArray(new String[]{"str1", "str1"}); nestedPojo.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); nestedPojo.setSensitiveBoolean(true); pojo.setSensitiveNestedPojo(nestedPojo); pojo.setSensitiveIntArray(new int[]{1, 2}); pojo.setSensitiveStringArray(new String[]{"str1", "str1"}); pojo.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); EncryptionPojo childPojo1 = new EncryptionPojo(); childPojo1.setId("childPojo1"); childPojo1.setSensitiveString("child1TestingString"); childPojo1.setSensitiveDouble(10.123); childPojo1.setSensitiveInt(123); childPojo1.setSensitiveLong(1234); childPojo1.setSensitiveBoolean(true); childPojo1.setSensitiveStringArray(new String[]{"str1", "str1"}); childPojo1.setSensitiveString3DArray(new String[][][]{{{"str1", "str2"}, {"str3", "str4"}}, {{"str5", "str6"}, { "str7", "str8"}}}); EncryptionPojo childPojo2 = new EncryptionPojo(); childPojo2.setId("childPojo2"); childPojo2.setSensitiveString("child2TestingString"); childPojo2.setSensitiveDouble(10.123); childPojo2.setSensitiveInt(123); childPojo2.setSensitiveLong(1234); childPojo2.setSensitiveBoolean(true); pojo.setSensitiveChildPojoList(new ArrayList<>()); pojo.getSensitiveChildPojoList().add(childPojo1); pojo.getSensitiveChildPojoList().add(childPojo2); pojo.setSensitiveChildPojo2DArray(new EncryptionPojo[][]{{childPojo1, childPojo2}, {childPojo1, childPojo2}}); return pojo; } public static class TestEncryptionKeyStoreProvider extends EncryptionKeyStoreProvider { Map<String, Integer> keyInfo = new HashMap<>(); String providerName = "TEST_KEY_STORE_PROVIDER"; @Override public String getProviderName() { return providerName; } public TestEncryptionKeyStoreProvider() { keyInfo.put("tempmetadata1", 1); keyInfo.put("tempmetadata2", 2); } @Override public byte[] unwrapKey(String s, KeyEncryptionKeyAlgorithm keyEncryptionKeyAlgorithm, byte[] encryptedBytes) { int moveBy = this.keyInfo.get(s); byte[] plainkey = new byte[encryptedBytes.length]; for (int i = 0; i < encryptedBytes.length; i++) { plainkey[i] = (byte) (encryptedBytes[i] - moveBy); } return plainkey; } @Override public byte[] wrapKey(String s, KeyEncryptionKeyAlgorithm keyEncryptionKeyAlgorithm, byte[] key) { int moveBy = this.keyInfo.get(s); byte[] encryptedBytes = new byte[key.length]; for (int i = 0; i < key.length; i++) { encryptedBytes[i] = (byte) (key[i] + moveBy); } return encryptedBytes; } @Override public byte[] sign(String s, boolean b) { return new byte[0]; } @Override public boolean verify(String s, boolean b, byte[] bytes) { return true; } } public static List<ClientEncryptionIncludedPath> getPaths() { ClientEncryptionIncludedPath includedPath1 = new ClientEncryptionIncludedPath(); includedPath1.setClientEncryptionKeyId("key1"); includedPath1.setPath("/sensitiveString"); includedPath1.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath1.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath2 = new ClientEncryptionIncludedPath(); includedPath2.setClientEncryptionKeyId("key2"); includedPath2.setPath("/nonValidPath"); includedPath2.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath2.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath3 = new ClientEncryptionIncludedPath(); includedPath3.setClientEncryptionKeyId("key1"); includedPath3.setPath("/sensitiveInt"); includedPath3.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath3.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath4 = new ClientEncryptionIncludedPath(); includedPath4.setClientEncryptionKeyId("key2"); includedPath4.setPath("/sensitiveFloat"); includedPath4.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath4.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath5 = new ClientEncryptionIncludedPath(); includedPath5.setClientEncryptionKeyId("key1"); includedPath5.setPath("/sensitiveLong"); includedPath5.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath5.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath6 = new ClientEncryptionIncludedPath(); includedPath6.setClientEncryptionKeyId("key2"); includedPath6.setPath("/sensitiveDouble"); includedPath6.setEncryptionType(CosmosEncryptionType.RANDOMIZED); includedPath6.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath7 = new ClientEncryptionIncludedPath(); includedPath7.setClientEncryptionKeyId("key1"); includedPath7.setPath("/sensitiveBoolean"); includedPath7.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath7.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath8 = new ClientEncryptionIncludedPath(); includedPath8.setClientEncryptionKeyId("key1"); includedPath8.setPath("/sensitiveNestedPojo"); includedPath8.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath8.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath9 = new ClientEncryptionIncludedPath(); includedPath9.setClientEncryptionKeyId("key1"); includedPath9.setPath("/sensitiveIntArray"); includedPath9.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath9.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath10 = new ClientEncryptionIncludedPath(); includedPath10.setClientEncryptionKeyId("key2"); includedPath10.setPath("/sensitiveString3DArray"); includedPath10.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath10.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath11 = new ClientEncryptionIncludedPath(); includedPath11.setClientEncryptionKeyId("key1"); includedPath11.setPath("/sensitiveStringArray"); includedPath11.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath11.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath12 = new ClientEncryptionIncludedPath(); includedPath12.setClientEncryptionKeyId("key1"); includedPath12.setPath("/sensitiveChildPojoList"); includedPath12.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath12.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); ClientEncryptionIncludedPath includedPath13 = new ClientEncryptionIncludedPath(); includedPath13.setClientEncryptionKeyId("key1"); includedPath13.setPath("/sensitiveChildPojo2DArray"); includedPath13.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath13.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); List<ClientEncryptionIncludedPath> paths = new ArrayList<>(); paths.add(includedPath1); paths.add(includedPath2); paths.add(includedPath3); paths.add(includedPath4); paths.add(includedPath5); paths.add(includedPath6); paths.add(includedPath7); paths.add(includedPath8); paths.add(includedPath9); paths.add(includedPath10); paths.add(includedPath11); paths.add(includedPath12); paths.add(includedPath13); return paths; } public static List<ClientEncryptionIncludedPath> getPathWithOneEncryptionField() { ClientEncryptionIncludedPath includedPath = new ClientEncryptionIncludedPath(); includedPath.setClientEncryptionKeyId("key1"); includedPath.setPath("/sensitiveString"); includedPath.setEncryptionType(CosmosEncryptionType.DETERMINISTIC); includedPath.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256); List<ClientEncryptionIncludedPath> paths = new ArrayList<>(); paths.add(includedPath); return paths; } private void createEncryptionContainer(CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase, ClientEncryptionPolicy clientEncryptionPolicy, String containerId) { CosmosContainerProperties properties = new CosmosContainerProperties(containerId, "/mypk"); properties.setClientEncryptionPolicy(clientEncryptionPolicy); cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties).block(); } private void createNewDatabaseWithClientEncryptionKey(String databaseId){ cosmosEncryptionAsyncClient.getCosmosAsyncClient().createDatabase(databaseId).block(); CosmosEncryptionAsyncDatabase encryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(databaseId); encryptionAsyncDatabase.createClientEncryptionKey("key1", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata1).block(); encryptionAsyncDatabase.createClientEncryptionKey("key2", CosmosEncryptionAlgorithm.AEAES_256_CBC_HMAC_SHA_256, metadata2).block(); } private CosmosEncryptionAsyncContainer getNewEncryptionContainerProxyObject(String databaseId, String containerId) { CosmosAsyncClient client = getClientBuilder().buildAsyncClient(); EncryptionKeyStoreProvider encryptionKeyStoreProvider = new TestEncryptionKeyStoreProvider(); CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient = CosmosEncryptionAsyncClient.createCosmosEncryptionAsyncClient(client, encryptionKeyStoreProvider); CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(client.getDatabase(databaseId)); CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerId); return cosmosEncryptionAsyncContainer; } }
Is it possible both scopes need?
private Set<String> azureClientAccessTokenScopes() { Set<String> result = Optional.of(properties) .map(AADAuthenticationProperties::getAuthorizationClients) .map(clients -> clients.get(AZURE_CLIENT_REGISTRATION_ID)) .map(AuthorizationClientProperties::getScopes) .map(Collection::stream) .orElseGet(Stream::empty) .collect(Collectors.toSet()); result.addAll(azureClientOpenidScopes()); if (properties.allowedGroupNamesConfigured()) { result.add(properties.getGraphBaseUri() + "Directory.Read.All"); } else if (properties.allowedGroupIdsConfigured()) { result.add(properties.getGraphBaseUri() + "User.Read"); } return result; }
} else if (properties.allowedGroupIdsConfigured()) {
private Set<String> azureClientAccessTokenScopes() { Set<String> result = Optional.of(properties) .map(AADAuthenticationProperties::getAuthorizationClients) .map(clients -> clients.get(AZURE_CLIENT_REGISTRATION_ID)) .map(AuthorizationClientProperties::getScopes) .map(Collection::stream) .orElseGet(Stream::empty) .collect(Collectors.toSet()); result.addAll(azureClientOpenidScopes()); if (properties.allowedGroupNamesConfigured()) { result.add(properties.getGraphBaseUri() + "Directory.Read.All"); } else if (properties.allowedGroupIdsConfigured()) { result.add(properties.getGraphBaseUri() + "User.Read"); } return result; }
class AADClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> { private static final Logger LOGGER = LoggerFactory.getLogger(AADClientRegistrationRepository.class); public static final String AZURE_CLIENT_REGISTRATION_ID = "azure"; protected final AzureClientRegistration azureClient; protected final Map<String, ClientRegistration> delegatedClients; protected final Map<String, ClientRegistration> allClients; protected final AADAuthenticationProperties properties; public AADClientRegistrationRepository(AADAuthenticationProperties properties) { this.properties = properties; this.azureClient = azureClientRegistration(); this.delegatedClients = delegatedClientRegistrations(); this.allClients = allClientRegistrations(); } private AzureClientRegistration azureClientRegistration() { if (!needDelegation()) { return null; } AuthorizationClientProperties azureProperties = properties.getAuthorizationClients() .getOrDefault(AZURE_CLIENT_REGISTRATION_ID, defaultAzureAuthorizationClientProperties()); ClientRegistration.Builder builder = toClientRegistrationBuilder(AZURE_CLIENT_REGISTRATION_ID, azureProperties); Set<String> authorizationCodeScopes = azureClientAuthorizationCodeScopes(); ClientRegistration client = builder.scope(authorizationCodeScopes).build(); Set<String> accessTokenScopes = azureClientAccessTokenScopes(); if (resourceServerCount(accessTokenScopes) == 0 && resourceServerCount((authorizationCodeScopes)) > 1) { accessTokenScopes.add(properties.getGraphBaseUri() + "User.Read"); } return new AzureClientRegistration(client, accessTokenScopes); } private boolean needDelegation() { return WEB_APPLICATION == properties.getApplicationType() || WEB_APPLICATION_AND_RESOURCE_SERVER == properties.getApplicationType(); } private Map<String, ClientRegistration> delegatedClientRegistrations() { if (!needDelegation()) { return Collections.emptyMap(); } return properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> isAzureDelegatedClientRegistration(entry.getKey(), entry.getValue())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); } private Map<String, ClientRegistration> allClientRegistrations() { Map<String, ClientRegistration> result = properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> !delegatedClients.containsKey(entry.getKey())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); if (needDelegation()) { result.putAll(delegatedClients); result.put(AZURE_CLIENT_REGISTRATION_ID, azureClient.getClient()); } return Collections.unmodifiableMap(result); } private ClientRegistration.Builder toClientRegistrationBuilder(String registrationId, AuthorizationClientProperties clientProperties) { AADAuthorizationServerEndpoints endpoints = new AADAuthorizationServerEndpoints(properties.getBaseUri(), properties.getTenantId()); AuthorizationGrantType authorizationGrantType; switch (clientProperties.getAuthorizationGrantType()) { case AUTHORIZATION_CODE: authorizationGrantType = AuthorizationGrantType.AUTHORIZATION_CODE; break; case ON_BEHALF_OF: authorizationGrantType = new AuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF.getValue()); break; case CLIENT_CREDENTIALS: authorizationGrantType = AuthorizationGrantType.CLIENT_CREDENTIALS; break; default: throw new IllegalArgumentException("Unsupported authorization type " + clientProperties.getAuthorizationGrantType().getValue()); } return ClientRegistration.withRegistrationId(registrationId) .clientName(registrationId) .authorizationGrantType(authorizationGrantType) .scope(toScopes(clientProperties)) .redirectUri(properties.getRedirectUriTemplate()) .userNameAttributeName(properties.getUserNameAttribute()) .clientId(properties.getClientId()) .clientSecret(properties.getClientSecret()) .authorizationUri(endpoints.authorizationEndpoint()) .tokenUri(endpoints.tokenEndpoint()) .jwkSetUri(endpoints.jwkSetEndpoint()) .providerConfigurationMetadata(providerConfigurationMetadata(endpoints)); } private AuthorizationClientProperties defaultAzureAuthorizationClientProperties() { AuthorizationClientProperties result = new AuthorizationClientProperties(); result.setAuthorizationGrantType(AUTHORIZATION_CODE); return result; } private List<String> toScopes(AuthorizationClientProperties clientProperties) { List<String> result = clientProperties.getScopes(); if (clientProperties.isOnDemand()) { if (!result.contains("openid")) { result.add("openid"); } if (!result.contains("profile")) { result.add("profile"); } } return result; } private Map<String, Object> providerConfigurationMetadata(AADAuthorizationServerEndpoints endpoints) { Map<String, Object> result = new LinkedHashMap<>(); String endSessionEndpoint = endpoints.endSessionEndpoint(); result.put("end_session_endpoint", endSessionEndpoint); return result; } public static int resourceServerCount(Set<String> scopes) { return (int) scopes.stream() .filter(scope -> scope.contains("/")) .map(scope -> scope.substring(0, scope.lastIndexOf('/'))) .distinct() .count(); } private Set<String> azureClientAuthorizationCodeScopes() { Set<String> result = azureClientAccessTokenScopes(); result.addAll(delegatedClientsAccessTokenScopes()); return result; } private Set<String> delegatedClientsAccessTokenScopes() { return properties.getAuthorizationClients() .values() .stream() .filter(p -> !p.isOnDemand() && AUTHORIZATION_CODE.equals(p.getAuthorizationGrantType())) .flatMap(p -> p.getScopes().stream()) .collect(Collectors.toSet()); } /** * @return the scopes needed for OpenID Connect. * @see <a href="https: * @see <a href="https: */ private Set<String> azureClientOpenidScopes() { Set<String> result = new HashSet<>(); result.add("openid"); result.add("profile"); if (!properties.getAuthorizationClients().isEmpty()) { result.add("offline_access"); } return result; } private ClientRegistration toClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return toClientRegistrationBuilder(registrationId, clientProperties).build(); } private boolean isAzureDelegatedClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return !AZURE_CLIENT_REGISTRATION_ID.equals(registrationId) && AUTHORIZATION_CODE.equals(clientProperties.getAuthorizationGrantType()) && !clientProperties.isOnDemand(); } @Override public ClientRegistration findByRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return allClients.get(registrationId); } @Override public Iterator<ClientRegistration> iterator() { if (!needDelegation()) { return allClients.values().iterator(); } return Collections.singleton(azureClient.getClient()).iterator(); } public AzureClientRegistration getAzureClient() { return azureClient; } public boolean isAzureDelegatedClientRegistration(ClientRegistration client) { return delegatedClients.containsValue(client); } public boolean isAzureDelegatedClientRegistration(String registrationId) { return delegatedClients.containsKey(registrationId); } public static boolean isDefaultClient(String registrationId) { return AZURE_CLIENT_REGISTRATION_ID.equals(registrationId); } }
class AADClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> { private static final Logger LOGGER = LoggerFactory.getLogger(AADClientRegistrationRepository.class); public static final String AZURE_CLIENT_REGISTRATION_ID = "azure"; protected final AzureClientRegistration azureClient; protected final Map<String, ClientRegistration> delegatedClients; protected final Map<String, ClientRegistration> allClients; protected final AADAuthenticationProperties properties; public AADClientRegistrationRepository(AADAuthenticationProperties properties) { this.properties = properties; this.azureClient = azureClientRegistration(); this.delegatedClients = delegatedClientRegistrations(); this.allClients = allClientRegistrations(); } private AzureClientRegistration azureClientRegistration() { if (!needDelegation()) { return null; } AuthorizationClientProperties azureProperties = properties.getAuthorizationClients() .getOrDefault(AZURE_CLIENT_REGISTRATION_ID, defaultAzureAuthorizationClientProperties()); ClientRegistration.Builder builder = toClientRegistrationBuilder(AZURE_CLIENT_REGISTRATION_ID, azureProperties); Set<String> authorizationCodeScopes = azureClientAuthorizationCodeScopes(); ClientRegistration client = builder.scope(authorizationCodeScopes).build(); Set<String> accessTokenScopes = azureClientAccessTokenScopes(); if (resourceServerCount(accessTokenScopes) == 0 && resourceServerCount((authorizationCodeScopes)) > 1) { accessTokenScopes.add(properties.getGraphBaseUri() + "User.Read"); } return new AzureClientRegistration(client, accessTokenScopes); } private boolean needDelegation() { return WEB_APPLICATION == properties.getApplicationType() || WEB_APPLICATION_AND_RESOURCE_SERVER == properties.getApplicationType(); } private Map<String, ClientRegistration> delegatedClientRegistrations() { if (!needDelegation()) { return Collections.emptyMap(); } return properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> isAzureDelegatedClientRegistration(entry.getKey(), entry.getValue())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); } private Map<String, ClientRegistration> allClientRegistrations() { Map<String, ClientRegistration> result = properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> !delegatedClients.containsKey(entry.getKey())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); if (needDelegation()) { result.putAll(delegatedClients); result.put(AZURE_CLIENT_REGISTRATION_ID, azureClient.getClient()); } return Collections.unmodifiableMap(result); } private ClientRegistration.Builder toClientRegistrationBuilder(String registrationId, AuthorizationClientProperties clientProperties) { AADAuthorizationServerEndpoints endpoints = new AADAuthorizationServerEndpoints(properties.getBaseUri(), properties.getTenantId()); AuthorizationGrantType authorizationGrantType; switch (clientProperties.getAuthorizationGrantType()) { case AUTHORIZATION_CODE: authorizationGrantType = AuthorizationGrantType.AUTHORIZATION_CODE; break; case ON_BEHALF_OF: authorizationGrantType = new AuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF.getValue()); break; case CLIENT_CREDENTIALS: authorizationGrantType = AuthorizationGrantType.CLIENT_CREDENTIALS; break; default: throw new IllegalArgumentException("Unsupported authorization type " + clientProperties.getAuthorizationGrantType().getValue()); } return ClientRegistration.withRegistrationId(registrationId) .clientName(registrationId) .authorizationGrantType(authorizationGrantType) .scope(toScopes(clientProperties)) .redirectUri(properties.getRedirectUriTemplate()) .userNameAttributeName(properties.getUserNameAttribute()) .clientId(properties.getClientId()) .clientSecret(properties.getClientSecret()) .authorizationUri(endpoints.authorizationEndpoint()) .tokenUri(endpoints.tokenEndpoint()) .jwkSetUri(endpoints.jwkSetEndpoint()) .providerConfigurationMetadata(providerConfigurationMetadata(endpoints)); } private AuthorizationClientProperties defaultAzureAuthorizationClientProperties() { AuthorizationClientProperties result = new AuthorizationClientProperties(); result.setAuthorizationGrantType(AUTHORIZATION_CODE); return result; } private List<String> toScopes(AuthorizationClientProperties clientProperties) { List<String> result = clientProperties.getScopes(); if (clientProperties.isOnDemand()) { if (!result.contains("openid")) { result.add("openid"); } if (!result.contains("profile")) { result.add("profile"); } } return result; } private Map<String, Object> providerConfigurationMetadata(AADAuthorizationServerEndpoints endpoints) { Map<String, Object> result = new LinkedHashMap<>(); String endSessionEndpoint = endpoints.endSessionEndpoint(); result.put("end_session_endpoint", endSessionEndpoint); return result; } public static int resourceServerCount(Set<String> scopes) { return (int) scopes.stream() .filter(scope -> scope.contains("/")) .map(scope -> scope.substring(0, scope.lastIndexOf('/'))) .distinct() .count(); } private Set<String> azureClientAuthorizationCodeScopes() { Set<String> result = azureClientAccessTokenScopes(); result.addAll(delegatedClientsAccessTokenScopes()); return result; } private Set<String> delegatedClientsAccessTokenScopes() { return properties.getAuthorizationClients() .values() .stream() .filter(p -> !p.isOnDemand() && AUTHORIZATION_CODE.equals(p.getAuthorizationGrantType())) .flatMap(p -> p.getScopes().stream()) .collect(Collectors.toSet()); } /** * @return the scopes needed for OpenID Connect. * @see <a href="https: * @see <a href="https: */ private Set<String> azureClientOpenidScopes() { Set<String> result = new HashSet<>(); result.add("openid"); result.add("profile"); if (!properties.getAuthorizationClients().isEmpty()) { result.add("offline_access"); } return result; } private ClientRegistration toClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return toClientRegistrationBuilder(registrationId, clientProperties).build(); } private boolean isAzureDelegatedClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return !AZURE_CLIENT_REGISTRATION_ID.equals(registrationId) && AUTHORIZATION_CODE.equals(clientProperties.getAuthorizationGrantType()) && !clientProperties.isOnDemand(); } @Override public ClientRegistration findByRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return allClients.get(registrationId); } @Override public Iterator<ClientRegistration> iterator() { if (!needDelegation()) { return allClients.values().iterator(); } return Collections.singleton(azureClient.getClient()).iterator(); } public AzureClientRegistration getAzureClient() { return azureClient; } public boolean isAzureDelegatedClientRegistration(ClientRegistration client) { return delegatedClients.containsValue(client); } public boolean isAzureDelegatedClientRegistration(String registrationId) { return delegatedClients.containsKey(registrationId); } public static boolean isDefaultClient(String registrationId) { return AZURE_CLIENT_REGISTRATION_ID.equals(registrationId); } }
No. `User.Read` is not necessary anymore we have `Directory.Read.All`. Please refer to the link in line 204.
private Set<String> azureClientAccessTokenScopes() { Set<String> result = Optional.of(properties) .map(AADAuthenticationProperties::getAuthorizationClients) .map(clients -> clients.get(AZURE_CLIENT_REGISTRATION_ID)) .map(AuthorizationClientProperties::getScopes) .map(Collection::stream) .orElseGet(Stream::empty) .collect(Collectors.toSet()); result.addAll(azureClientOpenidScopes()); if (properties.allowedGroupNamesConfigured()) { result.add(properties.getGraphBaseUri() + "Directory.Read.All"); } else if (properties.allowedGroupIdsConfigured()) { result.add(properties.getGraphBaseUri() + "User.Read"); } return result; }
} else if (properties.allowedGroupIdsConfigured()) {
private Set<String> azureClientAccessTokenScopes() { Set<String> result = Optional.of(properties) .map(AADAuthenticationProperties::getAuthorizationClients) .map(clients -> clients.get(AZURE_CLIENT_REGISTRATION_ID)) .map(AuthorizationClientProperties::getScopes) .map(Collection::stream) .orElseGet(Stream::empty) .collect(Collectors.toSet()); result.addAll(azureClientOpenidScopes()); if (properties.allowedGroupNamesConfigured()) { result.add(properties.getGraphBaseUri() + "Directory.Read.All"); } else if (properties.allowedGroupIdsConfigured()) { result.add(properties.getGraphBaseUri() + "User.Read"); } return result; }
class AADClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> { private static final Logger LOGGER = LoggerFactory.getLogger(AADClientRegistrationRepository.class); public static final String AZURE_CLIENT_REGISTRATION_ID = "azure"; protected final AzureClientRegistration azureClient; protected final Map<String, ClientRegistration> delegatedClients; protected final Map<String, ClientRegistration> allClients; protected final AADAuthenticationProperties properties; public AADClientRegistrationRepository(AADAuthenticationProperties properties) { this.properties = properties; this.azureClient = azureClientRegistration(); this.delegatedClients = delegatedClientRegistrations(); this.allClients = allClientRegistrations(); } private AzureClientRegistration azureClientRegistration() { if (!needDelegation()) { return null; } AuthorizationClientProperties azureProperties = properties.getAuthorizationClients() .getOrDefault(AZURE_CLIENT_REGISTRATION_ID, defaultAzureAuthorizationClientProperties()); ClientRegistration.Builder builder = toClientRegistrationBuilder(AZURE_CLIENT_REGISTRATION_ID, azureProperties); Set<String> authorizationCodeScopes = azureClientAuthorizationCodeScopes(); ClientRegistration client = builder.scope(authorizationCodeScopes).build(); Set<String> accessTokenScopes = azureClientAccessTokenScopes(); if (resourceServerCount(accessTokenScopes) == 0 && resourceServerCount((authorizationCodeScopes)) > 1) { accessTokenScopes.add(properties.getGraphBaseUri() + "User.Read"); } return new AzureClientRegistration(client, accessTokenScopes); } private boolean needDelegation() { return WEB_APPLICATION == properties.getApplicationType() || WEB_APPLICATION_AND_RESOURCE_SERVER == properties.getApplicationType(); } private Map<String, ClientRegistration> delegatedClientRegistrations() { if (!needDelegation()) { return Collections.emptyMap(); } return properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> isAzureDelegatedClientRegistration(entry.getKey(), entry.getValue())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); } private Map<String, ClientRegistration> allClientRegistrations() { Map<String, ClientRegistration> result = properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> !delegatedClients.containsKey(entry.getKey())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); if (needDelegation()) { result.putAll(delegatedClients); result.put(AZURE_CLIENT_REGISTRATION_ID, azureClient.getClient()); } return Collections.unmodifiableMap(result); } private ClientRegistration.Builder toClientRegistrationBuilder(String registrationId, AuthorizationClientProperties clientProperties) { AADAuthorizationServerEndpoints endpoints = new AADAuthorizationServerEndpoints(properties.getBaseUri(), properties.getTenantId()); AuthorizationGrantType authorizationGrantType; switch (clientProperties.getAuthorizationGrantType()) { case AUTHORIZATION_CODE: authorizationGrantType = AuthorizationGrantType.AUTHORIZATION_CODE; break; case ON_BEHALF_OF: authorizationGrantType = new AuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF.getValue()); break; case CLIENT_CREDENTIALS: authorizationGrantType = AuthorizationGrantType.CLIENT_CREDENTIALS; break; default: throw new IllegalArgumentException("Unsupported authorization type " + clientProperties.getAuthorizationGrantType().getValue()); } return ClientRegistration.withRegistrationId(registrationId) .clientName(registrationId) .authorizationGrantType(authorizationGrantType) .scope(toScopes(clientProperties)) .redirectUri(properties.getRedirectUriTemplate()) .userNameAttributeName(properties.getUserNameAttribute()) .clientId(properties.getClientId()) .clientSecret(properties.getClientSecret()) .authorizationUri(endpoints.authorizationEndpoint()) .tokenUri(endpoints.tokenEndpoint()) .jwkSetUri(endpoints.jwkSetEndpoint()) .providerConfigurationMetadata(providerConfigurationMetadata(endpoints)); } private AuthorizationClientProperties defaultAzureAuthorizationClientProperties() { AuthorizationClientProperties result = new AuthorizationClientProperties(); result.setAuthorizationGrantType(AUTHORIZATION_CODE); return result; } private List<String> toScopes(AuthorizationClientProperties clientProperties) { List<String> result = clientProperties.getScopes(); if (clientProperties.isOnDemand()) { if (!result.contains("openid")) { result.add("openid"); } if (!result.contains("profile")) { result.add("profile"); } } return result; } private Map<String, Object> providerConfigurationMetadata(AADAuthorizationServerEndpoints endpoints) { Map<String, Object> result = new LinkedHashMap<>(); String endSessionEndpoint = endpoints.endSessionEndpoint(); result.put("end_session_endpoint", endSessionEndpoint); return result; } public static int resourceServerCount(Set<String> scopes) { return (int) scopes.stream() .filter(scope -> scope.contains("/")) .map(scope -> scope.substring(0, scope.lastIndexOf('/'))) .distinct() .count(); } private Set<String> azureClientAuthorizationCodeScopes() { Set<String> result = azureClientAccessTokenScopes(); result.addAll(delegatedClientsAccessTokenScopes()); return result; } private Set<String> delegatedClientsAccessTokenScopes() { return properties.getAuthorizationClients() .values() .stream() .filter(p -> !p.isOnDemand() && AUTHORIZATION_CODE.equals(p.getAuthorizationGrantType())) .flatMap(p -> p.getScopes().stream()) .collect(Collectors.toSet()); } /** * @return the scopes needed for OpenID Connect. * @see <a href="https: * @see <a href="https: */ private Set<String> azureClientOpenidScopes() { Set<String> result = new HashSet<>(); result.add("openid"); result.add("profile"); if (!properties.getAuthorizationClients().isEmpty()) { result.add("offline_access"); } return result; } private ClientRegistration toClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return toClientRegistrationBuilder(registrationId, clientProperties).build(); } private boolean isAzureDelegatedClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return !AZURE_CLIENT_REGISTRATION_ID.equals(registrationId) && AUTHORIZATION_CODE.equals(clientProperties.getAuthorizationGrantType()) && !clientProperties.isOnDemand(); } @Override public ClientRegistration findByRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return allClients.get(registrationId); } @Override public Iterator<ClientRegistration> iterator() { if (!needDelegation()) { return allClients.values().iterator(); } return Collections.singleton(azureClient.getClient()).iterator(); } public AzureClientRegistration getAzureClient() { return azureClient; } public boolean isAzureDelegatedClientRegistration(ClientRegistration client) { return delegatedClients.containsValue(client); } public boolean isAzureDelegatedClientRegistration(String registrationId) { return delegatedClients.containsKey(registrationId); } public static boolean isDefaultClient(String registrationId) { return AZURE_CLIENT_REGISTRATION_ID.equals(registrationId); } }
class AADClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> { private static final Logger LOGGER = LoggerFactory.getLogger(AADClientRegistrationRepository.class); public static final String AZURE_CLIENT_REGISTRATION_ID = "azure"; protected final AzureClientRegistration azureClient; protected final Map<String, ClientRegistration> delegatedClients; protected final Map<String, ClientRegistration> allClients; protected final AADAuthenticationProperties properties; public AADClientRegistrationRepository(AADAuthenticationProperties properties) { this.properties = properties; this.azureClient = azureClientRegistration(); this.delegatedClients = delegatedClientRegistrations(); this.allClients = allClientRegistrations(); } private AzureClientRegistration azureClientRegistration() { if (!needDelegation()) { return null; } AuthorizationClientProperties azureProperties = properties.getAuthorizationClients() .getOrDefault(AZURE_CLIENT_REGISTRATION_ID, defaultAzureAuthorizationClientProperties()); ClientRegistration.Builder builder = toClientRegistrationBuilder(AZURE_CLIENT_REGISTRATION_ID, azureProperties); Set<String> authorizationCodeScopes = azureClientAuthorizationCodeScopes(); ClientRegistration client = builder.scope(authorizationCodeScopes).build(); Set<String> accessTokenScopes = azureClientAccessTokenScopes(); if (resourceServerCount(accessTokenScopes) == 0 && resourceServerCount((authorizationCodeScopes)) > 1) { accessTokenScopes.add(properties.getGraphBaseUri() + "User.Read"); } return new AzureClientRegistration(client, accessTokenScopes); } private boolean needDelegation() { return WEB_APPLICATION == properties.getApplicationType() || WEB_APPLICATION_AND_RESOURCE_SERVER == properties.getApplicationType(); } private Map<String, ClientRegistration> delegatedClientRegistrations() { if (!needDelegation()) { return Collections.emptyMap(); } return properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> isAzureDelegatedClientRegistration(entry.getKey(), entry.getValue())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); } private Map<String, ClientRegistration> allClientRegistrations() { Map<String, ClientRegistration> result = properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> !delegatedClients.containsKey(entry.getKey())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); if (needDelegation()) { result.putAll(delegatedClients); result.put(AZURE_CLIENT_REGISTRATION_ID, azureClient.getClient()); } return Collections.unmodifiableMap(result); } private ClientRegistration.Builder toClientRegistrationBuilder(String registrationId, AuthorizationClientProperties clientProperties) { AADAuthorizationServerEndpoints endpoints = new AADAuthorizationServerEndpoints(properties.getBaseUri(), properties.getTenantId()); AuthorizationGrantType authorizationGrantType; switch (clientProperties.getAuthorizationGrantType()) { case AUTHORIZATION_CODE: authorizationGrantType = AuthorizationGrantType.AUTHORIZATION_CODE; break; case ON_BEHALF_OF: authorizationGrantType = new AuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF.getValue()); break; case CLIENT_CREDENTIALS: authorizationGrantType = AuthorizationGrantType.CLIENT_CREDENTIALS; break; default: throw new IllegalArgumentException("Unsupported authorization type " + clientProperties.getAuthorizationGrantType().getValue()); } return ClientRegistration.withRegistrationId(registrationId) .clientName(registrationId) .authorizationGrantType(authorizationGrantType) .scope(toScopes(clientProperties)) .redirectUri(properties.getRedirectUriTemplate()) .userNameAttributeName(properties.getUserNameAttribute()) .clientId(properties.getClientId()) .clientSecret(properties.getClientSecret()) .authorizationUri(endpoints.authorizationEndpoint()) .tokenUri(endpoints.tokenEndpoint()) .jwkSetUri(endpoints.jwkSetEndpoint()) .providerConfigurationMetadata(providerConfigurationMetadata(endpoints)); } private AuthorizationClientProperties defaultAzureAuthorizationClientProperties() { AuthorizationClientProperties result = new AuthorizationClientProperties(); result.setAuthorizationGrantType(AUTHORIZATION_CODE); return result; } private List<String> toScopes(AuthorizationClientProperties clientProperties) { List<String> result = clientProperties.getScopes(); if (clientProperties.isOnDemand()) { if (!result.contains("openid")) { result.add("openid"); } if (!result.contains("profile")) { result.add("profile"); } } return result; } private Map<String, Object> providerConfigurationMetadata(AADAuthorizationServerEndpoints endpoints) { Map<String, Object> result = new LinkedHashMap<>(); String endSessionEndpoint = endpoints.endSessionEndpoint(); result.put("end_session_endpoint", endSessionEndpoint); return result; } public static int resourceServerCount(Set<String> scopes) { return (int) scopes.stream() .filter(scope -> scope.contains("/")) .map(scope -> scope.substring(0, scope.lastIndexOf('/'))) .distinct() .count(); } private Set<String> azureClientAuthorizationCodeScopes() { Set<String> result = azureClientAccessTokenScopes(); result.addAll(delegatedClientsAccessTokenScopes()); return result; } private Set<String> delegatedClientsAccessTokenScopes() { return properties.getAuthorizationClients() .values() .stream() .filter(p -> !p.isOnDemand() && AUTHORIZATION_CODE.equals(p.getAuthorizationGrantType())) .flatMap(p -> p.getScopes().stream()) .collect(Collectors.toSet()); } /** * @return the scopes needed for OpenID Connect. * @see <a href="https: * @see <a href="https: */ private Set<String> azureClientOpenidScopes() { Set<String> result = new HashSet<>(); result.add("openid"); result.add("profile"); if (!properties.getAuthorizationClients().isEmpty()) { result.add("offline_access"); } return result; } private ClientRegistration toClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return toClientRegistrationBuilder(registrationId, clientProperties).build(); } private boolean isAzureDelegatedClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return !AZURE_CLIENT_REGISTRATION_ID.equals(registrationId) && AUTHORIZATION_CODE.equals(clientProperties.getAuthorizationGrantType()) && !clientProperties.isOnDemand(); } @Override public ClientRegistration findByRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return allClients.get(registrationId); } @Override public Iterator<ClientRegistration> iterator() { if (!needDelegation()) { return allClients.values().iterator(); } return Collections.singleton(azureClient.getClient()).iterator(); } public AzureClientRegistration getAzureClient() { return azureClient; } public boolean isAzureDelegatedClientRegistration(ClientRegistration client) { return delegatedClients.containsValue(client); } public boolean isAzureDelegatedClientRegistration(String registrationId) { return delegatedClients.containsKey(registrationId); } public static boolean isDefaultClient(String registrationId) { return AZURE_CLIENT_REGISTRATION_ID.equals(registrationId); } }
Yeah, in this case, we could potentially use `instanceof` because the class is marked `final`. But I prefer to use `getClass()` because if `a` extends `b`, then `a instanceof b` is true and not vice versa. See - https://youtrack.jetbrains.com/issue/IDEA-7692
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeInterval that = (TimeInterval) o; return Objects.equals(this.duration, that.duration) && Objects.equals(this.startDuration, that.startDuration) && Objects.equals(this.endDuration, that.endDuration) && Objects.equals(this.startTime, that.startTime) && Objects.equals(this.endTime, that.endTime); }
if (o == null || getClass() != o.getClass()) {
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeInterval that = (TimeInterval) o; return Objects.equals(this.duration, that.duration) && Objects.equals(this.startTime, that.startTime) && Objects.equals(this.endTime, that.endTime); }
class TimeInterval { public static final TimeInterval ALL = new TimeInterval(OffsetDateTime.MIN, OffsetDateTime.MAX); public static final TimeInterval LAST_5_MINUTES = new TimeInterval(Duration.ofMinutes(5)); public static final TimeInterval LAST_30_MINUTES = new TimeInterval(Duration.ofMinutes(30)); public static final TimeInterval LAST_1_HOUR = new TimeInterval(Duration.ofHours(1)); public static final TimeInterval LAST_4_HOURS = new TimeInterval(Duration.ofHours(4)); public static final TimeInterval LAST_12_HOURS = new TimeInterval(Duration.ofHours(12)); public static final TimeInterval LAST_DAY = new TimeInterval(Duration.ofDays(1)); public static final TimeInterval LAST_2_DAYS = new TimeInterval(Duration.ofDays(2)); public static final TimeInterval LAST_3_DAYS = new TimeInterval(Duration.ofDays(3)); public static final TimeInterval LAST_7_DAYS = new TimeInterval(Duration.ofDays(7)); private static final ClientLogger LOGGER = new ClientLogger(TimeInterval.class); private static final String ERROR_MESSAGE = "%s is an invalid time interval. It must be in one of the " + "following ISO 8601 time interval formats: duration, startDuration/endTime, " + "startTime/endTime, startTime/endDuration"; private final Duration duration; private final Duration startDuration; private final Duration endDuration; private final OffsetDateTime startTime; private final OffsetDateTime endTime; /** * Creates an instance of {@link TimeInterval} using the provided duration. * @param duration the duration for this query time span. */ public TimeInterval(Duration duration) { this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startDuration = null; this.endDuration = null; this.startTime = null; this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end {@link OffsetDateTime OffsetDateTimes}. * @param startTime The start time of the interval. * @param endTime The end time of the interval. */ public TimeInterval(OffsetDateTime startTime, OffsetDateTime endTime) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = null; this.startDuration = null; this.endDuration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startTime The start time of the interval. * @param endDuration The end duration of the interval. */ public TimeInterval(OffsetDateTime startTime, Duration endDuration) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endDuration = Objects.requireNonNull(endDuration, "'endDuration' cannot be null"); this.duration = null; this.endTime = null; this.startDuration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startDuration The duration of the interval. * @param endTime The end time of the interval. */ public TimeInterval(Duration startDuration, OffsetDateTime endTime) { this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.startDuration = Objects.requireNonNull(startDuration, "'startDuration' cannot be null"); this.duration = null; this.startTime = null; this.endDuration = null; } /** * Returns the duration of this {@link TimeInterval} instance. * @return the duration of this {@link TimeInterval} instance. */ public Duration getDuration() { return duration; } /** * Returns the start duration of this {@link TimeInterval} instance. * @return the start duration of this {@link TimeInterval} instance. */ public Duration getStartDuration() { return startDuration; } /** * Returns the end duration of this {@link TimeInterval} instance. * @return the end duration of this {@link TimeInterval} instance. */ public Duration getEndDuration() { return endDuration; } /** * Returns the start time of this {@link TimeInterval} instance. * @return the start time of this {@link TimeInterval} instance. */ public OffsetDateTime getStartTime() { return startTime; } /** * Returns the end time of this {@link TimeInterval} instance. * @return the end time of this {@link TimeInterval} instance. */ public OffsetDateTime getEndTime() { return endTime; } /** * Returns this {@link TimeInterval} in ISO 8601 string format. * @return ISO 8601 formatted string representation of this {@link TimeInterval} instance. */ public String toIso8601Format() { if (startTime != null && endTime != null) { return startTime + "/" + endTime; } if (startTime != null && endDuration != null) { return startTime + "/" + endDuration; } if (startDuration != null && endTime != null) { return startDuration + "/" + endTime; } if (duration != null) { return duration.toString(); } throw LOGGER.logExceptionAsError(new IllegalStateException("Invalid date time range")); } /** * This method takes an ISO 8601 formatted time interval string and returns an instance of {@link TimeInterval}. * @param value The ISO 8601 formatted time interval string. * @return An instance of {@link TimeInterval}. * @throws IllegalArgumentException if {@code value} is not in the correct format. */ public static TimeInterval parse(String value) { Objects.requireNonNull(value); String[] parts = value.split("/"); if (parts.length == 1) { Duration duration = parseDuration(parts[0]); if (duration == null || parts[0].length() + 1 == value.length()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } return new TimeInterval(duration); } if (parts.length == 2) { Duration startDuration = parseDuration(parts[0]); OffsetDateTime startTime = parseTime(parts[0]); Duration endDuration = parseDuration(parts[1]); OffsetDateTime endTime = parseTime(parts[1]); if (startDuration != null && endTime != null) { return new TimeInterval(startDuration, endTime); } if (startTime != null && endTime != null) { return new TimeInterval(startTime, endTime); } if (startTime != null && endDuration != null) { return new TimeInterval(startTime, endDuration); } } throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (duration != null) { return sb.append("duration: ").append(duration).append("]").toString(); } if (startTime != null) { sb.append("start time: ").append(startTime); } if (startDuration != null) { sb.append("start duration: ").append(startDuration); } sb.append(", "); if (endTime != null) { sb.append("end time: ").append(endTime); } if (endDuration != null) { sb.append("end duration: ").append(endDuration); } sb.append("]"); return sb.toString(); } @Override @Override public int hashCode() { return Objects.hash(duration, startDuration, endDuration, startTime, endTime); } private static OffsetDateTime parseTime(String value) { try { return OffsetDateTime.parse(value); } catch (Exception exception) { return null; } } private static Duration parseDuration(String value) { try { return Duration.parse(value); } catch (Exception exception) { return null; } } }
class TimeInterval { public static final TimeInterval ALL = new TimeInterval(OffsetDateTime.MIN, OffsetDateTime.MAX); public static final TimeInterval LAST_5_MINUTES = new TimeInterval(Duration.ofMinutes(5)); public static final TimeInterval LAST_30_MINUTES = new TimeInterval(Duration.ofMinutes(30)); public static final TimeInterval LAST_1_HOUR = new TimeInterval(Duration.ofHours(1)); public static final TimeInterval LAST_4_HOURS = new TimeInterval(Duration.ofHours(4)); public static final TimeInterval LAST_12_HOURS = new TimeInterval(Duration.ofHours(12)); public static final TimeInterval LAST_DAY = new TimeInterval(Duration.ofDays(1)); public static final TimeInterval LAST_2_DAYS = new TimeInterval(Duration.ofDays(2)); public static final TimeInterval LAST_3_DAYS = new TimeInterval(Duration.ofDays(3)); public static final TimeInterval LAST_7_DAYS = new TimeInterval(Duration.ofDays(7)); private static final ClientLogger LOGGER = new ClientLogger(TimeInterval.class); private static final String ERROR_MESSAGE = "%s is an invalid time interval. It must be in one of the " + "following ISO 8601 time interval formats: duration, startDuration/endTime, " + "startTime/endTime, startTime/endDuration"; private final Duration duration; private final OffsetDateTime startTime; private final OffsetDateTime endTime; /** * Creates an instance of {@link TimeInterval} using the provided duration. The duration is the interval that * starts from the provided duration and ends at the current time. * @param duration the duration for this query time span. */ public TimeInterval(Duration duration) { this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startTime = null; this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end {@link OffsetDateTime OffsetDateTimes}. * @param startTime The start time of the interval. * @param endTime The end time of the interval. */ public TimeInterval(OffsetDateTime startTime, OffsetDateTime endTime) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startTime The start time of the interval. * @param duration The end duration of the interval. */ public TimeInterval(OffsetDateTime startTime, Duration duration) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param duration The duration of the interval. * @param endTime The end time of the interval. */ TimeInterval(Duration duration, OffsetDateTime endTime) { this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startTime = null; } /** * Returns the duration of this {@link TimeInterval} instance. * @return the duration of this {@link TimeInterval} instance. */ public Duration getDuration() { return duration; } /** * Returns the start time of this {@link TimeInterval} instance. * @return the start time of this {@link TimeInterval} instance. */ public OffsetDateTime getStartTime() { if (startTime != null) { return startTime; } if (duration != null && endTime != null) { return endTime.minusNanos(duration.toNanos()); } return null; } /** * Returns the end time of this {@link TimeInterval} instance. * @return the end time of this {@link TimeInterval} instance. */ public OffsetDateTime getEndTime() { if (endTime != null) { return endTime; } if (startTime != null && duration != null) { return startTime.plusNanos(duration.toNanos()); } return null; } /** * Returns this {@link TimeInterval} in ISO 8601 string format. * @return ISO 8601 formatted string representation of this {@link TimeInterval} instance. */ public String toIso8601Format() { if (startTime != null && endTime != null) { return startTime + "/" + endTime; } if (startTime != null && duration != null) { return startTime + "/" + duration; } if (duration != null && endTime != null) { return duration + "/" + endTime; } return duration == null ? null : duration.toString(); } /** * This method takes an ISO 8601 formatted time interval string and returns an instance of {@link TimeInterval}. * @param value The ISO 8601 formatted time interval string. * @return An instance of {@link TimeInterval}. * @throws IllegalArgumentException if {@code value} is not in the correct format. */ public static TimeInterval parse(String value) { Objects.requireNonNull(value); String[] parts = value.split("/"); if (parts.length == 1) { Duration duration = parseDuration(parts[0]); if (duration == null || parts[0].length() + 1 == value.length()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } return new TimeInterval(duration); } if (parts.length == 2) { Duration startDuration = parseDuration(parts[0]); OffsetDateTime startTime = parseTime(parts[0]); Duration endDuration = parseDuration(parts[1]); OffsetDateTime endTime = parseTime(parts[1]); if (startDuration != null && endTime != null) { return new TimeInterval(startDuration, endTime); } if (startTime != null && endTime != null) { return new TimeInterval(startTime, endTime); } if (startTime != null && endDuration != null) { return new TimeInterval(startTime, endDuration); } } throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (duration != null && endTime != null) { sb.append("duration: ") .append(duration) .append(", ") .append("end time: ") .append(endTime); } else if (startTime != null && endTime != null) { sb.append("start time: ") .append(startTime) .append(", ") .append("end time: ") .append(endTime); } else if (startTime != null && duration != null) { sb.append("start time: ") .append(startTime) .append(", ") .append("duration: ") .append(duration); } else { sb.append("duration: ").append(duration); } sb.append("]"); return sb.toString(); } @Override @Override public int hashCode() { return Objects.hash(duration, startTime, endTime); } private static OffsetDateTime parseTime(String value) { try { return OffsetDateTime.parse(value); } catch (Exception exception) { return null; } } private static Duration parseDuration(String value) { try { return Duration.parse(value); } catch (Exception exception) { return null; } } }
@moarychan , could you please comment `LGTM` if you think this PR is OK to merge?
private Set<String> azureClientAccessTokenScopes() { Set<String> result = Optional.of(properties) .map(AADAuthenticationProperties::getAuthorizationClients) .map(clients -> clients.get(AZURE_CLIENT_REGISTRATION_ID)) .map(AuthorizationClientProperties::getScopes) .map(Collection::stream) .orElseGet(Stream::empty) .collect(Collectors.toSet()); result.addAll(azureClientOpenidScopes()); if (properties.allowedGroupNamesConfigured()) { result.add(properties.getGraphBaseUri() + "Directory.Read.All"); } else if (properties.allowedGroupIdsConfigured()) { result.add(properties.getGraphBaseUri() + "User.Read"); } return result; }
} else if (properties.allowedGroupIdsConfigured()) {
private Set<String> azureClientAccessTokenScopes() { Set<String> result = Optional.of(properties) .map(AADAuthenticationProperties::getAuthorizationClients) .map(clients -> clients.get(AZURE_CLIENT_REGISTRATION_ID)) .map(AuthorizationClientProperties::getScopes) .map(Collection::stream) .orElseGet(Stream::empty) .collect(Collectors.toSet()); result.addAll(azureClientOpenidScopes()); if (properties.allowedGroupNamesConfigured()) { result.add(properties.getGraphBaseUri() + "Directory.Read.All"); } else if (properties.allowedGroupIdsConfigured()) { result.add(properties.getGraphBaseUri() + "User.Read"); } return result; }
class AADClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> { private static final Logger LOGGER = LoggerFactory.getLogger(AADClientRegistrationRepository.class); public static final String AZURE_CLIENT_REGISTRATION_ID = "azure"; protected final AzureClientRegistration azureClient; protected final Map<String, ClientRegistration> delegatedClients; protected final Map<String, ClientRegistration> allClients; protected final AADAuthenticationProperties properties; public AADClientRegistrationRepository(AADAuthenticationProperties properties) { this.properties = properties; this.azureClient = azureClientRegistration(); this.delegatedClients = delegatedClientRegistrations(); this.allClients = allClientRegistrations(); } private AzureClientRegistration azureClientRegistration() { if (!needDelegation()) { return null; } AuthorizationClientProperties azureProperties = properties.getAuthorizationClients() .getOrDefault(AZURE_CLIENT_REGISTRATION_ID, defaultAzureAuthorizationClientProperties()); ClientRegistration.Builder builder = toClientRegistrationBuilder(AZURE_CLIENT_REGISTRATION_ID, azureProperties); Set<String> authorizationCodeScopes = azureClientAuthorizationCodeScopes(); ClientRegistration client = builder.scope(authorizationCodeScopes).build(); Set<String> accessTokenScopes = azureClientAccessTokenScopes(); if (resourceServerCount(accessTokenScopes) == 0 && resourceServerCount((authorizationCodeScopes)) > 1) { accessTokenScopes.add(properties.getGraphBaseUri() + "User.Read"); } return new AzureClientRegistration(client, accessTokenScopes); } private boolean needDelegation() { return WEB_APPLICATION == properties.getApplicationType() || WEB_APPLICATION_AND_RESOURCE_SERVER == properties.getApplicationType(); } private Map<String, ClientRegistration> delegatedClientRegistrations() { if (!needDelegation()) { return Collections.emptyMap(); } return properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> isAzureDelegatedClientRegistration(entry.getKey(), entry.getValue())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); } private Map<String, ClientRegistration> allClientRegistrations() { Map<String, ClientRegistration> result = properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> !delegatedClients.containsKey(entry.getKey())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); if (needDelegation()) { result.putAll(delegatedClients); result.put(AZURE_CLIENT_REGISTRATION_ID, azureClient.getClient()); } return Collections.unmodifiableMap(result); } private ClientRegistration.Builder toClientRegistrationBuilder(String registrationId, AuthorizationClientProperties clientProperties) { AADAuthorizationServerEndpoints endpoints = new AADAuthorizationServerEndpoints(properties.getBaseUri(), properties.getTenantId()); AuthorizationGrantType authorizationGrantType; switch (clientProperties.getAuthorizationGrantType()) { case AUTHORIZATION_CODE: authorizationGrantType = AuthorizationGrantType.AUTHORIZATION_CODE; break; case ON_BEHALF_OF: authorizationGrantType = new AuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF.getValue()); break; case CLIENT_CREDENTIALS: authorizationGrantType = AuthorizationGrantType.CLIENT_CREDENTIALS; break; default: throw new IllegalArgumentException("Unsupported authorization type " + clientProperties.getAuthorizationGrantType().getValue()); } return ClientRegistration.withRegistrationId(registrationId) .clientName(registrationId) .authorizationGrantType(authorizationGrantType) .scope(toScopes(clientProperties)) .redirectUri(properties.getRedirectUriTemplate()) .userNameAttributeName(properties.getUserNameAttribute()) .clientId(properties.getClientId()) .clientSecret(properties.getClientSecret()) .authorizationUri(endpoints.authorizationEndpoint()) .tokenUri(endpoints.tokenEndpoint()) .jwkSetUri(endpoints.jwkSetEndpoint()) .providerConfigurationMetadata(providerConfigurationMetadata(endpoints)); } private AuthorizationClientProperties defaultAzureAuthorizationClientProperties() { AuthorizationClientProperties result = new AuthorizationClientProperties(); result.setAuthorizationGrantType(AUTHORIZATION_CODE); return result; } private List<String> toScopes(AuthorizationClientProperties clientProperties) { List<String> result = clientProperties.getScopes(); if (clientProperties.isOnDemand()) { if (!result.contains("openid")) { result.add("openid"); } if (!result.contains("profile")) { result.add("profile"); } } return result; } private Map<String, Object> providerConfigurationMetadata(AADAuthorizationServerEndpoints endpoints) { Map<String, Object> result = new LinkedHashMap<>(); String endSessionEndpoint = endpoints.endSessionEndpoint(); result.put("end_session_endpoint", endSessionEndpoint); return result; } public static int resourceServerCount(Set<String> scopes) { return (int) scopes.stream() .filter(scope -> scope.contains("/")) .map(scope -> scope.substring(0, scope.lastIndexOf('/'))) .distinct() .count(); } private Set<String> azureClientAuthorizationCodeScopes() { Set<String> result = azureClientAccessTokenScopes(); result.addAll(delegatedClientsAccessTokenScopes()); return result; } private Set<String> delegatedClientsAccessTokenScopes() { return properties.getAuthorizationClients() .values() .stream() .filter(p -> !p.isOnDemand() && AUTHORIZATION_CODE.equals(p.getAuthorizationGrantType())) .flatMap(p -> p.getScopes().stream()) .collect(Collectors.toSet()); } /** * @return the scopes needed for OpenID Connect. * @see <a href="https: * @see <a href="https: */ private Set<String> azureClientOpenidScopes() { Set<String> result = new HashSet<>(); result.add("openid"); result.add("profile"); if (!properties.getAuthorizationClients().isEmpty()) { result.add("offline_access"); } return result; } private ClientRegistration toClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return toClientRegistrationBuilder(registrationId, clientProperties).build(); } private boolean isAzureDelegatedClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return !AZURE_CLIENT_REGISTRATION_ID.equals(registrationId) && AUTHORIZATION_CODE.equals(clientProperties.getAuthorizationGrantType()) && !clientProperties.isOnDemand(); } @Override public ClientRegistration findByRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return allClients.get(registrationId); } @Override public Iterator<ClientRegistration> iterator() { if (!needDelegation()) { return allClients.values().iterator(); } return Collections.singleton(azureClient.getClient()).iterator(); } public AzureClientRegistration getAzureClient() { return azureClient; } public boolean isAzureDelegatedClientRegistration(ClientRegistration client) { return delegatedClients.containsValue(client); } public boolean isAzureDelegatedClientRegistration(String registrationId) { return delegatedClients.containsKey(registrationId); } public static boolean isDefaultClient(String registrationId) { return AZURE_CLIENT_REGISTRATION_ID.equals(registrationId); } }
class AADClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> { private static final Logger LOGGER = LoggerFactory.getLogger(AADClientRegistrationRepository.class); public static final String AZURE_CLIENT_REGISTRATION_ID = "azure"; protected final AzureClientRegistration azureClient; protected final Map<String, ClientRegistration> delegatedClients; protected final Map<String, ClientRegistration> allClients; protected final AADAuthenticationProperties properties; public AADClientRegistrationRepository(AADAuthenticationProperties properties) { this.properties = properties; this.azureClient = azureClientRegistration(); this.delegatedClients = delegatedClientRegistrations(); this.allClients = allClientRegistrations(); } private AzureClientRegistration azureClientRegistration() { if (!needDelegation()) { return null; } AuthorizationClientProperties azureProperties = properties.getAuthorizationClients() .getOrDefault(AZURE_CLIENT_REGISTRATION_ID, defaultAzureAuthorizationClientProperties()); ClientRegistration.Builder builder = toClientRegistrationBuilder(AZURE_CLIENT_REGISTRATION_ID, azureProperties); Set<String> authorizationCodeScopes = azureClientAuthorizationCodeScopes(); ClientRegistration client = builder.scope(authorizationCodeScopes).build(); Set<String> accessTokenScopes = azureClientAccessTokenScopes(); if (resourceServerCount(accessTokenScopes) == 0 && resourceServerCount((authorizationCodeScopes)) > 1) { accessTokenScopes.add(properties.getGraphBaseUri() + "User.Read"); } return new AzureClientRegistration(client, accessTokenScopes); } private boolean needDelegation() { return WEB_APPLICATION == properties.getApplicationType() || WEB_APPLICATION_AND_RESOURCE_SERVER == properties.getApplicationType(); } private Map<String, ClientRegistration> delegatedClientRegistrations() { if (!needDelegation()) { return Collections.emptyMap(); } return properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> isAzureDelegatedClientRegistration(entry.getKey(), entry.getValue())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); } private Map<String, ClientRegistration> allClientRegistrations() { Map<String, ClientRegistration> result = properties.getAuthorizationClients() .entrySet() .stream() .filter(entry -> !delegatedClients.containsKey(entry.getKey())) .collect(Collectors.toMap( Map.Entry::getKey, entry -> toClientRegistration(entry.getKey(), entry.getValue()))); if (needDelegation()) { result.putAll(delegatedClients); result.put(AZURE_CLIENT_REGISTRATION_ID, azureClient.getClient()); } return Collections.unmodifiableMap(result); } private ClientRegistration.Builder toClientRegistrationBuilder(String registrationId, AuthorizationClientProperties clientProperties) { AADAuthorizationServerEndpoints endpoints = new AADAuthorizationServerEndpoints(properties.getBaseUri(), properties.getTenantId()); AuthorizationGrantType authorizationGrantType; switch (clientProperties.getAuthorizationGrantType()) { case AUTHORIZATION_CODE: authorizationGrantType = AuthorizationGrantType.AUTHORIZATION_CODE; break; case ON_BEHALF_OF: authorizationGrantType = new AuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF.getValue()); break; case CLIENT_CREDENTIALS: authorizationGrantType = AuthorizationGrantType.CLIENT_CREDENTIALS; break; default: throw new IllegalArgumentException("Unsupported authorization type " + clientProperties.getAuthorizationGrantType().getValue()); } return ClientRegistration.withRegistrationId(registrationId) .clientName(registrationId) .authorizationGrantType(authorizationGrantType) .scope(toScopes(clientProperties)) .redirectUri(properties.getRedirectUriTemplate()) .userNameAttributeName(properties.getUserNameAttribute()) .clientId(properties.getClientId()) .clientSecret(properties.getClientSecret()) .authorizationUri(endpoints.authorizationEndpoint()) .tokenUri(endpoints.tokenEndpoint()) .jwkSetUri(endpoints.jwkSetEndpoint()) .providerConfigurationMetadata(providerConfigurationMetadata(endpoints)); } private AuthorizationClientProperties defaultAzureAuthorizationClientProperties() { AuthorizationClientProperties result = new AuthorizationClientProperties(); result.setAuthorizationGrantType(AUTHORIZATION_CODE); return result; } private List<String> toScopes(AuthorizationClientProperties clientProperties) { List<String> result = clientProperties.getScopes(); if (clientProperties.isOnDemand()) { if (!result.contains("openid")) { result.add("openid"); } if (!result.contains("profile")) { result.add("profile"); } } return result; } private Map<String, Object> providerConfigurationMetadata(AADAuthorizationServerEndpoints endpoints) { Map<String, Object> result = new LinkedHashMap<>(); String endSessionEndpoint = endpoints.endSessionEndpoint(); result.put("end_session_endpoint", endSessionEndpoint); return result; } public static int resourceServerCount(Set<String> scopes) { return (int) scopes.stream() .filter(scope -> scope.contains("/")) .map(scope -> scope.substring(0, scope.lastIndexOf('/'))) .distinct() .count(); } private Set<String> azureClientAuthorizationCodeScopes() { Set<String> result = azureClientAccessTokenScopes(); result.addAll(delegatedClientsAccessTokenScopes()); return result; } private Set<String> delegatedClientsAccessTokenScopes() { return properties.getAuthorizationClients() .values() .stream() .filter(p -> !p.isOnDemand() && AUTHORIZATION_CODE.equals(p.getAuthorizationGrantType())) .flatMap(p -> p.getScopes().stream()) .collect(Collectors.toSet()); } /** * @return the scopes needed for OpenID Connect. * @see <a href="https: * @see <a href="https: */ private Set<String> azureClientOpenidScopes() { Set<String> result = new HashSet<>(); result.add("openid"); result.add("profile"); if (!properties.getAuthorizationClients().isEmpty()) { result.add("offline_access"); } return result; } private ClientRegistration toClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return toClientRegistrationBuilder(registrationId, clientProperties).build(); } private boolean isAzureDelegatedClientRegistration(String registrationId, AuthorizationClientProperties clientProperties) { return !AZURE_CLIENT_REGISTRATION_ID.equals(registrationId) && AUTHORIZATION_CODE.equals(clientProperties.getAuthorizationGrantType()) && !clientProperties.isOnDemand(); } @Override public ClientRegistration findByRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return allClients.get(registrationId); } @Override public Iterator<ClientRegistration> iterator() { if (!needDelegation()) { return allClients.values().iterator(); } return Collections.singleton(azureClient.getClient()).iterator(); } public AzureClientRegistration getAzureClient() { return azureClient; } public boolean isAzureDelegatedClientRegistration(ClientRegistration client) { return delegatedClients.containsValue(client); } public boolean isAzureDelegatedClientRegistration(String registrationId) { return delegatedClients.containsKey(registrationId); } public static boolean isDefaultClient(String registrationId) { return AZURE_CLIENT_REGISTRATION_ID.equals(registrationId); } }
Maybe it would be better to make the `doAfterRequest` handler a method which accepts a `ResponseTimeoutHandler` and if `AZURE_RESPONSE_TIMEOUT` isn't configured it uses the default one in the builder. This would be better as we aren't creating a handler that will be thrown away anymore.
public Mono<HttpResponse> send(HttpRequest request, Context context) { Objects.requireNonNull(request.getHttpMethod(), "'request.getHttpMethod()' cannot be null."); Objects.requireNonNull(request.getUrl(), "'request.getUrl()' cannot be null."); Objects.requireNonNull(request.getUrl().getProtocol(), "'request.getUrl().getProtocol()' cannot be null."); boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false); reactor.netty.http.client.HttpClient client = this.nettyClient; Optional<Object> requestResponseTimeout = context.getData(AZURE_RESPONSE_TIMEOUT); if (requestResponseTimeout.isPresent()) { client = nettyClient.doAfterRequest((req, connection) -> { long responseTimeoutMillis = ((Duration) requestResponseTimeout.get()).toMillis(); connection.removeHandler(WriteTimeoutHandler.HANDLER_NAME) .removeHandler(ResponseTimeoutHandler.HANDLER_NAME) .addHandlerLast(ResponseTimeoutHandler.HANDLER_NAME, new ResponseTimeoutHandler(responseTimeoutMillis)); }); } return client .request(HttpMethod.valueOf(request.getHttpMethod().toString())) .uri(request.getUrl().toString()) .send(bodySendDelegate(request)) .responseConnection(responseDelegate(request, disableBufferCopy, eagerlyReadResponse)) .single() .onErrorMap(throwable -> { if (throwable instanceof SSLException) { if (throwable.getCause() instanceof ProxyConnectException) { return throwable.getCause(); } } return throwable; }) .retryWhen(Retry.max(1).filter(throwable -> throwable instanceof ProxyConnectException) .onRetryExhaustedThrow((ignoredSpec, signal) -> signal.failure())); }
.addHandlerLast(ResponseTimeoutHandler.HANDLER_NAME,
public Mono<HttpResponse> send(HttpRequest request, Context context) { Objects.requireNonNull(request.getHttpMethod(), "'request.getHttpMethod()' cannot be null."); Objects.requireNonNull(request.getUrl(), "'request.getUrl()' cannot be null."); Objects.requireNonNull(request.getUrl().getProtocol(), "'request.getUrl().getProtocol()' cannot be null."); boolean eagerlyReadResponse = (boolean) context.getData("azure-eagerly-read-response").orElse(false); Optional<Object> requestResponseTimeout = context.getData(AZURE_RESPONSE_TIMEOUT); long effectiveResponseTimeout = requestResponseTimeout .map(timeoutDuration -> ((Duration) timeoutDuration).toMillis()) .orElse(this.responseTimeout); return nettyClient .doOnRequest((r, connection) -> addWriteTimeoutHandler(connection, writeTimeout)) .doAfterRequest((r, connection) -> addResponseTimeoutHandler(connection, effectiveResponseTimeout)) .doOnResponse((response, connection) -> addReadTimeoutHandler(connection, readTimeout)) .doAfterResponseSuccess((response, connection) -> removeReadTimeoutHandler(connection)) .request(HttpMethod.valueOf(request.getHttpMethod().toString())) .uri(request.getUrl().toString()) .send(bodySendDelegate(request)) .responseConnection(responseDelegate(request, disableBufferCopy, eagerlyReadResponse)) .single() .onErrorMap(throwable -> { if (throwable instanceof SSLException) { if (throwable.getCause() instanceof ProxyConnectException) { return throwable.getCause(); } } return throwable; }) .retryWhen(Retry.max(1).filter(throwable -> throwable instanceof ProxyConnectException) .onRetryExhaustedThrow((ignoredSpec, signal) -> signal.failure())); }
class NettyAsyncHttpClient implements HttpClient { private static final String AZURE_RESPONSE_TIMEOUT = "azure-response-timeout"; private final boolean disableBufferCopy; final reactor.netty.http.client.HttpClient nettyClient; /** * Creates NettyAsyncHttpClient with provided http client. * * @param nettyClient the reactor-netty http client * @param disableBufferCopy Determines whether deep cloning of response buffers should be disabled. */ NettyAsyncHttpClient(reactor.netty.http.client.HttpClient nettyClient, boolean disableBufferCopy) { this.nettyClient = nettyClient; this.disableBufferCopy = disableBufferCopy; } /** * {@inheritDoc} */ @Override public Mono<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override /** * Delegate to send the request content. * * @param restRequest the Rest request contains the body to be sent * @return a delegate upon invocation sets the request body in reactor-netty outbound object */ private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate( final HttpRequest restRequest) { return (reactorNettyRequest, reactorNettyOutbound) -> { for (HttpHeader hdr : restRequest.getHeaders()) { if (reactorNettyRequest.requestHeaders().contains(hdr.getName())) { final AtomicBoolean first = new AtomicBoolean(true); hdr.getValuesList().forEach(value -> { if (first.compareAndSet(true, false)) { reactorNettyRequest.header(hdr.getName(), value); } else { reactorNettyRequest.addHeader(hdr.getName(), value); } }); } else { hdr.getValuesList().forEach(value -> reactorNettyRequest.addHeader(hdr.getName(), value)); } } if (restRequest.getBody() != null) { Flux<ByteBuf> nettyByteBufFlux = restRequest.getBody().map(Unpooled::wrappedBuffer); return reactorNettyOutbound.send(nettyByteBufFlux); } else { return reactorNettyOutbound; } }; } /** * Delegate to receive response. * * @param restRequest the Rest request whose response this delegate handles * @param disableBufferCopy Flag indicating if the network response shouldn't be buffered. * @param eagerlyReadResponse Flag indicating if the network response should be eagerly read into memory. * @return a delegate upon invocation setup Rest response object */ private static BiFunction<HttpClientResponse, Connection, Publisher<HttpResponse>> responseDelegate( final HttpRequest restRequest, final boolean disableBufferCopy, final boolean eagerlyReadResponse) { return (reactorNettyResponse, reactorNettyConnection) -> { /* * If we are eagerly reading the response into memory we can ignore the disable buffer copy flag as we * MUST deep copy the buffer to ensure it can safely be used downstream. */ if (eagerlyReadResponse) { Flux<ByteBuffer> body = reactorNettyConnection.inbound().receive().asByteBuffer() .doFinally(ignored -> closeConnection(reactorNettyConnection)); return FluxUtil.collectBytesFromNetworkResponse(body, new NettyToAzureCoreHttpHeadersWrapper(reactorNettyResponse.responseHeaders())) .map(bytes -> new NettyAsyncHttpBufferedResponse(reactorNettyResponse, restRequest, bytes)); } else { return Mono.just(new NettyAsyncHttpResponse(reactorNettyResponse, reactorNettyConnection, restRequest, disableBufferCopy)); } }; } }
class NettyAsyncHttpClient implements HttpClient { private static final String AZURE_RESPONSE_TIMEOUT = "azure-response-timeout"; private final boolean disableBufferCopy; private final long readTimeout; private final long writeTimeout; private final long responseTimeout; final reactor.netty.http.client.HttpClient nettyClient; /** * Creates NettyAsyncHttpClient with provided http client. * * @param nettyClient the reactor-netty http client * @param disableBufferCopy Determines whether deep cloning of response buffers should be disabled. */ NettyAsyncHttpClient(reactor.netty.http.client.HttpClient nettyClient, boolean disableBufferCopy, long readTimeout, long writeTimeout, long responseTimeout) { this.nettyClient = nettyClient; this.disableBufferCopy = disableBufferCopy; this.readTimeout = readTimeout; this.writeTimeout = writeTimeout; this.responseTimeout = responseTimeout; } /** * {@inheritDoc} */ @Override public Mono<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override /** * Delegate to send the request content. * * @param restRequest the Rest request contains the body to be sent * @return a delegate upon invocation sets the request body in reactor-netty outbound object */ private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate( final HttpRequest restRequest) { return (reactorNettyRequest, reactorNettyOutbound) -> { for (HttpHeader hdr : restRequest.getHeaders()) { if (reactorNettyRequest.requestHeaders().contains(hdr.getName())) { final AtomicBoolean first = new AtomicBoolean(true); hdr.getValuesList().forEach(value -> { if (first.compareAndSet(true, false)) { reactorNettyRequest.header(hdr.getName(), value); } else { reactorNettyRequest.addHeader(hdr.getName(), value); } }); } else { hdr.getValuesList().forEach(value -> reactorNettyRequest.addHeader(hdr.getName(), value)); } } if (restRequest.getBody() != null) { Flux<ByteBuf> nettyByteBufFlux = restRequest.getBody().map(Unpooled::wrappedBuffer); return reactorNettyOutbound.send(nettyByteBufFlux); } else { return reactorNettyOutbound; } }; } /** * Delegate to receive response. * * @param restRequest the Rest request whose response this delegate handles * @param disableBufferCopy Flag indicating if the network response shouldn't be buffered. * @param eagerlyReadResponse Flag indicating if the network response should be eagerly read into memory. * @return a delegate upon invocation setup Rest response object */ private static BiFunction<HttpClientResponse, Connection, Publisher<HttpResponse>> responseDelegate( final HttpRequest restRequest, final boolean disableBufferCopy, final boolean eagerlyReadResponse) { return (reactorNettyResponse, reactorNettyConnection) -> { /* * If we are eagerly reading the response into memory we can ignore the disable buffer copy flag as we * MUST deep copy the buffer to ensure it can safely be used downstream. */ if (eagerlyReadResponse) { Flux<ByteBuffer> body = reactorNettyConnection.inbound().receive().asByteBuffer() .doFinally(ignored -> closeConnection(reactorNettyConnection)); return FluxUtil.collectBytesFromNetworkResponse(body, new NettyToAzureCoreHttpHeadersWrapper(reactorNettyResponse.responseHeaders())) .map(bytes -> new NettyAsyncHttpBufferedResponse(reactorNettyResponse, restRequest, bytes)); } else { return Mono.just(new NettyAsyncHttpResponse(reactorNettyResponse, reactorNettyConnection, restRequest, disableBufferCopy)); } }; } /* * Adds the write timeout handler once the request is ready to begin sending. */ private static void addWriteTimeoutHandler(Connection connection, long timeoutMillis) { connection.addHandlerLast(WriteTimeoutHandler.HANDLER_NAME, new WriteTimeoutHandler(timeoutMillis)); } /* * First removes the write timeout handler from the connection as the request has finished sending, then adds the * response timeout handler. */ private static void addResponseTimeoutHandler(Connection connection, long timeoutMillis) { connection.removeHandler(WriteTimeoutHandler.HANDLER_NAME) .addHandlerLast(ResponseTimeoutHandler.HANDLER_NAME, new ResponseTimeoutHandler(timeoutMillis)); } /* * First removes the response timeout handler from the connection as the response has been received, then adds the * read timeout handler. */ private static void addReadTimeoutHandler(Connection connection, long timeoutMillis) { connection.removeHandler(ResponseTimeoutHandler.HANDLER_NAME) .addHandlerLast(ReadTimeoutHandler.HANDLER_NAME, new ReadTimeoutHandler(timeoutMillis)); } /* * Removes the read timeout handler as the complete response has been received. */ private static void removeReadTimeoutHandler(Connection connection) { connection.removeHandler(ReadTimeoutHandler.HANDLER_NAME); } }
can we follow the same pattern as the other else if here? ```java else if (cfg.isEncryptionEnabled()) ``` instead of ```java else { if (cfg.isEncryptionEnabled()) } ```
public static void main(String[] args) throws Exception { try { LOGGER.debug("Parsing the arguments ..."); Configuration cfg = new Configuration(); cfg.tryGetValuesFromSystem(); JCommander jcommander = new JCommander(cfg, args); if (cfg.isHelp()) { jcommander.usage(); return; } validateConfiguration(cfg); if (cfg.isSync()) { syncBenchmark(cfg); } else { if (cfg.getOperationType().equals(ReadThroughputWithMultipleClients)) { asyncMultiClientBenchmark(cfg); } else if (cfg.getOperationType().equals(CtlWorkload)) { asyncCtlWorkload(cfg); } else if (cfg.getOperationType().equals(LinkedInCtlWorkload)) { linkedInCtlWorkload(cfg); } else { if (cfg.isEncryptionEnabled()) { asyncEncryptionBenchmark(cfg); } else { asyncBenchmark(cfg); } } } } catch (ParameterException e) { System.err.println("INVALID Usage: " + e.getMessage()); System.err.println("Try '-help' for more information."); throw e; } }
if (cfg.isEncryptionEnabled()) {
public static void main(String[] args) throws Exception { try { LOGGER.debug("Parsing the arguments ..."); Configuration cfg = new Configuration(); cfg.tryGetValuesFromSystem(); JCommander jcommander = new JCommander(cfg, args); if (cfg.isHelp()) { jcommander.usage(); return; } validateConfiguration(cfg); if (cfg.isSync()) { syncBenchmark(cfg); } else { if (cfg.getOperationType().equals(ReadThroughputWithMultipleClients)) { asyncMultiClientBenchmark(cfg); } else if (cfg.getOperationType().equals(CtlWorkload)) { asyncCtlWorkload(cfg); } else if (cfg.getOperationType().equals(LinkedInCtlWorkload)) { linkedInCtlWorkload(cfg); } else if (cfg.isEncryptionEnabled()) { asyncEncryptionBenchmark(cfg); } else { asyncBenchmark(cfg); } } } catch (ParameterException e) { System.err.println("INVALID Usage: " + e.getMessage()); System.err.println("Try '-help' for more information."); throw e; } }
class Main { private final static Logger LOGGER = LoggerFactory.getLogger(Main.class); private static void validateConfiguration(Configuration cfg) { switch (cfg.getOperationType()) { case WriteLatency: case WriteThroughput: break; default: if (!Boolean.parseBoolean(cfg.isContentResponseOnWriteEnabled())) { throw new IllegalArgumentException("contentResponseOnWriteEnabled parameter can only be set to false " + "for write latency and write throughput operations"); } } switch (cfg.getOperationType()) { case ReadLatency: case ReadThroughput: break; default: if (cfg.getSparsityWaitTime() != null) { throw new IllegalArgumentException("sparsityWaitTime is not supported for " + cfg.getOperationType()); } } } private static void syncBenchmark(Configuration cfg) throws Exception { LOGGER.info("Sync benchmark ..."); SyncBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case ReadThroughput: case ReadLatency: benchmark = new SyncReadBenchmark(cfg); break; case WriteLatency: case WriteThroughput: benchmark = new SyncWriteBenchmark(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async benchmark ..."); AsyncBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case WriteThroughput: case WriteLatency: benchmark = new AsyncWriteBenchmark(cfg); break; case ReadThroughput: case ReadLatency: benchmark = new AsyncReadBenchmark(cfg); break; case QueryCross: case QuerySingle: case QueryParallel: case QueryOrderby: case QueryAggregate: case QueryTopOrderby: case QueryAggregateTopOrderby: case QueryInClauseParallel: case ReadAllItemsOfLogicalPartition: benchmark = new AsyncQueryBenchmark(cfg); break; case Mixed: benchmark = new AsyncMixedBenchmark(cfg); break; case QuerySingleMany: benchmark = new AsyncQuerySinglePartitionMultiple(cfg); break; case ReadMyWrites: benchmark = new ReadMyWriteWorkflow(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncEncryptionBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async encryption benchmark ..."); AsyncEncryptionBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case WriteThroughput: case WriteLatency: benchmark = new AsyncEncryptionWriteBenchmark(cfg); break; case ReadThroughput: case ReadLatency: benchmark = new AsyncEncryptionReadBenchmark(cfg); break; case QueryCross: case QuerySingle: case QueryParallel: case QueryOrderby: case QueryTopOrderby: case QueryInClauseParallel: benchmark = new AsyncEncryptionQueryBenchmark(cfg); break; case QuerySingleMany: benchmark = new AsyncEncryptionQuerySinglePartitionMultiple(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncMultiClientBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async multi client benchmark ..."); AsynReadWithMultipleClients<?> benchmark = null; try { benchmark = new AsynReadWithMultipleClients<>(cfg); LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncCtlWorkload(Configuration cfg) throws Exception { LOGGER.info("Async ctl workload"); AsyncCtlWorkload benchmark = null; try { benchmark = new AsyncCtlWorkload(cfg); LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void linkedInCtlWorkload(Configuration cfg) { LOGGER.info("Executing the LinkedIn ctl workload"); LICtlWorkload workload = null; try { workload = new LICtlWorkload(cfg); LOGGER.info("Setting up the LinkedIn ctl workload"); workload.setup(); LOGGER.info("Starting the LinkedIn ctl workload"); workload.run(); } catch (Exception e) { LOGGER.error("Exception received while executing the LinkedIn ctl workload", e); throw e; } finally { Optional.ofNullable(workload) .ifPresent(LICtlWorkload::shutdown); } LOGGER.info("Completed LinkedIn ctl workload execution"); } }
class Main { private final static Logger LOGGER = LoggerFactory.getLogger(Main.class); private static void validateConfiguration(Configuration cfg) { switch (cfg.getOperationType()) { case WriteLatency: case WriteThroughput: break; default: if (!Boolean.parseBoolean(cfg.isContentResponseOnWriteEnabled())) { throw new IllegalArgumentException("contentResponseOnWriteEnabled parameter can only be set to false " + "for write latency and write throughput operations"); } } switch (cfg.getOperationType()) { case ReadLatency: case ReadThroughput: break; default: if (cfg.getSparsityWaitTime() != null) { throw new IllegalArgumentException("sparsityWaitTime is not supported for " + cfg.getOperationType()); } } } private static void syncBenchmark(Configuration cfg) throws Exception { LOGGER.info("Sync benchmark ..."); SyncBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case ReadThroughput: case ReadLatency: benchmark = new SyncReadBenchmark(cfg); break; case WriteLatency: case WriteThroughput: benchmark = new SyncWriteBenchmark(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async benchmark ..."); AsyncBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case WriteThroughput: case WriteLatency: benchmark = new AsyncWriteBenchmark(cfg); break; case ReadThroughput: case ReadLatency: benchmark = new AsyncReadBenchmark(cfg); break; case QueryCross: case QuerySingle: case QueryParallel: case QueryOrderby: case QueryAggregate: case QueryTopOrderby: case QueryAggregateTopOrderby: case QueryInClauseParallel: case ReadAllItemsOfLogicalPartition: benchmark = new AsyncQueryBenchmark(cfg); break; case Mixed: benchmark = new AsyncMixedBenchmark(cfg); break; case QuerySingleMany: benchmark = new AsyncQuerySinglePartitionMultiple(cfg); break; case ReadMyWrites: benchmark = new ReadMyWriteWorkflow(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncEncryptionBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async encryption benchmark ..."); AsyncEncryptionBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case WriteThroughput: case WriteLatency: benchmark = new AsyncEncryptionWriteBenchmark(cfg); break; case ReadThroughput: case ReadLatency: benchmark = new AsyncEncryptionReadBenchmark(cfg); break; case QueryCross: case QuerySingle: case QueryParallel: case QueryOrderby: case QueryTopOrderby: case QueryInClauseParallel: benchmark = new AsyncEncryptionQueryBenchmark(cfg); break; case QuerySingleMany: benchmark = new AsyncEncryptionQuerySinglePartitionMultiple(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncMultiClientBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async multi client benchmark ..."); AsynReadWithMultipleClients<?> benchmark = null; try { benchmark = new AsynReadWithMultipleClients<>(cfg); LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncCtlWorkload(Configuration cfg) throws Exception { LOGGER.info("Async ctl workload"); AsyncCtlWorkload benchmark = null; try { benchmark = new AsyncCtlWorkload(cfg); LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void linkedInCtlWorkload(Configuration cfg) { LOGGER.info("Executing the LinkedIn ctl workload"); LICtlWorkload workload = null; try { workload = new LICtlWorkload(cfg); LOGGER.info("Setting up the LinkedIn ctl workload"); workload.setup(); LOGGER.info("Starting the LinkedIn ctl workload"); workload.run(); } catch (Exception e) { LOGGER.error("Exception received while executing the LinkedIn ctl workload", e); throw e; } finally { Optional.ofNullable(workload) .ifPresent(LICtlWorkload::shutdown); } LOGGER.info("Completed LinkedIn ctl workload execution"); } }
done
public static void main(String[] args) throws Exception { try { LOGGER.debug("Parsing the arguments ..."); Configuration cfg = new Configuration(); cfg.tryGetValuesFromSystem(); JCommander jcommander = new JCommander(cfg, args); if (cfg.isHelp()) { jcommander.usage(); return; } validateConfiguration(cfg); if (cfg.isSync()) { syncBenchmark(cfg); } else { if (cfg.getOperationType().equals(ReadThroughputWithMultipleClients)) { asyncMultiClientBenchmark(cfg); } else if (cfg.getOperationType().equals(CtlWorkload)) { asyncCtlWorkload(cfg); } else if (cfg.getOperationType().equals(LinkedInCtlWorkload)) { linkedInCtlWorkload(cfg); } else { if (cfg.isEncryptionEnabled()) { asyncEncryptionBenchmark(cfg); } else { asyncBenchmark(cfg); } } } } catch (ParameterException e) { System.err.println("INVALID Usage: " + e.getMessage()); System.err.println("Try '-help' for more information."); throw e; } }
if (cfg.isEncryptionEnabled()) {
public static void main(String[] args) throws Exception { try { LOGGER.debug("Parsing the arguments ..."); Configuration cfg = new Configuration(); cfg.tryGetValuesFromSystem(); JCommander jcommander = new JCommander(cfg, args); if (cfg.isHelp()) { jcommander.usage(); return; } validateConfiguration(cfg); if (cfg.isSync()) { syncBenchmark(cfg); } else { if (cfg.getOperationType().equals(ReadThroughputWithMultipleClients)) { asyncMultiClientBenchmark(cfg); } else if (cfg.getOperationType().equals(CtlWorkload)) { asyncCtlWorkload(cfg); } else if (cfg.getOperationType().equals(LinkedInCtlWorkload)) { linkedInCtlWorkload(cfg); } else if (cfg.isEncryptionEnabled()) { asyncEncryptionBenchmark(cfg); } else { asyncBenchmark(cfg); } } } catch (ParameterException e) { System.err.println("INVALID Usage: " + e.getMessage()); System.err.println("Try '-help' for more information."); throw e; } }
class Main { private final static Logger LOGGER = LoggerFactory.getLogger(Main.class); private static void validateConfiguration(Configuration cfg) { switch (cfg.getOperationType()) { case WriteLatency: case WriteThroughput: break; default: if (!Boolean.parseBoolean(cfg.isContentResponseOnWriteEnabled())) { throw new IllegalArgumentException("contentResponseOnWriteEnabled parameter can only be set to false " + "for write latency and write throughput operations"); } } switch (cfg.getOperationType()) { case ReadLatency: case ReadThroughput: break; default: if (cfg.getSparsityWaitTime() != null) { throw new IllegalArgumentException("sparsityWaitTime is not supported for " + cfg.getOperationType()); } } } private static void syncBenchmark(Configuration cfg) throws Exception { LOGGER.info("Sync benchmark ..."); SyncBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case ReadThroughput: case ReadLatency: benchmark = new SyncReadBenchmark(cfg); break; case WriteLatency: case WriteThroughput: benchmark = new SyncWriteBenchmark(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async benchmark ..."); AsyncBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case WriteThroughput: case WriteLatency: benchmark = new AsyncWriteBenchmark(cfg); break; case ReadThroughput: case ReadLatency: benchmark = new AsyncReadBenchmark(cfg); break; case QueryCross: case QuerySingle: case QueryParallel: case QueryOrderby: case QueryAggregate: case QueryTopOrderby: case QueryAggregateTopOrderby: case QueryInClauseParallel: case ReadAllItemsOfLogicalPartition: benchmark = new AsyncQueryBenchmark(cfg); break; case Mixed: benchmark = new AsyncMixedBenchmark(cfg); break; case QuerySingleMany: benchmark = new AsyncQuerySinglePartitionMultiple(cfg); break; case ReadMyWrites: benchmark = new ReadMyWriteWorkflow(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncEncryptionBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async encryption benchmark ..."); AsyncEncryptionBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case WriteThroughput: case WriteLatency: benchmark = new AsyncEncryptionWriteBenchmark(cfg); break; case ReadThroughput: case ReadLatency: benchmark = new AsyncEncryptionReadBenchmark(cfg); break; case QueryCross: case QuerySingle: case QueryParallel: case QueryOrderby: case QueryTopOrderby: case QueryInClauseParallel: benchmark = new AsyncEncryptionQueryBenchmark(cfg); break; case QuerySingleMany: benchmark = new AsyncEncryptionQuerySinglePartitionMultiple(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncMultiClientBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async multi client benchmark ..."); AsynReadWithMultipleClients<?> benchmark = null; try { benchmark = new AsynReadWithMultipleClients<>(cfg); LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncCtlWorkload(Configuration cfg) throws Exception { LOGGER.info("Async ctl workload"); AsyncCtlWorkload benchmark = null; try { benchmark = new AsyncCtlWorkload(cfg); LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void linkedInCtlWorkload(Configuration cfg) { LOGGER.info("Executing the LinkedIn ctl workload"); LICtlWorkload workload = null; try { workload = new LICtlWorkload(cfg); LOGGER.info("Setting up the LinkedIn ctl workload"); workload.setup(); LOGGER.info("Starting the LinkedIn ctl workload"); workload.run(); } catch (Exception e) { LOGGER.error("Exception received while executing the LinkedIn ctl workload", e); throw e; } finally { Optional.ofNullable(workload) .ifPresent(LICtlWorkload::shutdown); } LOGGER.info("Completed LinkedIn ctl workload execution"); } }
class Main { private final static Logger LOGGER = LoggerFactory.getLogger(Main.class); private static void validateConfiguration(Configuration cfg) { switch (cfg.getOperationType()) { case WriteLatency: case WriteThroughput: break; default: if (!Boolean.parseBoolean(cfg.isContentResponseOnWriteEnabled())) { throw new IllegalArgumentException("contentResponseOnWriteEnabled parameter can only be set to false " + "for write latency and write throughput operations"); } } switch (cfg.getOperationType()) { case ReadLatency: case ReadThroughput: break; default: if (cfg.getSparsityWaitTime() != null) { throw new IllegalArgumentException("sparsityWaitTime is not supported for " + cfg.getOperationType()); } } } private static void syncBenchmark(Configuration cfg) throws Exception { LOGGER.info("Sync benchmark ..."); SyncBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case ReadThroughput: case ReadLatency: benchmark = new SyncReadBenchmark(cfg); break; case WriteLatency: case WriteThroughput: benchmark = new SyncWriteBenchmark(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async benchmark ..."); AsyncBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case WriteThroughput: case WriteLatency: benchmark = new AsyncWriteBenchmark(cfg); break; case ReadThroughput: case ReadLatency: benchmark = new AsyncReadBenchmark(cfg); break; case QueryCross: case QuerySingle: case QueryParallel: case QueryOrderby: case QueryAggregate: case QueryTopOrderby: case QueryAggregateTopOrderby: case QueryInClauseParallel: case ReadAllItemsOfLogicalPartition: benchmark = new AsyncQueryBenchmark(cfg); break; case Mixed: benchmark = new AsyncMixedBenchmark(cfg); break; case QuerySingleMany: benchmark = new AsyncQuerySinglePartitionMultiple(cfg); break; case ReadMyWrites: benchmark = new ReadMyWriteWorkflow(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncEncryptionBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async encryption benchmark ..."); AsyncEncryptionBenchmark<?> benchmark = null; try { switch (cfg.getOperationType()) { case WriteThroughput: case WriteLatency: benchmark = new AsyncEncryptionWriteBenchmark(cfg); break; case ReadThroughput: case ReadLatency: benchmark = new AsyncEncryptionReadBenchmark(cfg); break; case QueryCross: case QuerySingle: case QueryParallel: case QueryOrderby: case QueryTopOrderby: case QueryInClauseParallel: benchmark = new AsyncEncryptionQueryBenchmark(cfg); break; case QuerySingleMany: benchmark = new AsyncEncryptionQuerySinglePartitionMultiple(cfg); break; default: throw new RuntimeException(cfg.getOperationType() + " is not supported"); } LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncMultiClientBenchmark(Configuration cfg) throws Exception { LOGGER.info("Async multi client benchmark ..."); AsynReadWithMultipleClients<?> benchmark = null; try { benchmark = new AsynReadWithMultipleClients<>(cfg); LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void asyncCtlWorkload(Configuration cfg) throws Exception { LOGGER.info("Async ctl workload"); AsyncCtlWorkload benchmark = null; try { benchmark = new AsyncCtlWorkload(cfg); LOGGER.info("Starting {}", cfg.getOperationType()); benchmark.run(); } finally { if (benchmark != null) { benchmark.shutdown(); } } } private static void linkedInCtlWorkload(Configuration cfg) { LOGGER.info("Executing the LinkedIn ctl workload"); LICtlWorkload workload = null; try { workload = new LICtlWorkload(cfg); LOGGER.info("Setting up the LinkedIn ctl workload"); workload.setup(); LOGGER.info("Starting the LinkedIn ctl workload"); workload.run(); } catch (Exception e) { LOGGER.error("Exception received while executing the LinkedIn ctl workload", e); throw e; } finally { Optional.ofNullable(workload) .ifPresent(LICtlWorkload::shutdown); } LOGGER.info("Completed LinkedIn ctl workload execution"); } }
I don't see "release_policy" getting deserialized. Should it here?
void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.exportable = (Boolean) attributes.get("exportable"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expiresOn = epochToOffsetDateTime(attributes.get("exp")); this.createdOn = epochToOffsetDateTime(attributes.get("created")); this.updatedOn = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.recoverableDays = (Integer) attributes.get("recoverableDays"); }
this.exportable = (Boolean) attributes.get("exportable");
void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.exportable = (Boolean) attributes.get("exportable"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expiresOn = epochToOffsetDateTime(attributes.get("exp")); this.createdOn = epochToOffsetDateTime(attributes.get("created")); this.updatedOn = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.recoverableDays = (Integer) attributes.get("recoverableDays"); }
class KeyProperties { /** * Determines whether the object is enabled. */ Boolean enabled; /* * Indicates if the private key can be exported. */ Boolean exportable; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * The key version. */ String version; /** * Expiry date in UTC. */ OffsetDateTime expiresOn; /** * Creation time in UTC. */ private OffsetDateTime createdOn; /** * Last updated time in UTC. */ private OffsetDateTime updatedOn; /** * Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains * 'Purgeable', the key can be permanently deleted by a privileged user; otherwise, only the system can purge the * key, at the end of the retention interval. Possible values include: 'Purgeable', 'Recoverable+Purgeable', * 'Recoverable', 'Recoverable+ProtectedSubscription'. */ private String recoveryLevel; /** * The key name. */ String name; /** * Key identifier. */ @JsonProperty(value = "kid") String id; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will * be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. */ @JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY) private Integer recoverableDays; /* * The policy rules under which the key can be exported. */ @JsonProperty(value = "release_policy") private KeyReleasePolicy releasePolicy; /** * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. * * @return The recoverable days. */ public Integer getRecoverableDays() { return recoverableDays; } /** * Get the policy rules under which the key can be exported. * * @return The policy rules under which the key can be exported. */ public KeyReleasePolicy getReleasePolicy() { return this.releasePolicy; } /** * Set the policy rules under which the key can be exported. * * @param releasePolicy The policy rules to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setReleasePolicy(KeyReleasePolicy releasePolicy) { this.releasePolicy = releasePolicy; return this; } /** * Get the key recovery level. * * @return The key recovery level. */ public String getRecoveryLevel() { return this.recoveryLevel; } /** * Get the key name. * * @return The name of the key. */ public String getName() { return this.name; } /** * Get the enabled value. * * @return The enabled value. */ public Boolean isEnabled() { return this.enabled; } /** * Set a value that indicates if the key is enabled. * * @param enabled The enabled value to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get a flag that indicates if the private key can be exported. * * @return A flag that indicates if the private key can be exported. */ public Boolean isExportable() { return this.exportable; } /** * Set a flag that indicates if the private key can be exported. * * @param exportable A flag that indicates if the private key can be exported. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setExportable(Boolean exportable) { this.exportable = exportable; return this; } /** * Get the {@link OffsetDateTime key's notBefore time} in UTC. * * @return The {@link OffsetDateTime key's notBefore time} in UTC. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime key's notBefore time} in UTC. * * @param notBefore The {@link OffsetDateTime key's notBefore time} in UTC. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the {@link OffsetDateTime key expiration time} in UTC. * * @return The {@link OffsetDateTime key expiration time} in UTC. */ public OffsetDateTime getExpiresOn() { return this.expiresOn; } /** * Set the {@link OffsetDateTime key expiration time} in UTC. * * @param expiresOn The {@link OffsetDateTime key expiration time} in UTC. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { this.expiresOn = expiresOn; return this; } /** * Get the {@link OffsetDateTime time at which key was created} in UTC. * * @return The {@link OffsetDateTime time at which key was created} in UTC. */ public OffsetDateTime getCreatedOn() { return createdOn; } /** * Get the {@link OffsetDateTime time at which key was last updated} in UTC. * * @return The {@link OffsetDateTime time at which key was last updated} in UTC. */ public OffsetDateTime getUpdatedOn() { return updatedOn; } /** * Get the key identifier. * * @return The key identifier. */ public String getId() { return this.id; } /** * Get the tags associated with the key. * * @return The tag names and values. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the key. * * @param tags The tags to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the managed value. * * @return The managed value. */ public Boolean isManaged() { return this.managed; } /** * Get the version of the key. * * @return The version of the key. */ public String getVersion() { return this.version; } /** * Unpacks the attributes JSON response and updates the variables in the Key Attributes object. Uses Lazy Update to * set values for variables id, contentType, and id as these variables are part of main JSON body and not attributes * JSON body when the key response comes from list keys operations. * * @param attributes The key value mapping of the key attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } @JsonProperty(value = "kid") void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { this.id = keyId; try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } List<KeyOperation> getKeyOperations(List<String> jsonWebKeyOps) { List<KeyOperation> output = new ArrayList<>(); for (String keyOp : jsonWebKeyOps) { output.add(KeyOperation.fromString(keyOp)); } return output; } @SuppressWarnings("unchecked") JsonWebKey createKeyMaterialFromJson(Map<String, Object> key) { JsonWebKey outputKey = new JsonWebKey() .setY(decode((String) key.get("y"))) .setX(decode((String) key.get("x"))) .setCurveName(KeyCurveName.fromString((String) key.get("crv"))) .setKeyOps(getKeyOperations((List<String>) key.get("key_ops"))) .setT(decode((String) key.get("key_hsm"))) .setK(decode((String) key.get("k"))) .setQ(decode((String) key.get("q"))) .setP(decode((String) key.get("p"))) .setQi(decode((String) key.get("qi"))) .setDq(decode((String) key.get("dq"))) .setDp(decode((String) key.get("dp"))) .setD(decode((String) key.get("d"))) .setE(decode((String) key.get("e"))) .setN(decode((String) key.get("n"))) .setKeyType(KeyType.fromString((String) key.get("kty"))) .setId((String) key.get("kid")); unpackId((String) key.get("kid")); return outputKey; } void setManaged(boolean managed) { this.managed = managed; } private byte[] decode(String in) { if (in != null) { return Base64.getUrlDecoder().decode(in); } return null; } }
class KeyProperties { /** * Determines whether the object is enabled. */ Boolean enabled; /* * Indicates if the private key can be exported. */ Boolean exportable; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * The key version. */ String version; /** * Expiry date in UTC. */ OffsetDateTime expiresOn; /** * Creation time in UTC. */ private OffsetDateTime createdOn; /** * Last updated time in UTC. */ private OffsetDateTime updatedOn; /** * Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains * 'Purgeable', the key can be permanently deleted by a privileged user; otherwise, only the system can purge the * key, at the end of the retention interval. Possible values include: 'Purgeable', 'Recoverable+Purgeable', * 'Recoverable', 'Recoverable+ProtectedSubscription'. */ private String recoveryLevel; /** * The key name. */ String name; /** * Key identifier. */ @JsonProperty(value = "kid") String id; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will * be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. */ @JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY) private Integer recoverableDays; /* * The policy rules under which the key can be exported. */ @JsonProperty(value = "release_policy") private KeyReleasePolicy releasePolicy; /** * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. * * @return The recoverable days. */ public Integer getRecoverableDays() { return recoverableDays; } /** * Get the policy rules under which the key can be exported. * * @return The policy rules under which the key can be exported. */ public KeyReleasePolicy getReleasePolicy() { return this.releasePolicy; } /** * Set the policy rules under which the key can be exported. * * @param releasePolicy The policy rules to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setReleasePolicy(KeyReleasePolicy releasePolicy) { this.releasePolicy = releasePolicy; return this; } /** * Get the key recovery level. * * @return The key recovery level. */ public String getRecoveryLevel() { return this.recoveryLevel; } /** * Get the key name. * * @return The name of the key. */ public String getName() { return this.name; } /** * Get the enabled value. * * @return The enabled value. */ public Boolean isEnabled() { return this.enabled; } /** * Set a value that indicates if the key is enabled. * * @param enabled The enabled value to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get a flag that indicates if the private key can be exported. * * @return A flag that indicates if the private key can be exported. */ public Boolean isExportable() { return this.exportable; } /** * Set a flag that indicates if the private key can be exported. * * @param exportable A flag that indicates if the private key can be exported. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setExportable(Boolean exportable) { this.exportable = exportable; return this; } /** * Get the {@link OffsetDateTime key's notBefore time} in UTC. * * @return The {@link OffsetDateTime key's notBefore time} in UTC. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime key's notBefore time} in UTC. * * @param notBefore The {@link OffsetDateTime key's notBefore time} in UTC. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the {@link OffsetDateTime key expiration time} in UTC. * * @return The {@link OffsetDateTime key expiration time} in UTC. */ public OffsetDateTime getExpiresOn() { return this.expiresOn; } /** * Set the {@link OffsetDateTime key expiration time} in UTC. * * @param expiresOn The {@link OffsetDateTime key expiration time} in UTC. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { this.expiresOn = expiresOn; return this; } /** * Get the {@link OffsetDateTime time at which key was created} in UTC. * * @return The {@link OffsetDateTime time at which key was created} in UTC. */ public OffsetDateTime getCreatedOn() { return createdOn; } /** * Get the {@link OffsetDateTime time at which key was last updated} in UTC. * * @return The {@link OffsetDateTime time at which key was last updated} in UTC. */ public OffsetDateTime getUpdatedOn() { return updatedOn; } /** * Get the key identifier. * * @return The key identifier. */ public String getId() { return this.id; } /** * Get the tags associated with the key. * * @return The tag names and values. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the key. * * @param tags The tags to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the managed value. * * @return The managed value. */ public Boolean isManaged() { return this.managed; } /** * Get the version of the key. * * @return The version of the key. */ public String getVersion() { return this.version; } /** * Unpacks the attributes JSON response and updates the variables in the Key Attributes object. Uses Lazy Update to * set values for variables id, contentType, and id as these variables are part of main JSON body and not attributes * JSON body when the key response comes from list keys operations. * * @param attributes The key value mapping of the key attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } @JsonProperty(value = "kid") void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { this.id = keyId; try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } List<KeyOperation> getKeyOperations(List<String> jsonWebKeyOps) { List<KeyOperation> output = new ArrayList<>(); for (String keyOp : jsonWebKeyOps) { output.add(KeyOperation.fromString(keyOp)); } return output; } @SuppressWarnings("unchecked") JsonWebKey createKeyMaterialFromJson(Map<String, Object> key) { JsonWebKey outputKey = new JsonWebKey() .setY(decode((String) key.get("y"))) .setX(decode((String) key.get("x"))) .setCurveName(KeyCurveName.fromString((String) key.get("crv"))) .setKeyOps(getKeyOperations((List<String>) key.get("key_ops"))) .setT(decode((String) key.get("key_hsm"))) .setK(decode((String) key.get("k"))) .setQ(decode((String) key.get("q"))) .setP(decode((String) key.get("p"))) .setQi(decode((String) key.get("qi"))) .setDq(decode((String) key.get("dq"))) .setDp(decode((String) key.get("dp"))) .setD(decode((String) key.get("d"))) .setE(decode((String) key.get("e"))) .setN(decode((String) key.get("n"))) .setKeyType(KeyType.fromString((String) key.get("kty"))) .setId((String) key.get("kid")); unpackId((String) key.get("kid")); return outputKey; } void setManaged(boolean managed) { this.managed = managed; } private byte[] decode(String in) { if (in != null) { return Base64.getUrlDecoder().decode(in); } return null; } }
Why decode the bytes every time instead of once and return the reference? Is providing immutability required for the Java SDKs? We don't attempt to do that in .NET at least. I don't see anything in Java's guidelines apart from immutable service clients - nothing about response models.
public byte[] getData() { if (this.data == null) { return null; } return this.data.decodedBytes(); }
return this.data.decodedBytes();
public byte[] getData() { return ByteExtensions.clone(this.data); }
class KeyReleasePolicy { /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") private Base64Url data; /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Set a blob encoding the policy rules under which the key can be released. * * @param data A blob encoding the policy rules under which the key can be released. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setData(byte[] data) { if (data == null) { this.data = null; } else { this.data = Base64Url.encode(CoreUtils.clone(data)); } return this; } }
class KeyReleasePolicy { /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) private byte[] data; /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; KeyReleasePolicy() { } /** * Creates an instance of {@link KeyReleasePolicy}. * * @param data A blob encoding the policy rules under which the key can be released. */ public KeyReleasePolicy(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = ByteExtensions.clone(data); } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } }
No, this method only takes care of deserializing members that are a part of a `KeyBundle`'s `attributes`. I will, however, add a method for deserializing the `release_policy` in `KeyVaultKey`. Thanks for catching this!
void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.exportable = (Boolean) attributes.get("exportable"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expiresOn = epochToOffsetDateTime(attributes.get("exp")); this.createdOn = epochToOffsetDateTime(attributes.get("created")); this.updatedOn = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.recoverableDays = (Integer) attributes.get("recoverableDays"); }
this.exportable = (Boolean) attributes.get("exportable");
void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.exportable = (Boolean) attributes.get("exportable"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expiresOn = epochToOffsetDateTime(attributes.get("exp")); this.createdOn = epochToOffsetDateTime(attributes.get("created")); this.updatedOn = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.recoverableDays = (Integer) attributes.get("recoverableDays"); }
class KeyProperties { /** * Determines whether the object is enabled. */ Boolean enabled; /* * Indicates if the private key can be exported. */ Boolean exportable; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * The key version. */ String version; /** * Expiry date in UTC. */ OffsetDateTime expiresOn; /** * Creation time in UTC. */ private OffsetDateTime createdOn; /** * Last updated time in UTC. */ private OffsetDateTime updatedOn; /** * Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains * 'Purgeable', the key can be permanently deleted by a privileged user; otherwise, only the system can purge the * key, at the end of the retention interval. Possible values include: 'Purgeable', 'Recoverable+Purgeable', * 'Recoverable', 'Recoverable+ProtectedSubscription'. */ private String recoveryLevel; /** * The key name. */ String name; /** * Key identifier. */ @JsonProperty(value = "kid") String id; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will * be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. */ @JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY) private Integer recoverableDays; /* * The policy rules under which the key can be exported. */ @JsonProperty(value = "release_policy") private KeyReleasePolicy releasePolicy; /** * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. * * @return The recoverable days. */ public Integer getRecoverableDays() { return recoverableDays; } /** * Get the policy rules under which the key can be exported. * * @return The policy rules under which the key can be exported. */ public KeyReleasePolicy getReleasePolicy() { return this.releasePolicy; } /** * Set the policy rules under which the key can be exported. * * @param releasePolicy The policy rules to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setReleasePolicy(KeyReleasePolicy releasePolicy) { this.releasePolicy = releasePolicy; return this; } /** * Get the key recovery level. * * @return The key recovery level. */ public String getRecoveryLevel() { return this.recoveryLevel; } /** * Get the key name. * * @return The name of the key. */ public String getName() { return this.name; } /** * Get the enabled value. * * @return The enabled value. */ public Boolean isEnabled() { return this.enabled; } /** * Set a value that indicates if the key is enabled. * * @param enabled The enabled value to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get a flag that indicates if the private key can be exported. * * @return A flag that indicates if the private key can be exported. */ public Boolean isExportable() { return this.exportable; } /** * Set a flag that indicates if the private key can be exported. * * @param exportable A flag that indicates if the private key can be exported. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setExportable(Boolean exportable) { this.exportable = exportable; return this; } /** * Get the {@link OffsetDateTime key's notBefore time} in UTC. * * @return The {@link OffsetDateTime key's notBefore time} in UTC. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime key's notBefore time} in UTC. * * @param notBefore The {@link OffsetDateTime key's notBefore time} in UTC. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the {@link OffsetDateTime key expiration time} in UTC. * * @return The {@link OffsetDateTime key expiration time} in UTC. */ public OffsetDateTime getExpiresOn() { return this.expiresOn; } /** * Set the {@link OffsetDateTime key expiration time} in UTC. * * @param expiresOn The {@link OffsetDateTime key expiration time} in UTC. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { this.expiresOn = expiresOn; return this; } /** * Get the {@link OffsetDateTime time at which key was created} in UTC. * * @return The {@link OffsetDateTime time at which key was created} in UTC. */ public OffsetDateTime getCreatedOn() { return createdOn; } /** * Get the {@link OffsetDateTime time at which key was last updated} in UTC. * * @return The {@link OffsetDateTime time at which key was last updated} in UTC. */ public OffsetDateTime getUpdatedOn() { return updatedOn; } /** * Get the key identifier. * * @return The key identifier. */ public String getId() { return this.id; } /** * Get the tags associated with the key. * * @return The tag names and values. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the key. * * @param tags The tags to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the managed value. * * @return The managed value. */ public Boolean isManaged() { return this.managed; } /** * Get the version of the key. * * @return The version of the key. */ public String getVersion() { return this.version; } /** * Unpacks the attributes JSON response and updates the variables in the Key Attributes object. Uses Lazy Update to * set values for variables id, contentType, and id as these variables are part of main JSON body and not attributes * JSON body when the key response comes from list keys operations. * * @param attributes The key value mapping of the key attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } @JsonProperty(value = "kid") void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { this.id = keyId; try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } List<KeyOperation> getKeyOperations(List<String> jsonWebKeyOps) { List<KeyOperation> output = new ArrayList<>(); for (String keyOp : jsonWebKeyOps) { output.add(KeyOperation.fromString(keyOp)); } return output; } @SuppressWarnings("unchecked") JsonWebKey createKeyMaterialFromJson(Map<String, Object> key) { JsonWebKey outputKey = new JsonWebKey() .setY(decode((String) key.get("y"))) .setX(decode((String) key.get("x"))) .setCurveName(KeyCurveName.fromString((String) key.get("crv"))) .setKeyOps(getKeyOperations((List<String>) key.get("key_ops"))) .setT(decode((String) key.get("key_hsm"))) .setK(decode((String) key.get("k"))) .setQ(decode((String) key.get("q"))) .setP(decode((String) key.get("p"))) .setQi(decode((String) key.get("qi"))) .setDq(decode((String) key.get("dq"))) .setDp(decode((String) key.get("dp"))) .setD(decode((String) key.get("d"))) .setE(decode((String) key.get("e"))) .setN(decode((String) key.get("n"))) .setKeyType(KeyType.fromString((String) key.get("kty"))) .setId((String) key.get("kid")); unpackId((String) key.get("kid")); return outputKey; } void setManaged(boolean managed) { this.managed = managed; } private byte[] decode(String in) { if (in != null) { return Base64.getUrlDecoder().decode(in); } return null; } }
class KeyProperties { /** * Determines whether the object is enabled. */ Boolean enabled; /* * Indicates if the private key can be exported. */ Boolean exportable; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * The key version. */ String version; /** * Expiry date in UTC. */ OffsetDateTime expiresOn; /** * Creation time in UTC. */ private OffsetDateTime createdOn; /** * Last updated time in UTC. */ private OffsetDateTime updatedOn; /** * Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains * 'Purgeable', the key can be permanently deleted by a privileged user; otherwise, only the system can purge the * key, at the end of the retention interval. Possible values include: 'Purgeable', 'Recoverable+Purgeable', * 'Recoverable', 'Recoverable+ProtectedSubscription'. */ private String recoveryLevel; /** * The key name. */ String name; /** * Key identifier. */ @JsonProperty(value = "kid") String id; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will * be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. */ @JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY) private Integer recoverableDays; /* * The policy rules under which the key can be exported. */ @JsonProperty(value = "release_policy") private KeyReleasePolicy releasePolicy; /** * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. * * @return The recoverable days. */ public Integer getRecoverableDays() { return recoverableDays; } /** * Get the policy rules under which the key can be exported. * * @return The policy rules under which the key can be exported. */ public KeyReleasePolicy getReleasePolicy() { return this.releasePolicy; } /** * Set the policy rules under which the key can be exported. * * @param releasePolicy The policy rules to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setReleasePolicy(KeyReleasePolicy releasePolicy) { this.releasePolicy = releasePolicy; return this; } /** * Get the key recovery level. * * @return The key recovery level. */ public String getRecoveryLevel() { return this.recoveryLevel; } /** * Get the key name. * * @return The name of the key. */ public String getName() { return this.name; } /** * Get the enabled value. * * @return The enabled value. */ public Boolean isEnabled() { return this.enabled; } /** * Set a value that indicates if the key is enabled. * * @param enabled The enabled value to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get a flag that indicates if the private key can be exported. * * @return A flag that indicates if the private key can be exported. */ public Boolean isExportable() { return this.exportable; } /** * Set a flag that indicates if the private key can be exported. * * @param exportable A flag that indicates if the private key can be exported. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setExportable(Boolean exportable) { this.exportable = exportable; return this; } /** * Get the {@link OffsetDateTime key's notBefore time} in UTC. * * @return The {@link OffsetDateTime key's notBefore time} in UTC. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime key's notBefore time} in UTC. * * @param notBefore The {@link OffsetDateTime key's notBefore time} in UTC. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the {@link OffsetDateTime key expiration time} in UTC. * * @return The {@link OffsetDateTime key expiration time} in UTC. */ public OffsetDateTime getExpiresOn() { return this.expiresOn; } /** * Set the {@link OffsetDateTime key expiration time} in UTC. * * @param expiresOn The {@link OffsetDateTime key expiration time} in UTC. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { this.expiresOn = expiresOn; return this; } /** * Get the {@link OffsetDateTime time at which key was created} in UTC. * * @return The {@link OffsetDateTime time at which key was created} in UTC. */ public OffsetDateTime getCreatedOn() { return createdOn; } /** * Get the {@link OffsetDateTime time at which key was last updated} in UTC. * * @return The {@link OffsetDateTime time at which key was last updated} in UTC. */ public OffsetDateTime getUpdatedOn() { return updatedOn; } /** * Get the key identifier. * * @return The key identifier. */ public String getId() { return this.id; } /** * Get the tags associated with the key. * * @return The tag names and values. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the key. * * @param tags The tags to set. * * @return The updated {@link KeyProperties} object. */ public KeyProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the managed value. * * @return The managed value. */ public Boolean isManaged() { return this.managed; } /** * Get the version of the key. * * @return The version of the key. */ public String getVersion() { return this.version; } /** * Unpacks the attributes JSON response and updates the variables in the Key Attributes object. Uses Lazy Update to * set values for variables id, contentType, and id as these variables are part of main JSON body and not attributes * JSON body when the key response comes from list keys operations. * * @param attributes The key value mapping of the key attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } @JsonProperty(value = "kid") void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { this.id = keyId; try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } List<KeyOperation> getKeyOperations(List<String> jsonWebKeyOps) { List<KeyOperation> output = new ArrayList<>(); for (String keyOp : jsonWebKeyOps) { output.add(KeyOperation.fromString(keyOp)); } return output; } @SuppressWarnings("unchecked") JsonWebKey createKeyMaterialFromJson(Map<String, Object> key) { JsonWebKey outputKey = new JsonWebKey() .setY(decode((String) key.get("y"))) .setX(decode((String) key.get("x"))) .setCurveName(KeyCurveName.fromString((String) key.get("crv"))) .setKeyOps(getKeyOperations((List<String>) key.get("key_ops"))) .setT(decode((String) key.get("key_hsm"))) .setK(decode((String) key.get("k"))) .setQ(decode((String) key.get("q"))) .setP(decode((String) key.get("p"))) .setQi(decode((String) key.get("qi"))) .setDq(decode((String) key.get("dq"))) .setDp(decode((String) key.get("dp"))) .setD(decode((String) key.get("d"))) .setE(decode((String) key.get("e"))) .setN(decode((String) key.get("n"))) .setKeyType(KeyType.fromString((String) key.get("kty"))) .setId((String) key.get("kid")); unpackId((String) key.get("kid")); return outputKey; } void setManaged(boolean managed) { this.managed = managed; } private byte[] decode(String in) { if (in != null) { return Base64.getUrlDecoder().decode(in); } return null; } }
This is what all classes generated by AutoRest do, so I thought I would follow that pattern. That said, I don't think it's a guideline and we can probably get away without decoding every time. I'll bring it up with our Java architect/deputy architect.
public byte[] getData() { if (this.data == null) { return null; } return this.data.decodedBytes(); }
return this.data.decodedBytes();
public byte[] getData() { return ByteExtensions.clone(this.data); }
class KeyReleasePolicy { /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") private Base64Url data; /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Set a blob encoding the policy rules under which the key can be released. * * @param data A blob encoding the policy rules under which the key can be released. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setData(byte[] data) { if (data == null) { this.data = null; } else { this.data = Base64Url.encode(CoreUtils.clone(data)); } return this; } }
class KeyReleasePolicy { /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) private byte[] data; /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; KeyReleasePolicy() { } /** * Creates an instance of {@link KeyReleasePolicy}. * * @param data A blob encoding the policy rules under which the key can be released. */ public KeyReleasePolicy(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = ByteExtensions.clone(data); } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } }
Now that I think about it, I think we do this to ensure the payload is properly encoded when sending it through the wire. I will still discuss this with them though.
public byte[] getData() { if (this.data == null) { return null; } return this.data.decodedBytes(); }
return this.data.decodedBytes();
public byte[] getData() { return ByteExtensions.clone(this.data); }
class KeyReleasePolicy { /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") private Base64Url data; /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Set a blob encoding the policy rules under which the key can be released. * * @param data A blob encoding the policy rules under which the key can be released. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setData(byte[] data) { if (data == null) { this.data = null; } else { this.data = Base64Url.encode(CoreUtils.clone(data)); } return this; } }
class KeyReleasePolicy { /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) private byte[] data; /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; KeyReleasePolicy() { } /** * Creates an instance of {@link KeyReleasePolicy}. * * @param data A blob encoding the policy rules under which the key can be released. */ public KeyReleasePolicy(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = ByteExtensions.clone(data); } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } }
Just heard back: we do this when the swagger specification marks a field as `base64url`. I don't think it should be much of a performance issue, I wouldn't expect people to access this field an overwhelming amount of times.
public byte[] getData() { if (this.data == null) { return null; } return this.data.decodedBytes(); }
return this.data.decodedBytes();
public byte[] getData() { return ByteExtensions.clone(this.data); }
class KeyReleasePolicy { /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") private Base64Url data; /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Set a blob encoding the policy rules under which the key can be released. * * @param data A blob encoding the policy rules under which the key can be released. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setData(byte[] data) { if (data == null) { this.data = null; } else { this.data = Base64Url.encode(CoreUtils.clone(data)); } return this; } }
class KeyReleasePolicy { /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) private byte[] data; /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; KeyReleasePolicy() { } /** * Creates an instance of {@link KeyReleasePolicy}. * * @param data A blob encoding the policy rules under which the key can be released. */ public KeyReleasePolicy(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = ByteExtensions.clone(data); } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } }
FYI, we have other properties in Keys defined as `base64Url` in the swagger that are actually saved as a byte array, [like those that are a part of `JsonWebKey`](https://github.com/Azure/azure-sdk-for-java/blob/cbba4149f87978ba16c0696ebe7177e6238c4598/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/JsonWebKey.java#L235), however, we still clone them when setting/getting them.
public byte[] getData() { if (this.data == null) { return null; } return this.data.decodedBytes(); }
return this.data.decodedBytes();
public byte[] getData() { return ByteExtensions.clone(this.data); }
class KeyReleasePolicy { /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") private Base64Url data; /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Set a blob encoding the policy rules under which the key can be released. * * @param data A blob encoding the policy rules under which the key can be released. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setData(byte[] data) { if (data == null) { this.data = null; } else { this.data = Base64Url.encode(CoreUtils.clone(data)); } return this; } }
class KeyReleasePolicy { /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) private byte[] data; /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; KeyReleasePolicy() { } /** * Creates an instance of {@link KeyReleasePolicy}. * * @param data A blob encoding the policy rules under which the key can be released. */ public KeyReleasePolicy(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = ByteExtensions.clone(data); } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } }
This is client-side validation and you should let the service error. We don't want tight coupling between SDK and service (it's in our guidelines). Only in rare cases - like null checks for required URL path parameters - do we do client-side validation of service client methods.
public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(isManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(client.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)).verifyComplete(); String target = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { target = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(client.releaseKey(keyToRelease.getName(), target)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); }
Assumptions.assumeTrue(isManagedHsmTest);
public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(isManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(client.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)).verifyComplete(); String target = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { target = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(client.releaseKey(keyToRelease.getName(), target)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion); client = spy(new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildAsyncClient()); if (interceptorManager.isPlaybackMode()) { when(client.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((expected) -> StepVerifier.create(client.createRsaKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { if (isManagedHsmTest && interceptorManager.isPlaybackMode()) { return; } createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey("", KeyType.RSA)) .verifyErrorSatisfies(ex -> { if (isManagedHsmTest) { assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_SERVER_ERROR); } else { assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST); } }); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyEmptyValueRunner((key) -> StepVerifier.create(client.createKey(key)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((original) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((key, keyWithNewVal) -> { final KeyVaultKey keyVersionOne = client.createKey(key).block(); final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block(); StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(key, response)) .verifyComplete(); StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewVal, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(client.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginDeleteKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(client.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(client.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(client.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.backupKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(client.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete(); byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> { assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode()); }).verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(client.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(client.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(client.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (!interceptorManager.isPlaybackMode()) { return; } listDeletedKeysRunner((keys) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keys.values()) { StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keys.values()) { PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = client.listDeletedKeys().map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keys) -> { List<KeyProperties> output = new ArrayList<>(); String keyName = null; for (CreateKeyOptions key : keys) { keyName = key.getName(); StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(30000); client.listPropertiesOfKeyVersions(keyName).subscribe(output::add); sleepInRecordMode(30000); assertEquals(keys.size(), output.size()); }); } /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keys) -> { for (CreateKeyOptions key : keys.values()) { assertKeyEquals(key, client.createKey(key).block()); } sleepInRecordMode(10000); client.listPropertiesOfKeys().map(actualKey -> { if (keys.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keys.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keys.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keys.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that an RSA key with a public exponent can be created in the key vault. */ @Disabled @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyWithPublicExponentRunner((createRsaKeyOptions) -> StepVerifier.create(client.createRsaKey(createRsaKeyOptions)) .assertNext(rsaKey -> assertKeyEquals(createRsaKeyOptions, rsaKey)) .assertNext(rsaKey -> { ByteBuffer wrappedArray = ByteBuffer.wrap(rsaKey.getKey().getE()); assertEquals(createRsaKeyOptions.getPublicExponent(), wrappedArray.getInt()); }) .verifyComplete()); } private void pollOnKeyDeletion(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 30) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey == null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s not found \n", keyName); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion); client = spy(new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildAsyncClient()); if (interceptorManager.isPlaybackMode()) { when(client.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((expected) -> StepVerifier.create(client.createRsaKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { if (isManagedHsmTest && interceptorManager.isPlaybackMode()) { return; } createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey("", KeyType.RSA)) .verifyErrorSatisfies(ex -> { if (isManagedHsmTest) { assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_SERVER_ERROR); } else { assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST); } }); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyEmptyValueRunner((key) -> StepVerifier.create(client.createKey(key)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((original) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((key, keyWithNewVal) -> { final KeyVaultKey keyVersionOne = client.createKey(key).block(); final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block(); StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(key, response)) .verifyComplete(); StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewVal, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(client.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginDeleteKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(client.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(client.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(client.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.backupKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(client.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete(); byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> { assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode()); }).verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(client.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(client.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(client.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (!interceptorManager.isPlaybackMode()) { return; } listDeletedKeysRunner((keys) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keys.values()) { StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keys.values()) { PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = client.listDeletedKeys().map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keys) -> { List<KeyProperties> output = new ArrayList<>(); String keyName = null; for (CreateKeyOptions key : keys) { keyName = key.getName(); StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(30000); client.listPropertiesOfKeyVersions(keyName).subscribe(output::add); sleepInRecordMode(30000); assertEquals(keys.size(), output.size()); }); } /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keys) -> { for (CreateKeyOptions key : keys.values()) { assertKeyEquals(key, client.createKey(key).block()); } sleepInRecordMode(10000); client.listPropertiesOfKeys().map(actualKey -> { if (keys.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keys.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keys.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keys.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that an RSA key with a public exponent can be created in the key vault. */ @Disabled @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyWithPublicExponentRunner((createRsaKeyOptions) -> StepVerifier.create(client.createRsaKey(createRsaKeyOptions)) .assertNext(rsaKey -> assertKeyEquals(createRsaKeyOptions, rsaKey)) .assertNext(rsaKey -> { ByteBuffer wrappedArray = ByteBuffer.wrap(rsaKey.getKey().getE()); assertEquals(createRsaKeyOptions.getPublicExponent(), wrappedArray.getInt()); }) .verifyComplete()); } private void pollOnKeyDeletion(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 30) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey == null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s not found \n", keyName); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
We do let the service error when it comes down to the public APIs. I added this to a test case just to avoid having it break the live tests. Should I remove it?
public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(isManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(client.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)).verifyComplete(); String target = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { target = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(client.releaseKey(keyToRelease.getName(), target)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); }
Assumptions.assumeTrue(isManagedHsmTest);
public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(isManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(client.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)).verifyComplete(); String target = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { target = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(client.releaseKey(keyToRelease.getName(), target)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion); client = spy(new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildAsyncClient()); if (interceptorManager.isPlaybackMode()) { when(client.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((expected) -> StepVerifier.create(client.createRsaKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { if (isManagedHsmTest && interceptorManager.isPlaybackMode()) { return; } createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey("", KeyType.RSA)) .verifyErrorSatisfies(ex -> { if (isManagedHsmTest) { assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_SERVER_ERROR); } else { assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST); } }); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyEmptyValueRunner((key) -> StepVerifier.create(client.createKey(key)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((original) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((key, keyWithNewVal) -> { final KeyVaultKey keyVersionOne = client.createKey(key).block(); final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block(); StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(key, response)) .verifyComplete(); StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewVal, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(client.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginDeleteKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(client.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(client.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(client.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.backupKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(client.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete(); byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> { assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode()); }).verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(client.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(client.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(client.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (!interceptorManager.isPlaybackMode()) { return; } listDeletedKeysRunner((keys) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keys.values()) { StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keys.values()) { PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = client.listDeletedKeys().map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keys) -> { List<KeyProperties> output = new ArrayList<>(); String keyName = null; for (CreateKeyOptions key : keys) { keyName = key.getName(); StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(30000); client.listPropertiesOfKeyVersions(keyName).subscribe(output::add); sleepInRecordMode(30000); assertEquals(keys.size(), output.size()); }); } /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keys) -> { for (CreateKeyOptions key : keys.values()) { assertKeyEquals(key, client.createKey(key).block()); } sleepInRecordMode(10000); client.listPropertiesOfKeys().map(actualKey -> { if (keys.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keys.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keys.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keys.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that an RSA key with a public exponent can be created in the key vault. */ @Disabled @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyWithPublicExponentRunner((createRsaKeyOptions) -> StepVerifier.create(client.createRsaKey(createRsaKeyOptions)) .assertNext(rsaKey -> assertKeyEquals(createRsaKeyOptions, rsaKey)) .assertNext(rsaKey -> { ByteBuffer wrappedArray = ByteBuffer.wrap(rsaKey.getKey().getE()); assertEquals(createRsaKeyOptions.getPublicExponent(), wrappedArray.getInt()); }) .verifyComplete()); } private void pollOnKeyDeletion(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 30) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey == null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s not found \n", keyName); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion); client = spy(new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildAsyncClient()); if (interceptorManager.isPlaybackMode()) { when(client.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((expected) -> StepVerifier.create(client.createRsaKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { if (isManagedHsmTest && interceptorManager.isPlaybackMode()) { return; } createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey("", KeyType.RSA)) .verifyErrorSatisfies(ex -> { if (isManagedHsmTest) { assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_SERVER_ERROR); } else { assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST); } }); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyEmptyValueRunner((key) -> StepVerifier.create(client.createKey(key)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((original) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((key, keyWithNewVal) -> { final KeyVaultKey keyVersionOne = client.createKey(key).block(); final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block(); StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(key, response)) .verifyComplete(); StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewVal, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(client.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginDeleteKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(client.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(client.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(client.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.backupKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(client.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete(); byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> { assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode()); }).verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(client.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(client.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(client.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (!interceptorManager.isPlaybackMode()) { return; } listDeletedKeysRunner((keys) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keys.values()) { StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keys.values()) { PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = client.listDeletedKeys().map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keys) -> { List<KeyProperties> output = new ArrayList<>(); String keyName = null; for (CreateKeyOptions key : keys) { keyName = key.getName(); StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(30000); client.listPropertiesOfKeyVersions(keyName).subscribe(output::add); sleepInRecordMode(30000); assertEquals(keys.size(), output.size()); }); } /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keys) -> { for (CreateKeyOptions key : keys.values()) { assertKeyEquals(key, client.createKey(key).block()); } sleepInRecordMode(10000); client.listPropertiesOfKeys().map(actualKey -> { if (keys.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keys.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keys.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keys.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that an RSA key with a public exponent can be created in the key vault. */ @Disabled @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyWithPublicExponentRunner((createRsaKeyOptions) -> StepVerifier.create(client.createRsaKey(createRsaKeyOptions)) .assertNext(rsaKey -> assertKeyEquals(createRsaKeyOptions, rsaKey)) .assertNext(rsaKey -> { ByteBuffer wrappedArray = ByteBuffer.wrap(rsaKey.getKey().getE()); assertEquals(createRsaKeyOptions.getPublicExponent(), wrappedArray.getInt()); }) .verifyComplete()); } private void pollOnKeyDeletion(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 30) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey == null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s not found \n", keyName); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
I recommend it, yes. If/when the service does change - especially unexpectedly - you'll know when it doesn't match the recordings, assuming you validate your request bodies like we do in .NET by default.
public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(isManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(client.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)).verifyComplete(); String target = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { target = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(client.releaseKey(keyToRelease.getName(), target)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); }
Assumptions.assumeTrue(isManagedHsmTest);
public void releaseKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { Assumptions.assumeTrue(isManagedHsmTest); createKeyAsyncClient(httpClient, serviceVersion); releaseKeyRunner((keyToRelease, attestationUrl) -> { StepVerifier.create(client.createRsaKey(keyToRelease)) .assertNext(keyResponse -> assertKeyEquals(keyToRelease, keyResponse)).verifyComplete(); String target = "testAttestationToken"; if (getTestMode() != TestMode.PLAYBACK) { if (!attestationUrl.endsWith("/")) { attestationUrl = attestationUrl + "/"; } try { target = getAttestationToken(attestationUrl + "generate-test-token"); } catch (IOException e) { fail("Found error when deserializing attestation token.", e); } } StepVerifier.create(client.releaseKey(keyToRelease.getName(), target)) .assertNext(releaseKeyResult -> assertNotNull(releaseKeyResult.getValue())) .expectComplete() .verify(); }); }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion); client = spy(new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildAsyncClient()); if (interceptorManager.isPlaybackMode()) { when(client.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((expected) -> StepVerifier.create(client.createRsaKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { if (isManagedHsmTest && interceptorManager.isPlaybackMode()) { return; } createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey("", KeyType.RSA)) .verifyErrorSatisfies(ex -> { if (isManagedHsmTest) { assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_SERVER_ERROR); } else { assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST); } }); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyEmptyValueRunner((key) -> StepVerifier.create(client.createKey(key)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((original) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((key, keyWithNewVal) -> { final KeyVaultKey keyVersionOne = client.createKey(key).block(); final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block(); StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(key, response)) .verifyComplete(); StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewVal, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(client.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginDeleteKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(client.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(client.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(client.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.backupKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(client.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete(); byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> { assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode()); }).verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(client.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(client.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(client.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (!interceptorManager.isPlaybackMode()) { return; } listDeletedKeysRunner((keys) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keys.values()) { StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keys.values()) { PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = client.listDeletedKeys().map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keys) -> { List<KeyProperties> output = new ArrayList<>(); String keyName = null; for (CreateKeyOptions key : keys) { keyName = key.getName(); StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(30000); client.listPropertiesOfKeyVersions(keyName).subscribe(output::add); sleepInRecordMode(30000); assertEquals(keys.size(), output.size()); }); } /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keys) -> { for (CreateKeyOptions key : keys.values()) { assertKeyEquals(key, client.createKey(key).block()); } sleepInRecordMode(10000); client.listPropertiesOfKeys().map(actualKey -> { if (keys.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keys.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keys.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keys.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that an RSA key with a public exponent can be created in the key vault. */ @Disabled @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyWithPublicExponentRunner((createRsaKeyOptions) -> StepVerifier.create(client.createRsaKey(createRsaKeyOptions)) .assertNext(rsaKey -> assertKeyEquals(createRsaKeyOptions, rsaKey)) .assertNext(rsaKey -> { ByteBuffer wrappedArray = ByteBuffer.wrap(rsaKey.getKey().getE()); assertEquals(createRsaKeyOptions.getPublicExponent(), wrappedArray.getInt()); }) .verifyComplete()); } private void pollOnKeyDeletion(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 30) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey == null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s not found \n", keyName); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
class KeyAsyncClientTest extends KeyClientTestBase { protected KeyAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); } protected void createKeyAsyncClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion); client = spy(new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildAsyncClient()); if (interceptorManager.isPlaybackMode()) { when(client.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyRunner((expected) -> StepVerifier.create(client.createKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that a RSA key created. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyRunner((expected) -> StepVerifier.create(client.createRsaKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot create a key when the key is an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) { if (isManagedHsmTest && interceptorManager.isPlaybackMode()) { return; } createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey("", KeyType.RSA)) .verifyErrorSatisfies(ex -> { if (isManagedHsmTest) { assertRestException(ex, HttpResponseException.class, HttpURLConnection.HTTP_SERVER_ERROR); } else { assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST); } }); } /** * Tests that we can create keys when value is not null or an empty string. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); setKeyEmptyValueRunner((key) -> StepVerifier.create(client.createKey(key)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST))); } /** * Verifies that an exception is thrown when null key object is passed for creation. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.createKey(null)) .verifyError(NullPointerException.class); } /** * Tests that a key is able to be updated when it exists. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that a key is not able to be updated when it is disabled. 403 error is expected. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); updateDisabledKeyRunner((original, updated) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); KeyVaultKey keyToUpdate = client.getKey(original.getName()).block(); StepVerifier.create(client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()))) .assertNext(response -> { assertNotNull(response); assertEquals(original.getName(), response.getName()); }).verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(updatedKeyResponse -> assertKeyEquals(updated, updatedKeyResponse)) .verifyComplete(); }); } /** * Tests that an existing key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeyRunner((original) -> { StepVerifier.create(client.createKey(original)) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); StepVerifier.create(client.getKey(original.getName())) .assertNext(response -> assertKeyEquals(original, response)) .verifyComplete(); }); } /** * Tests that a specific version of the key can be retrieved. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getKeySpecificVersionRunner((key, keyWithNewVal) -> { final KeyVaultKey keyVersionOne = client.createKey(key).block(); final KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal).block(); StepVerifier.create(client.getKey(key.getName(), keyVersionOne.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(key, response)) .verifyComplete(); StepVerifier.create(client.getKey(keyWithNewVal.getName(), keyVersionTwo.getProperties().getVersion())) .assertNext(response -> assertKeyEquals(keyWithNewVal, response)) .verifyComplete(); }); } /** * Tests that an attempt to get a non-existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an existing key can be deleted. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); deleteKeyRunner((keyToDelete) -> { StepVerifier.create(client.createKey(keyToDelete)) .assertNext(keyResponse -> assertKeyEquals(keyToDelete, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDelete.getName()); AsyncPollResponse<DeletedKey, Void> deletedKeyPollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); DeletedKey deletedKeyResponse = deletedKeyPollResponse.getValue(); assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDelete.getName(), deletedKeyResponse.getName()); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginDeleteKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.getDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a deleted key can be recovered on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((keyToDeleteAndRecover) -> { StepVerifier.create(client.createKey(keyToDeleteAndRecover)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndRecover, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<DeletedKey, Void> deleteKeyPollResponse = poller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(deleteKeyPollResponse.getValue()); PollerFlux<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName()); AsyncPollResponse<KeyVaultKey, Void> recoverKeyPollResponse = recoverPoller.takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); KeyVaultKey keyResponse = recoverKeyPollResponse.getValue(); assertEquals(keyToDeleteAndRecover.getName(), keyResponse.getName()); assertEquals(keyToDeleteAndRecover.getNotBefore(), keyResponse.getProperties().getNotBefore()); assertEquals(keyToDeleteAndRecover.getExpiresOn(), keyResponse.getProperties().getExpiresOn()); }); } /** * Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.beginRecoverDeletedKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); backupKeyRunner((keyToBackup) -> { StepVerifier.create(client.createKey(keyToBackup)) .assertNext(keyResponse -> assertKeyEquals(keyToBackup, keyResponse)).verifyComplete(); StepVerifier.create(client.backupKey(keyToBackup.getName())) .assertNext(response -> { assertNotNull(response); assertTrue(response.length > 0); }).verifyComplete(); }); } /** * Tests that an attempt to backup a non existing key throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); StepVerifier.create(client.backupKey("non-existing")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that a key can be backed up in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); restoreKeyRunner((keyToBackupAndRestore) -> { StepVerifier.create(client.createKey(keyToBackupAndRestore)) .assertNext(keyResponse -> assertKeyEquals(keyToBackupAndRestore, keyResponse)).verifyComplete(); byte[] backup = client.backupKey(keyToBackupAndRestore.getName()).block(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.purgeDeletedKeyWithResponse(keyToBackupAndRestore.getName())) .assertNext(voidResponse -> { assertEquals(HttpURLConnection.HTTP_NO_CONTENT, voidResponse.getStatusCode()); }).verifyComplete(); pollOnKeyPurge(keyToBackupAndRestore.getName()); sleepInRecordMode(60000); StepVerifier.create(client.restoreKeyBackup(backup)) .assertNext(response -> { assertEquals(keyToBackupAndRestore.getName(), response.getName()); assertEquals(keyToBackupAndRestore.getNotBefore(), response.getProperties().getNotBefore()); assertEquals(keyToBackupAndRestore.getExpiresOn(), response.getProperties().getExpiresOn()); }).verifyComplete(); }); } /** * Tests that an attempt to restore a key from malformed backup bytes throws an error. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(client.restoreKeyBackup(keyBackupBytes)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Tests that a deleted key can be retrieved on a soft-delete enabled vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); getDeletedKeyRunner((keyToDeleteAndGet) -> { StepVerifier.create(client.createKey(keyToDeleteAndGet)) .assertNext(keyResponse -> assertKeyEquals(keyToDeleteAndGet, keyResponse)).verifyComplete(); PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName()); AsyncPollResponse<DeletedKey, Void> pollResponse = poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .blockLast(); assertNotNull(pollResponse.getValue()); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.getName())) .assertNext(deletedKeyResponse -> { assertNotNull(deletedKeyResponse.getDeletedOn()); assertNotNull(deletedKeyResponse.getRecoveryId()); assertNotNull(deletedKeyResponse.getScheduledPurgeDate()); assertEquals(keyToDeleteAndGet.getName(), deletedKeyResponse.getName()); }).verifyComplete(); }); } /** * Tests that deleted keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); if (!interceptorManager.isPlaybackMode()) { return; } listDeletedKeysRunner((keys) -> { List<DeletedKey> deletedKeys = new ArrayList<>(); for (CreateKeyOptions key : keys.values()) { StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(10000); for (CreateKeyOptions key : keys.values()) { PollerFlux<DeletedKey, Void> poller = client.beginDeleteKey(key.getName()); AsyncPollResponse<DeletedKey, Void> response = poller.blockLast(); assertNotNull(response.getValue()); } sleepInRecordMode(90000); DeletedKey deletedKey = client.listDeletedKeys().map(actualKey -> { deletedKeys.add(actualKey); assertNotNull(actualKey.getDeletedOn()); assertNotNull(actualKey.getRecoveryId()); return actualKey; }).blockLast(); assertNotNull(deletedKey); }); } /** * Tests that key versions can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeyVersionsRunner((keys) -> { List<KeyProperties> output = new ArrayList<>(); String keyName = null; for (CreateKeyOptions key : keys) { keyName = key.getName(); StepVerifier.create(client.createKey(key)) .assertNext(keyResponse -> assertKeyEquals(key, keyResponse)).verifyComplete(); } sleepInRecordMode(30000); client.listPropertiesOfKeyVersions(keyName).subscribe(output::add); sleepInRecordMode(30000); assertEquals(keys.size(), output.size()); }); } /** * Tests that keys can be listed in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); listKeysRunner((keys) -> { for (CreateKeyOptions key : keys.values()) { assertKeyEquals(key, client.createKey(key).block()); } sleepInRecordMode(10000); client.listPropertiesOfKeys().map(actualKey -> { if (keys.containsKey(actualKey.getName())) { CreateKeyOptions expectedKey = keys.get(actualKey.getName()); assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn()); assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore()); keys.remove(actualKey.getName()); } return actualKey; }).blockLast(); assertEquals(0, keys.size()); }); } /** * Tests that an existing key can be released. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") /** * Tests that an RSA key with a public exponent can be created in the key vault. */ @Disabled @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createRsaKeyWithPublicExponent(HttpClient httpClient, KeyServiceVersion serviceVersion) { createKeyAsyncClient(httpClient, serviceVersion); createRsaKeyWithPublicExponentRunner((createRsaKeyOptions) -> StepVerifier.create(client.createRsaKey(createRsaKeyOptions)) .assertNext(rsaKey -> assertKeyEquals(createRsaKeyOptions, rsaKey)) .assertNext(rsaKey -> { ByteBuffer wrappedArray = ByteBuffer.wrap(rsaKey.getKey().getE()); assertEquals(createRsaKeyOptions.getPublicExponent(), wrappedArray.getInt()); }) .verifyComplete()); } private void pollOnKeyDeletion(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 30) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey == null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s not found \n", keyName); } private void pollOnKeyPurge(String keyName) { int pendingPollCount = 0; while (pendingPollCount < 10) { DeletedKey deletedKey = null; try { deletedKey = client.getDeletedKeyWithResponse(keyName).block().getValue(); } catch (ResourceNotFoundException e) { } if (deletedKey != null) { sleepInRecordMode(2000); pendingPollCount += 1; } else { return; } } System.err.printf("Deleted Key %s was not purged \n", keyName); } }
Ended up using a byte array type for this variable and using Jackson to properly serialize/deserialize it as base64.
public byte[] getData() { if (this.data == null) { return null; } return this.data.decodedBytes(); }
return this.data.decodedBytes();
public byte[] getData() { return ByteExtensions.clone(this.data); }
class KeyReleasePolicy { /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") private Base64Url data; /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Set a blob encoding the policy rules under which the key can be released. * * @param data A blob encoding the policy rules under which the key can be released. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setData(byte[] data) { if (data == null) { this.data = null; } else { this.data = Base64Url.encode(CoreUtils.clone(data)); } return this; } }
class KeyReleasePolicy { /* * Blob encoding the policy rules under which the key can be released. */ @JsonProperty(value = "data") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) private byte[] data; /* * Content type and version of key release policy. */ @JsonProperty(value = "contentType") private String contentType; KeyReleasePolicy() { } /** * Creates an instance of {@link KeyReleasePolicy}. * * @param data A blob encoding the policy rules under which the key can be released. */ public KeyReleasePolicy(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); this.data = ByteExtensions.clone(data); } /** * Get a blob encoding the policy rules under which the key can be released. * * @return A blob encoding the policy rules under which the key can be released. */ /** * Get the content type and version of key release policy. * * @return The content type and version of key release policy. */ public String getContentType() { return this.contentType; } /** * Set the content type and version of key release policy. * * <p>The service default is "application/json; charset=utf-8".</p> * * @param contentType The content type and version of key release policy to set. * * @return The updated {@link KeyReleasePolicy} object. */ public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; } }
Is this env var set by the user? If so, should we make this constant publicly available? It is public in this class but it's in implementation package.
public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration(); authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); ValidationUtil.validateAuthHost(getClass().getSimpleName(), authorityHost); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); identityLegacyTenantSelection = configuration .get(AZURE_IDENTITY_ENABLE_LEGACY_TENANT_SELECTION, false) ; }
.get(AZURE_IDENTITY_ENABLE_LEGACY_TENANT_SELECTION, false) ;
public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration(); loadFromConfiugration(configuration); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); identityLegacyTenantSelection = configuration .get(AZURE_IDENTITY_ENABLE_LEGACY_TENANT_SELECTION, false); }
class IdentityClientOptions { private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_ENABLE_LEGACY_TENANT_SELECTION = "AZURE_IDENTITY_ENABLE_LEGACY_TENANT_SELECTION"; private String authorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean allowMultiTenantAuthentication; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private boolean identityLegacyTenantSelection; /** * Creates an instance of IdentityClientOptions with default settings. */ /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } /** * Allows to override the tenant being used in the authentication request * via {@link com.azure.core.experimental.credential.TokenRequestContext * * @param allowMultiTenantAuthentication the flag to indicate if multi tenant authentication is enabled or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowMultiTenantAuthentication(boolean allowMultiTenantAuthentication) { this.allowMultiTenantAuthentication = allowMultiTenantAuthentication; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Get the flag indicating if multi tenant authentication is enabled or not. * * @return the boolean status indicating if multi tenant authentication is enabled or not. */ public boolean getAllowMultiTenantAuthentication() { return this.allowMultiTenantAuthentication; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ public IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public boolean isLegacyTenantSelectionEnabled() { return identityLegacyTenantSelection; } }
class IdentityClientOptions { private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_ENABLE_LEGACY_TENANT_SELECTION = "AZURE_IDENTITY_ENABLE_LEGACY_TENANT_SELECTION"; private String authorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean allowMultiTenantAuthentication; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private boolean identityLegacyTenantSelection; private Configuration configuration; /** * Creates an instance of IdentityClientOptions with default settings. */ /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } /** * Allows to override the tenant being used in the authentication request * via {@link com.azure.core.experimental.credential.TokenRequestContextExperimental * * @param allowMultiTenantAuthentication the flag to indicate if multi tenant authentication is enabled or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowMultiTenantAuthentication(boolean allowMultiTenantAuthentication) { this.allowMultiTenantAuthentication = allowMultiTenantAuthentication; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Get the flag indicating if multi tenant authentication is enabled or not. * * @return the boolean status indicating if multi tenant authentication is enabled or not. */ public boolean isMultiTenantAuthenticationAllowed() { return this.allowMultiTenantAuthentication; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ public IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public boolean isLegacyTenantSelectionEnabled() { return identityLegacyTenantSelection; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiugration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Loads the details from the specified Configuration Store. * * @return the regional authority value if specified */ private IdentityClientOptions loadFromConfiugration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); ValidationUtil.validateAuthHost(getClass().getSimpleName(), authorityHost); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); return this; } }
At this point none - but I can think of a scenario where someone wants to test a beta library to plan for work ahead of time. Since, we were adding this functionality I included both.
private List<BomDependency> scanOverriddenDependencies() { List<BomDependency> allInputDependencies = new ArrayList<>(); var overriddenInputDependencies = parseRawFile(); for(BomDependency dependency: overriddenInputDependencies.keySet()) { if(isPublishedArtifact(dependency)) { allInputDependencies.add(dependency); continue; } allInputDependencies.addAll(parsePomFileContent(overriddenInputDependencies.get(dependency))); } return allInputDependencies; }
private List<BomDependency> scanOverriddenDependencies() { List<BomDependency> allInputDependencies = new ArrayList<>(); var overriddenInputDependencies = parseRawFile(); for(BomDependency dependency: overriddenInputDependencies.keySet()) { if(isPublishedArtifact(dependency)) { allInputDependencies.add(dependency); continue; } allInputDependencies.addAll(parsePomFileContent(overriddenInputDependencies.get(dependency))); } return allInputDependencies; }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String overriddenInputDependenciesFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOverriddenInputDependenciesFileName() { return this.overriddenInputDependenciesFileName; } public void setOverriddenInputDependenciesFileName(String overriddenInputDependenciesFileName) { this.overriddenInputDependenciesFileName = overriddenInputDependenciesFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } public void run() { switch (mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; default: logger.error("Unknown value for mode: {}", mode); break; } } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scanVersioningClientFileDependencies() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private List<BomDependency> scan() { var versioningClientDependency = scanVersioningClientFileDependencies(); if (this.overriddenInputDependenciesFileName == null) { return versioningClientDependency; } var overriddenInputDependencies = scanOverriddenDependencies(); var overriddenInputDependenciesNoVersion = overriddenInputDependencies.stream().map(Utils::toBomDependencyNoVersion).collect(Collectors.toUnmodifiableSet()); var filteredInputDependencies = versioningClientDependency.stream().filter(dependency -> !overriddenInputDependenciesNoVersion.contains(toBomDependencyNoVersion(dependency))).collect(Collectors.toList()); filteredInputDependencies.addAll(overriddenInputDependencies); return filteredInputDependencies; } private Map<BomDependency, String> parseRawFile() { Map<BomDependency, String> inputDependencies = new HashMap(); try { for (String line : Files.readAllLines(Paths.get(overriddenInputDependenciesFileName))) { var matcher = INPUT_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { continue; } var dependencyPattern = matcher.group(1); var pomFilePath = matcher.groupCount() == 3 ? matcher.group(2) : null; var dependency = STRING_SPLIT_BY_COLON.split(dependencyPattern); { if(dependency.length != 3) { continue; } validateNotNullOrEmpty(dependency, "inputDependency"); inputDependencies.put(new BomDependency(dependency[0], dependency[1], dependency[2]), pomFilePath); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String overriddenInputDependenciesFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOverriddenInputDependenciesFileName() { return this.overriddenInputDependenciesFileName; } public void setOverriddenInputDependenciesFileName(String overriddenInputDependenciesFileName) { this.overriddenInputDependenciesFileName = overriddenInputDependenciesFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } public void run() { switch (mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; default: logger.error("Unknown value for mode: {}", mode); break; } } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scanVersioningClientFileDependencies() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private List<BomDependency> scan() { var versioningClientDependency = scanVersioningClientFileDependencies(); if (this.overriddenInputDependenciesFileName == null) { return versioningClientDependency; } var overriddenInputDependencies = scanOverriddenDependencies(); var overriddenInputDependenciesNoVersion = overriddenInputDependencies.stream().map(Utils::toBomDependencyNoVersion).collect(Collectors.toUnmodifiableSet()); var filteredInputDependencies = versioningClientDependency.stream().filter(dependency -> !overriddenInputDependenciesNoVersion.contains(toBomDependencyNoVersion(dependency))).collect(Collectors.toList()); filteredInputDependencies.addAll(overriddenInputDependencies); return filteredInputDependencies; } private Map<BomDependency, String> parseRawFile() { Map<BomDependency, String> inputDependencies = new HashMap(); try { for (String line : Files.readAllLines(Paths.get(overriddenInputDependenciesFileName))) { var matcher = INPUT_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { continue; } var dependencyPattern = matcher.group(1); var pomFilePath = matcher.groupCount() == 3 ? matcher.group(2) : null; var dependency = STRING_SPLIT_BY_COLON.split(dependencyPattern); { if(dependency.length != 3) { continue; } validateNotNullOrEmpty(dependency, "inputDependency"); inputDependencies.put(new BomDependency(dependency[0], dependency[1], dependency[2]), pomFilePath); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
What is the scenario where we use a dependency that is not published to maven?
private List<BomDependency> scanOverriddenDependencies() { List<BomDependency> allInputDependencies = new ArrayList<>(); var overriddenInputDependencies = parseRawFile(); for(BomDependency dependency: overriddenInputDependencies.keySet()) { if(isPublishedArtifact(dependency)) { allInputDependencies.add(dependency); continue; } allInputDependencies.addAll(parsePomFileContent(overriddenInputDependencies.get(dependency))); } return allInputDependencies; }
private List<BomDependency> scanOverriddenDependencies() { List<BomDependency> allInputDependencies = new ArrayList<>(); var overriddenInputDependencies = parseRawFile(); for(BomDependency dependency: overriddenInputDependencies.keySet()) { if(isPublishedArtifact(dependency)) { allInputDependencies.add(dependency); continue; } allInputDependencies.addAll(parsePomFileContent(overriddenInputDependencies.get(dependency))); } return allInputDependencies; }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String overriddenInputDependenciesFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOverriddenInputDependenciesFileName() { return this.overriddenInputDependenciesFileName; } public void setOverriddenInputDependenciesFileName(String overriddenInputDependenciesFileName) { this.overriddenInputDependenciesFileName = overriddenInputDependenciesFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } public void run() { switch (mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; default: logger.error("Unknown value for mode: {}", mode); break; } } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scanVersioningClientFileDependencies() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private List<BomDependency> scan() { var versioningClientDependency = scanVersioningClientFileDependencies(); if (this.overriddenInputDependenciesFileName == null) { return versioningClientDependency; } var overriddenInputDependencies = scanOverriddenDependencies(); var overriddenInputDependenciesNoVersion = overriddenInputDependencies.stream().map(Utils::toBomDependencyNoVersion).collect(Collectors.toUnmodifiableSet()); var filteredInputDependencies = versioningClientDependency.stream().filter(dependency -> !overriddenInputDependenciesNoVersion.contains(toBomDependencyNoVersion(dependency))).collect(Collectors.toList()); filteredInputDependencies.addAll(overriddenInputDependencies); return filteredInputDependencies; } private Map<BomDependency, String> parseRawFile() { Map<BomDependency, String> inputDependencies = new HashMap(); try { for (String line : Files.readAllLines(Paths.get(overriddenInputDependenciesFileName))) { var matcher = INPUT_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { continue; } var dependencyPattern = matcher.group(1); var pomFilePath = matcher.groupCount() == 3 ? matcher.group(2) : null; var dependency = STRING_SPLIT_BY_COLON.split(dependencyPattern); { if(dependency.length != 3) { continue; } validateNotNullOrEmpty(dependency, "inputDependency"); inputDependencies.put(new BomDependency(dependency[0], dependency[1], dependency[2]), pomFilePath); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
class BomGenerator { private String outputFileName; private String inputFileName; private String pomFileName; private String overriddenInputDependenciesFileName; private String mode; private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); BomGenerator() { this.mode = GENERATE_MODE; } public String getInputFileName() { return this.inputFileName; } public void setInputFileName(String inputFileName) { this.inputFileName = inputFileName; } public String getOverriddenInputDependenciesFileName() { return this.overriddenInputDependenciesFileName; } public void setOverriddenInputDependenciesFileName(String overriddenInputDependenciesFileName) { this.overriddenInputDependenciesFileName = overriddenInputDependenciesFileName; } public String getOutputFileName() { return this.outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } public String getPomFileName() { return this.pomFileName; } public void setPomFileName(String pomFileName) { this.pomFileName = pomFileName; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } public void run() { switch (mode) { case ANALYZE_MODE: validate(); break; case GENERATE_MODE: generate(); break; default: logger.error("Unknown value for mode: {}", mode); break; } } private void validate() { var inputDependencies = parsePomFileContent(this.pomFileName); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, null); analyzer.validate(); } private void generate() { List<BomDependency> inputDependencies = scan(); List<BomDependency> externalDependencies = resolveExternalDependencies(); DependencyAnalyzer analyzer = new DependencyAnalyzer(inputDependencies, externalDependencies); analyzer.reduce(); Collection<BomDependency> outputDependencies = analyzer.getBomEligibleDependencies(); analyzer = new DependencyAnalyzer(outputDependencies, externalDependencies); boolean validationFailed = analyzer.validate(); outputDependencies = analyzer.getBomEligibleDependencies(); if(!validationFailed) { rewriteExistingBomFile(); writeBom(outputDependencies); } else { logger.trace("Validation for the BOM failed. Exiting..."); } } private List<BomDependency> scanVersioningClientFileDependencies() { List<BomDependency> inputDependencies = new ArrayList<>(); try { for (String line : Files.readAllLines(Paths.get(inputFileName))) { BomDependency dependency = scanDependency(line); if(dependency != null) { inputDependencies.add(dependency); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private List<BomDependency> scan() { var versioningClientDependency = scanVersioningClientFileDependencies(); if (this.overriddenInputDependenciesFileName == null) { return versioningClientDependency; } var overriddenInputDependencies = scanOverriddenDependencies(); var overriddenInputDependenciesNoVersion = overriddenInputDependencies.stream().map(Utils::toBomDependencyNoVersion).collect(Collectors.toUnmodifiableSet()); var filteredInputDependencies = versioningClientDependency.stream().filter(dependency -> !overriddenInputDependenciesNoVersion.contains(toBomDependencyNoVersion(dependency))).collect(Collectors.toList()); filteredInputDependencies.addAll(overriddenInputDependencies); return filteredInputDependencies; } private Map<BomDependency, String> parseRawFile() { Map<BomDependency, String> inputDependencies = new HashMap(); try { for (String line : Files.readAllLines(Paths.get(overriddenInputDependenciesFileName))) { var matcher = INPUT_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { continue; } var dependencyPattern = matcher.group(1); var pomFilePath = matcher.groupCount() == 3 ? matcher.group(2) : null; var dependency = STRING_SPLIT_BY_COLON.split(dependencyPattern); { if(dependency.length != 3) { continue; } validateNotNullOrEmpty(dependency, "inputDependency"); inputDependencies.put(new BomDependency(dependency[0], dependency[1], dependency[2]), pomFilePath); } } } catch (IOException exception) { logger.error("Input file parsing failed. Exception{}", exception.toString()); } return inputDependencies; } private BomDependency scanDependency(String line) { Matcher matcher = SDK_DEPENDENCY_PATTERN.matcher(line); if (!matcher.matches()) { return null; } if (matcher.groupCount() != 3) { return null; } String artifactId = matcher.group(1); String version = matcher.group(2); if(version.contains("-")) { return null; } if (EXCLUSION_LIST.contains(artifactId) || artifactId.contains(AZURE_PERF_LIBRARY_IDENTIFIER) || (artifactId.contains(AZURE_TEST_LIBRARY_IDENTIFIER))) { logger.trace("Skipping dependency {}:{}", BASE_AZURE_GROUPID, artifactId); return null; } return new BomDependency(BASE_AZURE_GROUPID, artifactId, version); } private Model readModel() { MavenXpp3Reader reader = new MavenXpp3Reader(); try { Model model = reader.read(new FileReader(this.pomFileName)); return model; } catch (XmlPullParserException | IOException e) { logger.error("BOM reading failed with: {}", e.toString()); } return null; } private void writeModel(Model model) { String pomFileName = this.pomFileName; writeModel(pomFileName, model); } private void writeModel(String fileName, Model model) { MavenXpp3Writer writer = new MavenXpp3Writer(); try { writer.write(new FileWriter(fileName), model); } catch (IOException exception) { logger.error("BOM writing failed with: {}", exception.toString()); } } private List<BomDependency> resolveExternalDependencies() { List<BomDependency> externalDependencies = new ArrayList<>(); List<Dependency> externalBomDependencies = getExternalDependencies(); externalDependencies.addAll(Utils.getExternalDependenciesContent(externalBomDependencies)); return externalDependencies; } private List<Dependency> getExternalDependencies() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); return management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); } private void rewriteExistingBomFile() { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> dependencies = management.getDependencies(); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(model); } private void writeBom(Collection<BomDependency> bomDependencies) { Model model = readModel(); DependencyManagement management = model.getDependencyManagement(); List<Dependency> externalBomDependencies = management.getDependencies().stream().filter(dependency -> dependency.getType().equals(POM_TYPE)).collect(Collectors.toList()); List<Dependency> dependencies = bomDependencies.stream().map(bomDependency -> { Dependency dependency = new Dependency(); dependency.setGroupId(bomDependency.getGroupId()); dependency.setArtifactId(bomDependency.getArtifactId()); dependency.setVersion(bomDependency.getVersion()); return dependency; }).collect(Collectors.toList()); dependencies.addAll(externalBomDependencies); dependencies.sort(new DependencyComparator()); management.setDependencies(dependencies); writeModel(this.outputFileName, model); } }
I think here we should use inputDependency only when it matches the expected dependency in `versioning_client.txt`. #Resolved
private void resolveConflict(BomDependencyNoVersion dependencyNoVersion) { Map<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(dependencyNoVersion); if (versionToDependency.size() > 1) { List<String> versionList = versionToDependency.keySet().stream().sorted(new DependencyVersionComparator()).collect(Collectors.toList()); String eligibleVersion; logger.trace("Multiple version of the dependency {} included", dependencyNoVersion); if (coreDependencyNameToDependency.containsKey(dependencyNoVersion)) { eligibleVersion = coreDependencyNameToDependency.get(dependencyNoVersion).getVersion(); logger.trace(String.format("\tPicking the version used by azure-core - %s:%s", dependencyNoVersion, eligibleVersion)); } else { if (inputDependencies.containsKey(dependencyNoVersion)) { eligibleVersion = inputDependencies.get(dependencyNoVersion).getVersion(); } else { eligibleVersion = versionList.get(versionList.size() - 1); } logger.trace(String.format("\tPicking the version %s:%s", dependencyNoVersion, eligibleVersion)); } BomDependency dependency = new BomDependency(dependencyNoVersion.getGroupId(), dependencyNoVersion.getArtifactId(), eligibleVersion); if (!externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } for (String version : versionList) { if (!version.equals(eligibleVersion)) { makeDependencyInEligible(new BomDependency(dependency.getGroupId(), dependency.getArtifactId(), version), null, eligibleVersion); } } } }
if (inputDependencies.containsKey(dependencyNoVersion)) {
private void resolveConflict(BomDependencyNoVersion dependencyNoVersion) { Map<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(dependencyNoVersion); if (versionToDependency.size() > 1) { List<String> versionList = versionToDependency.keySet().stream().sorted(new DependencyVersionComparator()).collect(Collectors.toList()); String eligibleVersion; logger.trace("Multiple version of the dependency {} included", dependencyNoVersion); if (coreDependencyNameToDependency.containsKey(dependencyNoVersion)) { eligibleVersion = coreDependencyNameToDependency.get(dependencyNoVersion).getVersion(); logger.trace(String.format("\tPicking the version used by azure-core - %s:%s", dependencyNoVersion, eligibleVersion)); } else { if (inputDependencies.containsKey(dependencyNoVersion)) { eligibleVersion = inputDependencies.get(dependencyNoVersion).getVersion(); } else { eligibleVersion = versionList.get(versionList.size() - 1); } logger.trace(String.format("\tPicking the version %s:%s", dependencyNoVersion, eligibleVersion)); } BomDependency dependency = new BomDependency(dependencyNoVersion.getGroupId(), dependencyNoVersion.getArtifactId(), eligibleVersion); if (!externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } for (String version : versionList) { if (!version.equals(eligibleVersion)) { makeDependencyInEligible(new BomDependency(dependency.getGroupId(), dependency.getArtifactId(), version), null, eligibleVersion); } } } }
class DependencyAnalyzer { private Map<BomDependencyNoVersion, BomDependency> inputDependencies = new HashMap<>(); private Set<BomDependency> externalDependencies = new HashSet<>(); private Set<BomDependency> bomEligibleDependencies = new HashSet<>(); private Set<BomDependency> bomIneligibleDependencies = new HashSet<>(); private Map<BomDependencyNoVersion, BomDependency> coreDependencyNameToDependency = new HashMap<>(); private Map<BomDependency, BomDependencyErrorInfo> errorInfo = new HashMap(); private Map<BomDependencyNoVersion, HashMap<String, Collection<BomDependency>>> nameToVersionToChildrenDependencyTree = new TreeMap<>(new Comparator<BomDependencyNoVersion>() { @Override public int compare(BomDependencyNoVersion o1, BomDependencyNoVersion o2) { return (o1.getGroupId() + o1.getArtifactId()).compareTo(o1.getGroupId() + o2.getArtifactId()); } }); private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); DependencyAnalyzer(Collection<BomDependency> inputDependencies, Collection<BomDependency> externalDependencies) { if (inputDependencies != null) { this.inputDependencies = inputDependencies.stream().collect(Collectors.toMap(Utils::toBomDependencyNoVersion, dependency -> dependency)); } if (externalDependencies != null) { this.externalDependencies.addAll(externalDependencies); } } public Collection<BomDependency> getBomEligibleDependencies() { return this.bomEligibleDependencies; } public void reduce() { analyze(); generateReport(); this.bomEligibleDependencies.retainAll(this.inputDependencies.values()); } public boolean validate() { analyze(); generateReport(); return nameToVersionToChildrenDependencyTree.values().stream().anyMatch(value -> value.size() > 1); } private void analyze() { pickCoreDependencyRoots(); resolveTree(); resolveConflicts(); filterConflicts(); } private void generateReport() { Set<BomDependency> droppedDependencies = inputDependencies.values().stream().filter(dependency -> bomIneligibleDependencies.contains(dependency)).collect(Collectors.toSet()); if (droppedDependencies.size() == 0) { return; } if (errorInfo.size() > 0) { errorInfo.keySet().stream().forEach(key -> { if (droppedDependencies.contains(key)) { var conflictingDependencies = errorInfo.get(key).getConflictingDependencies(); var expectedDependency = errorInfo.get(key).getExpectedDependency(); if (expectedDependency != null) { logger.info("Dropped dependency {}.", key.toString(), expectedDependency); } conflictingDependencies.stream().forEach(conflictingDependency -> logger.info("\t\tIncludes dependency {}. Expected dependency {}", conflictingDependency.getActualDependency(), conflictingDependency.getExpectedDependency())); } }); } } private BomDependency getAzureCoreDependencyFromInput() { return inputDependencies.values().stream().filter(dependency -> dependency.getArtifactId().equals("azure-core")).findFirst().get(); } private void pickCoreDependencyRoots() { BomDependency coreDependency = getAzureCoreDependencyFromInput(); var coreDependencies = getDependencies(coreDependency); coreDependencyNameToDependency.put(toBomDependencyNoVersion(coreDependency), coreDependency); coreDependencies.forEach(dependency -> coreDependencyNameToDependency.put(toBomDependencyNoVersion(dependency), dependency)); for(var dependency : coreDependencyNameToDependency.values()) { if(!externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } } } /* Create a tree map of all the input binaries into the following map. * {groupId_artifactId}: {v1} : {all ancestors that include this binary.} * : {v2} : {all ancestors that include this binary.} * : {v3} : {all ancestors that include this binary.} */ private void resolveTree() { for (MavenDependency gaLibrary : inputDependencies.values()) { try { BomDependency parentDependency = new BomDependency(gaLibrary.getGroupId(), gaLibrary.getArtifactId(), gaLibrary.getVersion()); addDependencyToDependencyTree(parentDependency, null, nameToVersionToChildrenDependencyTree); List<BomDependency> dependencies = getDependencies(gaLibrary); for (BomDependency dependency : dependencies) { if (dependency.getScope() == ScopeType.TEST) { continue; } if (RESOLVED_EXCLUSION_LIST.contains(dependency.getArtifactId())) { continue; } BomDependency childDependency = new BomDependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()); addDependencyToDependencyTree(childDependency, parentDependency, nameToVersionToChildrenDependencyTree); } } catch (Exception ex) { System.out.println(ex); } } } private static List<BomDependency> getDependencies(MavenDependency dependency) { try { MavenResolvedArtifact mavenResolvedArtifact = getResolvedArtifact(dependency); return Arrays.stream(mavenResolvedArtifact.getDependencies()).map(mavenDependency -> new BomDependency(mavenDependency.getCoordinate().getGroupId(), mavenDependency.getCoordinate().getArtifactId(), mavenDependency.getCoordinate().getVersion(), mavenDependency.getScope())).collect(Collectors.toList()); } catch (Exception ex) { logger.error(ex.toString()); } return new ArrayList<>(); } private static void addDependencyToDependencyTree(BomDependency dependency, BomDependency parentDependency, Map<BomDependencyNoVersion, HashMap<String, Collection<BomDependency>>> dependencyTree) { if (IGNORE_CONFLICT_LIST.contains(dependency.getArtifactId())) { return; } dependencyTree.computeIfAbsent(new BomDependencyNoVersion(dependency.getGroupId(), dependency.getArtifactId()), key -> new HashMap<>()); var value = dependencyTree.get(dependency).computeIfAbsent(dependency.getVersion(), key -> new ArrayList<>()); if(parentDependency != null) { value.add(parentDependency); } } private void updateErrorInfo(BomDependency droppedDependency, String expectedVersion) { if (!errorInfo.containsKey(droppedDependency)) { errorInfo.put(droppedDependency, new BomDependencyErrorInfo(new BomDependency(droppedDependency.getGroupId(), droppedDependency.getArtifactId(), expectedVersion))); } } private void updateErrorInfo(BomDependency droppedDependency, BomDependency actualDependency, String expectedVersion) { updateErrorInfo(droppedDependency, expectedVersion); errorInfo.get(droppedDependency).addConflictingDependency(actualDependency, new BomDependency(actualDependency.getGroupId(), actualDependency.getArtifactId(), expectedVersion)); } private void makeDependencyInEligible(BomDependency dependency, BomDependency dependencyReason, String expectedVersion) { if (nameToVersionToChildrenDependencyTree.containsKey(dependency)) { HashMap<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(dependency); bomIneligibleDependencies.add(dependency); if (dependencyReason == null) { dependencyReason = dependency; updateErrorInfo(dependency, expectedVersion); } else { updateErrorInfo(dependency, dependencyReason, expectedVersion); } BomDependency finalDependencyReason = dependencyReason; versionToDependency.get(dependency.getVersion()).forEach(parent -> makeDependencyInEligible(parent, finalDependencyReason, expectedVersion)); } } private void resolveConflicts() { nameToVersionToChildrenDependencyTree.keySet().stream().forEach(this::resolveConflict); bomEligibleDependencies.removeAll(bomIneligibleDependencies); } private void filterConflicts() { nameToVersionToChildrenDependencyTree.keySet().stream().forEach( key -> { HashMap<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(key); if (versionToDependency.size() == 1) { BomDependency dependency = new BomDependency(key.getGroupId(), key.getArtifactId(), versionToDependency.keySet().stream().findFirst().get()); if (!bomIneligibleDependencies.contains(dependency) && !externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } } }); } }
class DependencyAnalyzer { private Map<BomDependencyNoVersion, BomDependency> inputDependencies = new HashMap<>(); private Set<BomDependency> externalDependencies = new HashSet<>(); private Set<BomDependency> bomEligibleDependencies = new HashSet<>(); private Set<BomDependency> bomIneligibleDependencies = new HashSet<>(); private Map<BomDependencyNoVersion, BomDependency> coreDependencyNameToDependency = new HashMap<>(); private Map<BomDependency, BomDependencyErrorInfo> errorInfo = new HashMap(); private Map<BomDependencyNoVersion, HashMap<String, Collection<BomDependency>>> nameToVersionToChildrenDependencyTree = new TreeMap<>(new Comparator<BomDependencyNoVersion>() { @Override public int compare(BomDependencyNoVersion o1, BomDependencyNoVersion o2) { return (o1.getGroupId() + o1.getArtifactId()).compareTo(o1.getGroupId() + o2.getArtifactId()); } }); private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); DependencyAnalyzer(Collection<BomDependency> inputDependencies, Collection<BomDependency> externalDependencies) { if (inputDependencies != null) { this.inputDependencies = inputDependencies.stream().collect(Collectors.toMap(Utils::toBomDependencyNoVersion, dependency -> dependency)); } if (externalDependencies != null) { this.externalDependencies.addAll(externalDependencies); } } public Collection<BomDependency> getBomEligibleDependencies() { return this.bomEligibleDependencies; } public void reduce() { analyze(); generateReport(); this.bomEligibleDependencies.retainAll(this.inputDependencies.values()); } public boolean validate() { analyze(); generateReport(); return nameToVersionToChildrenDependencyTree.values().stream().anyMatch(value -> value.size() > 1); } private void analyze() { pickCoreDependencyRoots(); resolveTree(); resolveConflicts(); filterConflicts(); } private void generateReport() { Set<BomDependency> droppedDependencies = inputDependencies.values().stream().filter(dependency -> bomIneligibleDependencies.contains(dependency)).collect(Collectors.toSet()); if (droppedDependencies.size() == 0) { return; } if (errorInfo.size() > 0) { errorInfo.keySet().stream().forEach(key -> { if (droppedDependencies.contains(key)) { var conflictingDependencies = errorInfo.get(key).getConflictingDependencies(); var expectedDependency = errorInfo.get(key).getExpectedDependency(); if (expectedDependency != null) { logger.info("Dropped dependency {}.", key.toString(), expectedDependency); } conflictingDependencies.stream().forEach(conflictingDependency -> logger.info("\t\tIncludes dependency {}. Expected dependency {}", conflictingDependency.getActualDependency(), conflictingDependency.getExpectedDependency())); } }); } } private BomDependency getAzureCoreDependencyFromInput() { return inputDependencies.values().stream().filter(dependency -> dependency.getArtifactId().equals("azure-core")).findFirst().get(); } private void pickCoreDependencyRoots() { BomDependency coreDependency = getAzureCoreDependencyFromInput(); var coreDependencies = getDependencies(coreDependency); coreDependencyNameToDependency.put(toBomDependencyNoVersion(coreDependency), coreDependency); coreDependencies.forEach(dependency -> coreDependencyNameToDependency.put(toBomDependencyNoVersion(dependency), dependency)); for(var dependency : coreDependencyNameToDependency.values()) { if(!externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } } } /* Create a tree map of all the input binaries into the following map. * {groupId_artifactId}: {v1} : {all ancestors that include this binary.} * : {v2} : {all ancestors that include this binary.} * : {v3} : {all ancestors that include this binary.} */ private void resolveTree() { for (MavenDependency gaLibrary : inputDependencies.values()) { try { BomDependency parentDependency = new BomDependency(gaLibrary.getGroupId(), gaLibrary.getArtifactId(), gaLibrary.getVersion()); addDependencyToDependencyTree(parentDependency, null, nameToVersionToChildrenDependencyTree); List<BomDependency> dependencies = getDependencies(gaLibrary); for (BomDependency dependency : dependencies) { if (dependency.getScope() == ScopeType.TEST) { continue; } if (RESOLVED_EXCLUSION_LIST.contains(dependency.getArtifactId())) { continue; } BomDependency childDependency = new BomDependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()); addDependencyToDependencyTree(childDependency, parentDependency, nameToVersionToChildrenDependencyTree); } } catch (Exception ex) { System.out.println(ex); } } } private static List<BomDependency> getDependencies(MavenDependency dependency) { try { MavenResolvedArtifact mavenResolvedArtifact = getResolvedArtifact(dependency); return Arrays.stream(mavenResolvedArtifact.getDependencies()).map(mavenDependency -> new BomDependency(mavenDependency.getCoordinate().getGroupId(), mavenDependency.getCoordinate().getArtifactId(), mavenDependency.getCoordinate().getVersion(), mavenDependency.getScope())).collect(Collectors.toList()); } catch (Exception ex) { logger.error(ex.toString()); } return new ArrayList<>(); } private static void addDependencyToDependencyTree(BomDependency dependency, BomDependency parentDependency, Map<BomDependencyNoVersion, HashMap<String, Collection<BomDependency>>> dependencyTree) { if (IGNORE_CONFLICT_LIST.contains(dependency.getArtifactId())) { return; } dependencyTree.computeIfAbsent(new BomDependencyNoVersion(dependency.getGroupId(), dependency.getArtifactId()), key -> new HashMap<>()); var value = dependencyTree.get(dependency).computeIfAbsent(dependency.getVersion(), key -> new ArrayList<>()); if(parentDependency != null) { value.add(parentDependency); } } private void updateErrorInfo(BomDependency droppedDependency, String expectedVersion) { if (!errorInfo.containsKey(droppedDependency)) { errorInfo.put(droppedDependency, new BomDependencyErrorInfo(new BomDependency(droppedDependency.getGroupId(), droppedDependency.getArtifactId(), expectedVersion))); } } private void updateErrorInfo(BomDependency droppedDependency, BomDependency actualDependency, String expectedVersion) { updateErrorInfo(droppedDependency, expectedVersion); errorInfo.get(droppedDependency).addConflictingDependency(actualDependency, new BomDependency(actualDependency.getGroupId(), actualDependency.getArtifactId(), expectedVersion)); } private void makeDependencyInEligible(BomDependency dependency, BomDependency dependencyReason, String expectedVersion) { if (nameToVersionToChildrenDependencyTree.containsKey(dependency)) { HashMap<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(dependency); bomIneligibleDependencies.add(dependency); if (dependencyReason == null) { dependencyReason = dependency; updateErrorInfo(dependency, expectedVersion); } else { updateErrorInfo(dependency, dependencyReason, expectedVersion); } BomDependency finalDependencyReason = dependencyReason; versionToDependency.get(dependency.getVersion()).forEach(parent -> makeDependencyInEligible(parent, finalDependencyReason, expectedVersion)); } } private void resolveConflicts() { nameToVersionToChildrenDependencyTree.keySet().stream().forEach(this::resolveConflict); bomEligibleDependencies.removeAll(bomIneligibleDependencies); } private void filterConflicts() { nameToVersionToChildrenDependencyTree.keySet().stream().forEach( key -> { HashMap<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(key); if (versionToDependency.size() == 1) { BomDependency dependency = new BomDependency(key.getGroupId(), key.getArtifactId(), versionToDependency.keySet().stream().findFirst().get()); if (!bomIneligibleDependencies.contains(dependency) && !externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } } }); } }
I think there is a slight confusion on what override means - the override input dependency filename - is a way of overriding what is in the versioning_client.txt or in another words what assembly should be in the BOM. So, for the analyzer - inputdependencies is the list of potential BOM roots which includes dependencies from versioning_client.txt as well overridden dependencies,
private void resolveConflict(BomDependencyNoVersion dependencyNoVersion) { Map<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(dependencyNoVersion); if (versionToDependency.size() > 1) { List<String> versionList = versionToDependency.keySet().stream().sorted(new DependencyVersionComparator()).collect(Collectors.toList()); String eligibleVersion; logger.trace("Multiple version of the dependency {} included", dependencyNoVersion); if (coreDependencyNameToDependency.containsKey(dependencyNoVersion)) { eligibleVersion = coreDependencyNameToDependency.get(dependencyNoVersion).getVersion(); logger.trace(String.format("\tPicking the version used by azure-core - %s:%s", dependencyNoVersion, eligibleVersion)); } else { if (inputDependencies.containsKey(dependencyNoVersion)) { eligibleVersion = inputDependencies.get(dependencyNoVersion).getVersion(); } else { eligibleVersion = versionList.get(versionList.size() - 1); } logger.trace(String.format("\tPicking the version %s:%s", dependencyNoVersion, eligibleVersion)); } BomDependency dependency = new BomDependency(dependencyNoVersion.getGroupId(), dependencyNoVersion.getArtifactId(), eligibleVersion); if (!externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } for (String version : versionList) { if (!version.equals(eligibleVersion)) { makeDependencyInEligible(new BomDependency(dependency.getGroupId(), dependency.getArtifactId(), version), null, eligibleVersion); } } } }
if (inputDependencies.containsKey(dependencyNoVersion)) {
private void resolveConflict(BomDependencyNoVersion dependencyNoVersion) { Map<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(dependencyNoVersion); if (versionToDependency.size() > 1) { List<String> versionList = versionToDependency.keySet().stream().sorted(new DependencyVersionComparator()).collect(Collectors.toList()); String eligibleVersion; logger.trace("Multiple version of the dependency {} included", dependencyNoVersion); if (coreDependencyNameToDependency.containsKey(dependencyNoVersion)) { eligibleVersion = coreDependencyNameToDependency.get(dependencyNoVersion).getVersion(); logger.trace(String.format("\tPicking the version used by azure-core - %s:%s", dependencyNoVersion, eligibleVersion)); } else { if (inputDependencies.containsKey(dependencyNoVersion)) { eligibleVersion = inputDependencies.get(dependencyNoVersion).getVersion(); } else { eligibleVersion = versionList.get(versionList.size() - 1); } logger.trace(String.format("\tPicking the version %s:%s", dependencyNoVersion, eligibleVersion)); } BomDependency dependency = new BomDependency(dependencyNoVersion.getGroupId(), dependencyNoVersion.getArtifactId(), eligibleVersion); if (!externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } for (String version : versionList) { if (!version.equals(eligibleVersion)) { makeDependencyInEligible(new BomDependency(dependency.getGroupId(), dependency.getArtifactId(), version), null, eligibleVersion); } } } }
class DependencyAnalyzer { private Map<BomDependencyNoVersion, BomDependency> inputDependencies = new HashMap<>(); private Set<BomDependency> externalDependencies = new HashSet<>(); private Set<BomDependency> bomEligibleDependencies = new HashSet<>(); private Set<BomDependency> bomIneligibleDependencies = new HashSet<>(); private Map<BomDependencyNoVersion, BomDependency> coreDependencyNameToDependency = new HashMap<>(); private Map<BomDependency, BomDependencyErrorInfo> errorInfo = new HashMap(); private Map<BomDependencyNoVersion, HashMap<String, Collection<BomDependency>>> nameToVersionToChildrenDependencyTree = new TreeMap<>(new Comparator<BomDependencyNoVersion>() { @Override public int compare(BomDependencyNoVersion o1, BomDependencyNoVersion o2) { return (o1.getGroupId() + o1.getArtifactId()).compareTo(o1.getGroupId() + o2.getArtifactId()); } }); private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); DependencyAnalyzer(Collection<BomDependency> inputDependencies, Collection<BomDependency> externalDependencies) { if (inputDependencies != null) { this.inputDependencies = inputDependencies.stream().collect(Collectors.toMap(Utils::toBomDependencyNoVersion, dependency -> dependency)); } if (externalDependencies != null) { this.externalDependencies.addAll(externalDependencies); } } public Collection<BomDependency> getBomEligibleDependencies() { return this.bomEligibleDependencies; } public void reduce() { analyze(); generateReport(); this.bomEligibleDependencies.retainAll(this.inputDependencies.values()); } public boolean validate() { analyze(); generateReport(); return nameToVersionToChildrenDependencyTree.values().stream().anyMatch(value -> value.size() > 1); } private void analyze() { pickCoreDependencyRoots(); resolveTree(); resolveConflicts(); filterConflicts(); } private void generateReport() { Set<BomDependency> droppedDependencies = inputDependencies.values().stream().filter(dependency -> bomIneligibleDependencies.contains(dependency)).collect(Collectors.toSet()); if (droppedDependencies.size() == 0) { return; } if (errorInfo.size() > 0) { errorInfo.keySet().stream().forEach(key -> { if (droppedDependencies.contains(key)) { var conflictingDependencies = errorInfo.get(key).getConflictingDependencies(); var expectedDependency = errorInfo.get(key).getExpectedDependency(); if (expectedDependency != null) { logger.info("Dropped dependency {}.", key.toString(), expectedDependency); } conflictingDependencies.stream().forEach(conflictingDependency -> logger.info("\t\tIncludes dependency {}. Expected dependency {}", conflictingDependency.getActualDependency(), conflictingDependency.getExpectedDependency())); } }); } } private BomDependency getAzureCoreDependencyFromInput() { return inputDependencies.values().stream().filter(dependency -> dependency.getArtifactId().equals("azure-core")).findFirst().get(); } private void pickCoreDependencyRoots() { BomDependency coreDependency = getAzureCoreDependencyFromInput(); var coreDependencies = getDependencies(coreDependency); coreDependencyNameToDependency.put(toBomDependencyNoVersion(coreDependency), coreDependency); coreDependencies.forEach(dependency -> coreDependencyNameToDependency.put(toBomDependencyNoVersion(dependency), dependency)); for(var dependency : coreDependencyNameToDependency.values()) { if(!externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } } } /* Create a tree map of all the input binaries into the following map. * {groupId_artifactId}: {v1} : {all ancestors that include this binary.} * : {v2} : {all ancestors that include this binary.} * : {v3} : {all ancestors that include this binary.} */ private void resolveTree() { for (MavenDependency gaLibrary : inputDependencies.values()) { try { BomDependency parentDependency = new BomDependency(gaLibrary.getGroupId(), gaLibrary.getArtifactId(), gaLibrary.getVersion()); addDependencyToDependencyTree(parentDependency, null, nameToVersionToChildrenDependencyTree); List<BomDependency> dependencies = getDependencies(gaLibrary); for (BomDependency dependency : dependencies) { if (dependency.getScope() == ScopeType.TEST) { continue; } if (RESOLVED_EXCLUSION_LIST.contains(dependency.getArtifactId())) { continue; } BomDependency childDependency = new BomDependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()); addDependencyToDependencyTree(childDependency, parentDependency, nameToVersionToChildrenDependencyTree); } } catch (Exception ex) { System.out.println(ex); } } } private static List<BomDependency> getDependencies(MavenDependency dependency) { try { MavenResolvedArtifact mavenResolvedArtifact = getResolvedArtifact(dependency); return Arrays.stream(mavenResolvedArtifact.getDependencies()).map(mavenDependency -> new BomDependency(mavenDependency.getCoordinate().getGroupId(), mavenDependency.getCoordinate().getArtifactId(), mavenDependency.getCoordinate().getVersion(), mavenDependency.getScope())).collect(Collectors.toList()); } catch (Exception ex) { logger.error(ex.toString()); } return new ArrayList<>(); } private static void addDependencyToDependencyTree(BomDependency dependency, BomDependency parentDependency, Map<BomDependencyNoVersion, HashMap<String, Collection<BomDependency>>> dependencyTree) { if (IGNORE_CONFLICT_LIST.contains(dependency.getArtifactId())) { return; } dependencyTree.computeIfAbsent(new BomDependencyNoVersion(dependency.getGroupId(), dependency.getArtifactId()), key -> new HashMap<>()); var value = dependencyTree.get(dependency).computeIfAbsent(dependency.getVersion(), key -> new ArrayList<>()); if(parentDependency != null) { value.add(parentDependency); } } private void updateErrorInfo(BomDependency droppedDependency, String expectedVersion) { if (!errorInfo.containsKey(droppedDependency)) { errorInfo.put(droppedDependency, new BomDependencyErrorInfo(new BomDependency(droppedDependency.getGroupId(), droppedDependency.getArtifactId(), expectedVersion))); } } private void updateErrorInfo(BomDependency droppedDependency, BomDependency actualDependency, String expectedVersion) { updateErrorInfo(droppedDependency, expectedVersion); errorInfo.get(droppedDependency).addConflictingDependency(actualDependency, new BomDependency(actualDependency.getGroupId(), actualDependency.getArtifactId(), expectedVersion)); } private void makeDependencyInEligible(BomDependency dependency, BomDependency dependencyReason, String expectedVersion) { if (nameToVersionToChildrenDependencyTree.containsKey(dependency)) { HashMap<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(dependency); bomIneligibleDependencies.add(dependency); if (dependencyReason == null) { dependencyReason = dependency; updateErrorInfo(dependency, expectedVersion); } else { updateErrorInfo(dependency, dependencyReason, expectedVersion); } BomDependency finalDependencyReason = dependencyReason; versionToDependency.get(dependency.getVersion()).forEach(parent -> makeDependencyInEligible(parent, finalDependencyReason, expectedVersion)); } } private void resolveConflicts() { nameToVersionToChildrenDependencyTree.keySet().stream().forEach(this::resolveConflict); bomEligibleDependencies.removeAll(bomIneligibleDependencies); } private void filterConflicts() { nameToVersionToChildrenDependencyTree.keySet().stream().forEach( key -> { HashMap<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(key); if (versionToDependency.size() == 1) { BomDependency dependency = new BomDependency(key.getGroupId(), key.getArtifactId(), versionToDependency.keySet().stream().findFirst().get()); if (!bomIneligibleDependencies.contains(dependency) && !externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } } }); } }
class DependencyAnalyzer { private Map<BomDependencyNoVersion, BomDependency> inputDependencies = new HashMap<>(); private Set<BomDependency> externalDependencies = new HashSet<>(); private Set<BomDependency> bomEligibleDependencies = new HashSet<>(); private Set<BomDependency> bomIneligibleDependencies = new HashSet<>(); private Map<BomDependencyNoVersion, BomDependency> coreDependencyNameToDependency = new HashMap<>(); private Map<BomDependency, BomDependencyErrorInfo> errorInfo = new HashMap(); private Map<BomDependencyNoVersion, HashMap<String, Collection<BomDependency>>> nameToVersionToChildrenDependencyTree = new TreeMap<>(new Comparator<BomDependencyNoVersion>() { @Override public int compare(BomDependencyNoVersion o1, BomDependencyNoVersion o2) { return (o1.getGroupId() + o1.getArtifactId()).compareTo(o1.getGroupId() + o2.getArtifactId()); } }); private static Logger logger = LoggerFactory.getLogger(BomGenerator.class); DependencyAnalyzer(Collection<BomDependency> inputDependencies, Collection<BomDependency> externalDependencies) { if (inputDependencies != null) { this.inputDependencies = inputDependencies.stream().collect(Collectors.toMap(Utils::toBomDependencyNoVersion, dependency -> dependency)); } if (externalDependencies != null) { this.externalDependencies.addAll(externalDependencies); } } public Collection<BomDependency> getBomEligibleDependencies() { return this.bomEligibleDependencies; } public void reduce() { analyze(); generateReport(); this.bomEligibleDependencies.retainAll(this.inputDependencies.values()); } public boolean validate() { analyze(); generateReport(); return nameToVersionToChildrenDependencyTree.values().stream().anyMatch(value -> value.size() > 1); } private void analyze() { pickCoreDependencyRoots(); resolveTree(); resolveConflicts(); filterConflicts(); } private void generateReport() { Set<BomDependency> droppedDependencies = inputDependencies.values().stream().filter(dependency -> bomIneligibleDependencies.contains(dependency)).collect(Collectors.toSet()); if (droppedDependencies.size() == 0) { return; } if (errorInfo.size() > 0) { errorInfo.keySet().stream().forEach(key -> { if (droppedDependencies.contains(key)) { var conflictingDependencies = errorInfo.get(key).getConflictingDependencies(); var expectedDependency = errorInfo.get(key).getExpectedDependency(); if (expectedDependency != null) { logger.info("Dropped dependency {}.", key.toString(), expectedDependency); } conflictingDependencies.stream().forEach(conflictingDependency -> logger.info("\t\tIncludes dependency {}. Expected dependency {}", conflictingDependency.getActualDependency(), conflictingDependency.getExpectedDependency())); } }); } } private BomDependency getAzureCoreDependencyFromInput() { return inputDependencies.values().stream().filter(dependency -> dependency.getArtifactId().equals("azure-core")).findFirst().get(); } private void pickCoreDependencyRoots() { BomDependency coreDependency = getAzureCoreDependencyFromInput(); var coreDependencies = getDependencies(coreDependency); coreDependencyNameToDependency.put(toBomDependencyNoVersion(coreDependency), coreDependency); coreDependencies.forEach(dependency -> coreDependencyNameToDependency.put(toBomDependencyNoVersion(dependency), dependency)); for(var dependency : coreDependencyNameToDependency.values()) { if(!externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } } } /* Create a tree map of all the input binaries into the following map. * {groupId_artifactId}: {v1} : {all ancestors that include this binary.} * : {v2} : {all ancestors that include this binary.} * : {v3} : {all ancestors that include this binary.} */ private void resolveTree() { for (MavenDependency gaLibrary : inputDependencies.values()) { try { BomDependency parentDependency = new BomDependency(gaLibrary.getGroupId(), gaLibrary.getArtifactId(), gaLibrary.getVersion()); addDependencyToDependencyTree(parentDependency, null, nameToVersionToChildrenDependencyTree); List<BomDependency> dependencies = getDependencies(gaLibrary); for (BomDependency dependency : dependencies) { if (dependency.getScope() == ScopeType.TEST) { continue; } if (RESOLVED_EXCLUSION_LIST.contains(dependency.getArtifactId())) { continue; } BomDependency childDependency = new BomDependency(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion()); addDependencyToDependencyTree(childDependency, parentDependency, nameToVersionToChildrenDependencyTree); } } catch (Exception ex) { System.out.println(ex); } } } private static List<BomDependency> getDependencies(MavenDependency dependency) { try { MavenResolvedArtifact mavenResolvedArtifact = getResolvedArtifact(dependency); return Arrays.stream(mavenResolvedArtifact.getDependencies()).map(mavenDependency -> new BomDependency(mavenDependency.getCoordinate().getGroupId(), mavenDependency.getCoordinate().getArtifactId(), mavenDependency.getCoordinate().getVersion(), mavenDependency.getScope())).collect(Collectors.toList()); } catch (Exception ex) { logger.error(ex.toString()); } return new ArrayList<>(); } private static void addDependencyToDependencyTree(BomDependency dependency, BomDependency parentDependency, Map<BomDependencyNoVersion, HashMap<String, Collection<BomDependency>>> dependencyTree) { if (IGNORE_CONFLICT_LIST.contains(dependency.getArtifactId())) { return; } dependencyTree.computeIfAbsent(new BomDependencyNoVersion(dependency.getGroupId(), dependency.getArtifactId()), key -> new HashMap<>()); var value = dependencyTree.get(dependency).computeIfAbsent(dependency.getVersion(), key -> new ArrayList<>()); if(parentDependency != null) { value.add(parentDependency); } } private void updateErrorInfo(BomDependency droppedDependency, String expectedVersion) { if (!errorInfo.containsKey(droppedDependency)) { errorInfo.put(droppedDependency, new BomDependencyErrorInfo(new BomDependency(droppedDependency.getGroupId(), droppedDependency.getArtifactId(), expectedVersion))); } } private void updateErrorInfo(BomDependency droppedDependency, BomDependency actualDependency, String expectedVersion) { updateErrorInfo(droppedDependency, expectedVersion); errorInfo.get(droppedDependency).addConflictingDependency(actualDependency, new BomDependency(actualDependency.getGroupId(), actualDependency.getArtifactId(), expectedVersion)); } private void makeDependencyInEligible(BomDependency dependency, BomDependency dependencyReason, String expectedVersion) { if (nameToVersionToChildrenDependencyTree.containsKey(dependency)) { HashMap<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(dependency); bomIneligibleDependencies.add(dependency); if (dependencyReason == null) { dependencyReason = dependency; updateErrorInfo(dependency, expectedVersion); } else { updateErrorInfo(dependency, dependencyReason, expectedVersion); } BomDependency finalDependencyReason = dependencyReason; versionToDependency.get(dependency.getVersion()).forEach(parent -> makeDependencyInEligible(parent, finalDependencyReason, expectedVersion)); } } private void resolveConflicts() { nameToVersionToChildrenDependencyTree.keySet().stream().forEach(this::resolveConflict); bomEligibleDependencies.removeAll(bomIneligibleDependencies); } private void filterConflicts() { nameToVersionToChildrenDependencyTree.keySet().stream().forEach( key -> { HashMap<String, Collection<BomDependency>> versionToDependency = nameToVersionToChildrenDependencyTree.get(key); if (versionToDependency.size() == 1) { BomDependency dependency = new BomDependency(key.getGroupId(), key.getArtifactId(), versionToDependency.keySet().stream().findFirst().get()); if (!bomIneligibleDependencies.contains(dependency) && !externalDependencies.contains(dependency)) { bomEligibleDependencies.add(dependency); } } }); } }
should this be using the CoreUtils method added above?
private HttpPipeline createPipeline() { if (pipeline != null) { return pipeline; } final Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>(); final String applicationId = CoreUtils.getApplicationId(clientOptions, httpLogOptions); httpPolicies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); httpPolicies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential)); httpPolicies.add(new AddHeadersFromContextPolicy()); httpPolicies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(httpPolicies); httpPolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPolicies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(h -> httpHeaderList.add(new HttpHeader(h.getName(), h.getValue()))); if (!httpHeaderList.isEmpty()) { httpPolicies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } } httpPolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPolicyProviders.addAfterRetryPolicies(httpPolicies); return new HttpPipelineBuilder() .policies(httpPolicies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); }
}
private HttpPipeline createPipeline() { if (pipeline != null) { return pipeline; } final Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>(); final String applicationId = CoreUtils.getApplicationId(clientOptions, httpLogOptions); httpPolicies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); httpPolicies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential)); httpPolicies.add(new AddHeadersFromContextPolicy()); httpPolicies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(httpPolicies); httpPolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPolicies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(h -> httpHeaderList.add(new HttpHeader(h.getName(), h.getValue()))); if (!httpHeaderList.isEmpty()) { httpPolicies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } } httpPolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPolicyProviders.addAfterRetryPolicies(httpPolicies); return new HttpPipelineBuilder() .policies(httpPolicies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); }
class ServiceBusAdministrationClientBuilder { private static final String CLIENT_NAME; private static final String CLIENT_VERSION; static { Map<String, String> properties = CoreUtils.getProperties("azure-messaging-servicebus.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); } private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationClientBuilder.class); private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer(); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private Configuration configuration; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private TokenCredential tokenCredential; private ServiceBusServiceVersion serviceVersion; private ClientOptions clientOptions; /** * Constructs a builder with the default parameters. */ public ServiceBusAdministrationClientBuilder() { } /** * Creates a {@link ServiceBusAdministrationAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient} is invoked, a new instance of the client is created. * * <p>If {@link * {@link * other builder settings are ignored.</p> * * @return A {@link ServiceBusAdministrationAsyncClient} with the options set in the builder. * @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link * * {@link * @throws IllegalStateException If applicationId if set in both {@code httpLogOptions} and {@code clientOptions} * and not same. */ public ServiceBusAdministrationAsyncClient buildAsyncClient() { if (endpoint == null) { throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null.")); } final ServiceBusServiceVersion apiVersion = serviceVersion == null ? ServiceBusServiceVersion.getLatest() : serviceVersion; final HttpPipeline httpPipeline = createPipeline(); final ServiceBusManagementClientImpl client = new ServiceBusManagementClientImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializer) .endpoint(endpoint) .apiVersion(apiVersion.getVersion()) .buildClient(); return new ServiceBusAdministrationAsyncClient(client, serializer); } /** * Creates a {@link ServiceBusAdministrationClient} based on options set in the builder. Every time {@code * buildClient} is invoked, a new instance of the client is created. * * <p>If {@link * {@link * other builder settings are ignored.</p> * * @return A {@link ServiceBusAdministrationClient} with the options set in the builder. * @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link * * {@link * @throws IllegalStateException If applicationId if set in both {@code httpLogOptions} and {@code clientOptions} * and not same. */ public ServiceBusAdministrationClient buildClient() { return new ServiceBusAdministrationClient(buildAsyncClient()); } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ServiceBusAdministrationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the service endpoint for the Service Bus namespace. * * @param endpoint The URL of the Service Bus namespace. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public ServiceBusAdministrationClientBuilder endpoint(String endpoint) { final URL url; try { url = new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null.")); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = url.getHost(); return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the connection string for a Service Bus namespace or a specific Service Bus resource. * * @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException If {@code connectionString} is {@code null}. * @throws IllegalArgumentException If {@code connectionString} is an entity specific connection string, and not * a {@code connectionString} for the Service Bus namespace. */ public ServiceBusAdministrationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential; try { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY); } catch (Exception e) { throw logger.logExceptionAsError( new AzureException("Could not create the ServiceBusSharedKeyCredential.", e)); } this.endpoint = properties.getEndpoint().getHost(); if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot contain an EntityPath. It should be a namespace connection string.")); } return credential(properties.getEndpoint().getHost(), tokenCredential); } /** * Sets the credential used to authenticate HTTP requests to the Service Bus namespace. * * @param fullyQualifiedNamespace for the Service Bus. * @param credential {@link TokenCredential} to be used for authentication. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) { this.endpoint = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting * {@code applicationId} using {@link ClientOptions * for telemetry/monitoring purpose. * <p> * * @param clientOptions to be set on the client. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * * @see <a href="https: * policy</a> */ public ServiceBusAdministrationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ServiceBusAdministrationClientBuilder * or {@link ServiceBusAdministrationAsyncClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link * to build {@link ServiceBusAdministrationClient} or {@link ServiceBusAdministrationAsyncClient}. * * @param retryPolicy The user's retry policy applied to each request. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ServiceBusServiceVersion} that is used. By default {@link ServiceBusServiceVersion * is used when none is specified. * * @param serviceVersion Service version to use. * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder serviceVersion(ServiceBusServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Builds a new HTTP pipeline if none is set, or returns a user-provided one. * * @return A new HTTP pipeline or the user-defined one from {@link * @throws IllegalStateException if applicationId is not same in httpLogOptions and clientOptions. */ }
class ServiceBusAdministrationClientBuilder { private static final String CLIENT_NAME; private static final String CLIENT_VERSION; static { Map<String, String> properties = CoreUtils.getProperties("azure-messaging-servicebus.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); } private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationClientBuilder.class); private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer(); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private Configuration configuration; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private TokenCredential tokenCredential; private ServiceBusServiceVersion serviceVersion; private ClientOptions clientOptions; /** * Constructs a builder with the default parameters. */ public ServiceBusAdministrationClientBuilder() { } /** * Creates a {@link ServiceBusAdministrationAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient} is invoked, a new instance of the client is created. * * <p>If {@link * {@link * other builder settings are ignored.</p> * * @return A {@link ServiceBusAdministrationAsyncClient} with the options set in the builder. * @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link * * {@link * @throws IllegalStateException If applicationId if set in both {@code httpLogOptions} and {@code clientOptions} * and not same. */ public ServiceBusAdministrationAsyncClient buildAsyncClient() { if (endpoint == null) { throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null.")); } final ServiceBusServiceVersion apiVersion = serviceVersion == null ? ServiceBusServiceVersion.getLatest() : serviceVersion; final HttpPipeline httpPipeline = createPipeline(); final ServiceBusManagementClientImpl client = new ServiceBusManagementClientImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializer) .endpoint(endpoint) .apiVersion(apiVersion.getVersion()) .buildClient(); return new ServiceBusAdministrationAsyncClient(client, serializer); } /** * Creates a {@link ServiceBusAdministrationClient} based on options set in the builder. Every time {@code * buildClient} is invoked, a new instance of the client is created. * * <p>If {@link * {@link * other builder settings are ignored.</p> * * @return A {@link ServiceBusAdministrationClient} with the options set in the builder. * @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link * * {@link * @throws IllegalStateException If applicationId if set in both {@code httpLogOptions} and {@code clientOptions} * and not same. */ public ServiceBusAdministrationClient buildClient() { return new ServiceBusAdministrationClient(buildAsyncClient()); } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ServiceBusAdministrationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the service endpoint for the Service Bus namespace. * * @param endpoint The URL of the Service Bus namespace. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public ServiceBusAdministrationClientBuilder endpoint(String endpoint) { final URL url; try { url = new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null.")); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = url.getHost(); return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the connection string for a Service Bus namespace or a specific Service Bus resource. * * @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException If {@code connectionString} is {@code null}. * @throws IllegalArgumentException If {@code connectionString} is an entity specific connection string, and not * a {@code connectionString} for the Service Bus namespace. */ public ServiceBusAdministrationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential; try { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY); } catch (Exception e) { throw logger.logExceptionAsError( new AzureException("Could not create the ServiceBusSharedKeyCredential.", e)); } this.endpoint = properties.getEndpoint().getHost(); if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot contain an EntityPath. It should be a namespace connection string.")); } return credential(properties.getEndpoint().getHost(), tokenCredential); } /** * Sets the credential used to authenticate HTTP requests to the Service Bus namespace. * * @param fullyQualifiedNamespace for the Service Bus. * @param credential {@link TokenCredential} to be used for authentication. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) { this.endpoint = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting * {@code applicationId} using {@link ClientOptions * for telemetry/monitoring purpose. * <p> * * @param clientOptions to be set on the client. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * * @see <a href="https: * policy</a> */ public ServiceBusAdministrationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ServiceBusAdministrationClientBuilder * or {@link ServiceBusAdministrationAsyncClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link * to build {@link ServiceBusAdministrationClient} or {@link ServiceBusAdministrationAsyncClient}. * * @param retryPolicy The user's retry policy applied to each request. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ServiceBusServiceVersion} that is used. By default {@link ServiceBusServiceVersion * is used when none is specified. * * @param serviceVersion Service version to use. * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder serviceVersion(ServiceBusServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Builds a new HTTP pipeline if none is set, or returns a user-provided one. * * @return A new HTTP pipeline or the user-defined one from {@link * @throws IllegalStateException if applicationId is not same in httpLogOptions and clientOptions. */ }
I'll let libraries update once azure-core ships the API rather than using unreleased dependencies.
private HttpPipeline createPipeline() { if (pipeline != null) { return pipeline; } final Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>(); final String applicationId = CoreUtils.getApplicationId(clientOptions, httpLogOptions); httpPolicies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); httpPolicies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential)); httpPolicies.add(new AddHeadersFromContextPolicy()); httpPolicies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(httpPolicies); httpPolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPolicies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(h -> httpHeaderList.add(new HttpHeader(h.getName(), h.getValue()))); if (!httpHeaderList.isEmpty()) { httpPolicies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } } httpPolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPolicyProviders.addAfterRetryPolicies(httpPolicies); return new HttpPipelineBuilder() .policies(httpPolicies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); }
}
private HttpPipeline createPipeline() { if (pipeline != null) { return pipeline; } final Configuration buildConfiguration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration; final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>(); final String applicationId = CoreUtils.getApplicationId(clientOptions, httpLogOptions); httpPolicies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); httpPolicies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential)); httpPolicies.add(new AddHeadersFromContextPolicy()); httpPolicies.addAll(perCallPolicies); HttpPolicyProviders.addBeforeRetryPolicies(httpPolicies); httpPolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); httpPolicies.addAll(perRetryPolicies); if (clientOptions != null) { List<HttpHeader> httpHeaderList = new ArrayList<>(); clientOptions.getHeaders().forEach(h -> httpHeaderList.add(new HttpHeader(h.getName(), h.getValue()))); if (!httpHeaderList.isEmpty()) { httpPolicies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); } } httpPolicies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPolicyProviders.addAfterRetryPolicies(httpPolicies); return new HttpPipelineBuilder() .policies(httpPolicies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); }
class ServiceBusAdministrationClientBuilder { private static final String CLIENT_NAME; private static final String CLIENT_VERSION; static { Map<String, String> properties = CoreUtils.getProperties("azure-messaging-servicebus.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); } private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationClientBuilder.class); private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer(); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private Configuration configuration; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private TokenCredential tokenCredential; private ServiceBusServiceVersion serviceVersion; private ClientOptions clientOptions; /** * Constructs a builder with the default parameters. */ public ServiceBusAdministrationClientBuilder() { } /** * Creates a {@link ServiceBusAdministrationAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient} is invoked, a new instance of the client is created. * * <p>If {@link * {@link * other builder settings are ignored.</p> * * @return A {@link ServiceBusAdministrationAsyncClient} with the options set in the builder. * @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link * * {@link * @throws IllegalStateException If applicationId if set in both {@code httpLogOptions} and {@code clientOptions} * and not same. */ public ServiceBusAdministrationAsyncClient buildAsyncClient() { if (endpoint == null) { throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null.")); } final ServiceBusServiceVersion apiVersion = serviceVersion == null ? ServiceBusServiceVersion.getLatest() : serviceVersion; final HttpPipeline httpPipeline = createPipeline(); final ServiceBusManagementClientImpl client = new ServiceBusManagementClientImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializer) .endpoint(endpoint) .apiVersion(apiVersion.getVersion()) .buildClient(); return new ServiceBusAdministrationAsyncClient(client, serializer); } /** * Creates a {@link ServiceBusAdministrationClient} based on options set in the builder. Every time {@code * buildClient} is invoked, a new instance of the client is created. * * <p>If {@link * {@link * other builder settings are ignored.</p> * * @return A {@link ServiceBusAdministrationClient} with the options set in the builder. * @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link * * {@link * @throws IllegalStateException If applicationId if set in both {@code httpLogOptions} and {@code clientOptions} * and not same. */ public ServiceBusAdministrationClient buildClient() { return new ServiceBusAdministrationClient(buildAsyncClient()); } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ServiceBusAdministrationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the service endpoint for the Service Bus namespace. * * @param endpoint The URL of the Service Bus namespace. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public ServiceBusAdministrationClientBuilder endpoint(String endpoint) { final URL url; try { url = new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null.")); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = url.getHost(); return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the connection string for a Service Bus namespace or a specific Service Bus resource. * * @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException If {@code connectionString} is {@code null}. * @throws IllegalArgumentException If {@code connectionString} is an entity specific connection string, and not * a {@code connectionString} for the Service Bus namespace. */ public ServiceBusAdministrationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential; try { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY); } catch (Exception e) { throw logger.logExceptionAsError( new AzureException("Could not create the ServiceBusSharedKeyCredential.", e)); } this.endpoint = properties.getEndpoint().getHost(); if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot contain an EntityPath. It should be a namespace connection string.")); } return credential(properties.getEndpoint().getHost(), tokenCredential); } /** * Sets the credential used to authenticate HTTP requests to the Service Bus namespace. * * @param fullyQualifiedNamespace for the Service Bus. * @param credential {@link TokenCredential} to be used for authentication. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) { this.endpoint = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting * {@code applicationId} using {@link ClientOptions * for telemetry/monitoring purpose. * <p> * * @param clientOptions to be set on the client. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * * @see <a href="https: * policy</a> */ public ServiceBusAdministrationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ServiceBusAdministrationClientBuilder * or {@link ServiceBusAdministrationAsyncClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link * to build {@link ServiceBusAdministrationClient} or {@link ServiceBusAdministrationAsyncClient}. * * @param retryPolicy The user's retry policy applied to each request. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ServiceBusServiceVersion} that is used. By default {@link ServiceBusServiceVersion * is used when none is specified. * * @param serviceVersion Service version to use. * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder serviceVersion(ServiceBusServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Builds a new HTTP pipeline if none is set, or returns a user-provided one. * * @return A new HTTP pipeline or the user-defined one from {@link * @throws IllegalStateException if applicationId is not same in httpLogOptions and clientOptions. */ }
class ServiceBusAdministrationClientBuilder { private static final String CLIENT_NAME; private static final String CLIENT_VERSION; static { Map<String, String> properties = CoreUtils.getProperties("azure-messaging-servicebus.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); } private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationClientBuilder.class); private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer(); private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>(); private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>(); private Configuration configuration; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private HttpPipelinePolicy retryPolicy; private TokenCredential tokenCredential; private ServiceBusServiceVersion serviceVersion; private ClientOptions clientOptions; /** * Constructs a builder with the default parameters. */ public ServiceBusAdministrationClientBuilder() { } /** * Creates a {@link ServiceBusAdministrationAsyncClient} based on options set in the builder. Every time {@code * buildAsyncClient} is invoked, a new instance of the client is created. * * <p>If {@link * {@link * other builder settings are ignored.</p> * * @return A {@link ServiceBusAdministrationAsyncClient} with the options set in the builder. * @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link * * {@link * @throws IllegalStateException If applicationId if set in both {@code httpLogOptions} and {@code clientOptions} * and not same. */ public ServiceBusAdministrationAsyncClient buildAsyncClient() { if (endpoint == null) { throw logger.logExceptionAsError(new NullPointerException("'endpoint' cannot be null.")); } final ServiceBusServiceVersion apiVersion = serviceVersion == null ? ServiceBusServiceVersion.getLatest() : serviceVersion; final HttpPipeline httpPipeline = createPipeline(); final ServiceBusManagementClientImpl client = new ServiceBusManagementClientImplBuilder() .pipeline(httpPipeline) .serializerAdapter(serializer) .endpoint(endpoint) .apiVersion(apiVersion.getVersion()) .buildClient(); return new ServiceBusAdministrationAsyncClient(client, serializer); } /** * Creates a {@link ServiceBusAdministrationClient} based on options set in the builder. Every time {@code * buildClient} is invoked, a new instance of the client is created. * * <p>If {@link * {@link * other builder settings are ignored.</p> * * @return A {@link ServiceBusAdministrationClient} with the options set in the builder. * @throws NullPointerException if {@code endpoint} has not been set. This is automatically set when {@link * * {@link * @throws IllegalStateException If applicationId if set in both {@code httpLogOptions} and {@code clientOptions} * and not same. */ public ServiceBusAdministrationClient buildClient() { return new ServiceBusAdministrationClient(buildAsyncClient()); } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ServiceBusAdministrationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { perCallPolicies.add(policy); } else { perRetryPolicies.add(policy); } return this; } /** * Sets the service endpoint for the Service Bus namespace. * * @param endpoint The URL of the Service Bus namespace. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException if {@code endpoint} is null. * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. */ public ServiceBusAdministrationClientBuilder endpoint(String endpoint) { final URL url; try { url = new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null.")); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = url.getHost(); return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the connection string for a Service Bus namespace or a specific Service Bus resource. * * @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * @throws NullPointerException If {@code connectionString} is {@code null}. * @throws IllegalArgumentException If {@code connectionString} is an entity specific connection string, and not * a {@code connectionString} for the Service Bus namespace. */ public ServiceBusAdministrationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); final TokenCredential tokenCredential; try { tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY); } catch (Exception e) { throw logger.logExceptionAsError( new AzureException("Could not create the ServiceBusSharedKeyCredential.", e)); } this.endpoint = properties.getEndpoint().getHost(); if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'connectionString' cannot contain an EntityPath. It should be a namespace connection string.")); } return credential(properties.getEndpoint().getHost(), tokenCredential); } /** * Sets the credential used to authenticate HTTP requests to the Service Bus namespace. * * @param fullyQualifiedNamespace for the Service Bus. * @param credential {@link TokenCredential} to be used for authentication. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) { this.endpoint = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.tokenCredential = Objects.requireNonNull(credential, "'credential' cannot be null."); if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) { throw logger.logExceptionAsError( new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string.")); } return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p>If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting * {@code applicationId} using {@link ClientOptions * for telemetry/monitoring purpose. * <p> * * @param clientOptions to be set on the client. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. * * @see <a href="https: * policy</a> */ public ServiceBusAdministrationClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from {@link * ServiceBusAdministrationClientBuilder * or {@link ServiceBusAdministrationAsyncClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; } /** * Sets the {@link HttpPipelinePolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link * to build {@link ServiceBusAdministrationClient} or {@link ServiceBusAdministrationAsyncClient}. * * @param retryPolicy The user's retry policy applied to each request. * * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder retryPolicy(HttpPipelinePolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link ServiceBusServiceVersion} that is used. By default {@link ServiceBusServiceVersion * is used when none is specified. * * @param serviceVersion Service version to use. * @return The updated {@link ServiceBusAdministrationClientBuilder} object. */ public ServiceBusAdministrationClientBuilder serviceVersion(ServiceBusServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } /** * Builds a new HTTP pipeline if none is set, or returns a user-provided one. * * @return A new HTTP pipeline or the user-defined one from {@link * @throws IllegalStateException if applicationId is not same in httpLogOptions and clientOptions. */ }
should it also be added in isWebExceptionRetriableInternal?
private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; }
|| ex instanceof PrematureCloseException) {
private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
WebExceptionRetryPolicy uses this method, shouldn't we add PrematureCloseException here
private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; }
webEx instanceof SSLPeerUnverifiedException) {
private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
No - these exceptions all indicate that the request never made it to the service - so it is safe to retry even for writes (see the comment above the if statement). PrmeatureCloseException means a TCP reset was received before receiving the response - but it is unknown whether the request made it to the service endpoint.
private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; }
webEx instanceof SSLPeerUnverifiedException) {
private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
No - these exceptions all indicate that the request never made it to the service - so it is safe to retry even for writes (see the comment above the if statement). PrmeatureCloseException means a TCP reset was received before receiving the response - but it is unknown whether the request made it to the service endpoint.
private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; }
|| ex instanceof PrematureCloseException) {
private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
In general, we should try to validate when calling the `build` method instead of doing the validation on individual setter methods. That's the recommendation anyway. If we need to reset to default, there's no way for the user to know what the default is for a httpPipeline. So, setting to `null` would be a way for the build method to create the default pipeline as it usually would.
public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; }
this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null.");
public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; }
class CommunicationRelayClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_IDENTITY_PROPERTIES = "azure-communication-networktravesal.properties"; private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_IDENTITY_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationRelayClientBuilder */ /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); return this; } /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code clientOptions} is {@code null}. */ public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder configuration(Configuration configuration) { this.configuration = Objects.requireNonNull(configuration, "'configuration' cannot be null."); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * @param retryPolicy User's retry policy applied to each request. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If the specified {@code retryPolicy} is null. */ public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null"); return this; } /** * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayAsyncClient instance */ public CommunicationRelayAsyncClient buildAsyncClient() { return new CommunicationRelayAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayClient instance */ public CommunicationRelayClient buildClient() { return new CommunicationRelayClient(createServiceImpl()); } private CommunicationNetworkingClientImpl createServiceImpl() { Objects.requireNonNull(endpoint); HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationNetworkingClientImplBuilder clientBuilder = new CommunicationNetworkingClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.azureKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.azureKeyCredential != null) { return new HmacAuthenticationPolicy(this.azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); applyRequiredPolicies(policies, authorizationPolicy); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies, HttpPipelinePolicy authorizationPolicy) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; String applicationId = null; if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { applicationId = buildClientOptions.getApplicationId(); } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { applicationId = buildLogOptions.getApplicationId(); } policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); policies.add(new CookiePolicy()); policies.add(authorizationPolicy); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
class CommunicationRelayClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES = "azure-communication-networktraversal.properties"; private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private String connectionString; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationRelayClientBuilder */ /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = keyCredential; return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder connectionString(String connectionString) { CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(customPolicy); return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * @param retryPolicy User's retry policy applied to each request. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayAsyncClient instance */ public CommunicationRelayAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return new CommunicationRelayAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayClient instance */ public CommunicationRelayClient buildClient() { return new CommunicationRelayClient(buildAsyncClient()); } private CommunicationNetworkingClientImpl createServiceImpl() { HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationNetworkingClientImplBuilder clientBuilder = new CommunicationNetworkingClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.azureKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.azureKeyCredential != null) { return new HmacAuthenticationPolicy(this.azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); applyRequiredPolicies(policies, authorizationPolicy); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies, HttpPipelinePolicy authorizationPolicy) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; String applicationId = null; if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { applicationId = buildClientOptions.getApplicationId(); } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { applicationId = buildLogOptions.getApplicationId(); } policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); policies.add(new CookiePolicy()); policies.add(authorizationPolicy); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
gotcha, thanks
private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; }
|| ex instanceof PrematureCloseException) {
private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
I think this will introduced the regression where on PrmeatureCloseException sdk will do the failover. I will discuss it offline and we might need to revert the pr
private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; }
|| ex instanceof PrematureCloseException) {
private static boolean isNetworkFailureInternal(Exception ex) { if (ex instanceof ClosedChannelException || ex instanceof SocketException || ex instanceof SSLException || ex instanceof UnknownHostException || ex instanceof PrematureCloseException) { return true; } if (ex instanceof UnknownServiceException || ex instanceof HttpRetryException || ex instanceof InterruptedByTimeoutException || ex instanceof InterruptedIOException) { return true; } if (ex instanceof ChannelException) { return true; } return false; }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
class WebExceptionUtility { public static boolean isWebExceptionRetriable(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isWebExceptionRetriableInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isWebExceptionRetriableInternal(Exception ex) { IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { return false; } if (webEx instanceof ConnectException || webEx instanceof UnknownHostException || webEx instanceof SSLHandshakeException || webEx instanceof NoRouteToHostException || webEx instanceof SSLPeerUnverifiedException) { return true; } return false; } public static boolean isNetworkFailure(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isNetworkFailureInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } public static boolean isReadTimeoutException(Exception ex) { Exception iterator = ex; while (iterator != null) { if (WebExceptionUtility.isReadTimeoutExceptionInternal(iterator)) { return true; } Throwable t = iterator.getCause(); iterator = Utils.as(t, Exception.class); } return false; } private static boolean isReadTimeoutExceptionInternal(Exception ex) { if (ex instanceof ReadTimeoutException) { return true; } return false; } }
A Table-level SAS is supported by Cosmos - or are those separate tests?
public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); }
Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints.");
public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } } @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } } @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
Do not throw exception directly. Wrap this with monoError.
Mono<Response<TableTransactionResult>> submitTransactionWithResponse(List<TableTransactionAction> transactionActions, Context context) { Context finalContext = context == null ? Context.NONE : context; if (transactionActions.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("A transaction must contain at least one operation.")); } final List<TransactionalBatchAction> operations = new ArrayList<>(); for (TableTransactionAction transactionAction : transactionActions) { switch (transactionAction.getActionType()) { case CREATE: operations.add(new TransactionalBatchAction.CreateEntity(transactionAction.getEntity())); break; case UPSERT_MERGE: operations.add(new TransactionalBatchAction.UpsertEntity(transactionAction.getEntity(), TableEntityUpdateMode.MERGE)); break; case UPSERT_REPLACE: operations.add(new TransactionalBatchAction.UpsertEntity(transactionAction.getEntity(), TableEntityUpdateMode.REPLACE)); break; case UPDATE_MERGE: operations.add(new TransactionalBatchAction.UpdateEntity(transactionAction.getEntity(), TableEntityUpdateMode.MERGE, transactionAction.getIfUnchanged())); break; case UPDATE_REPLACE: operations.add(new TransactionalBatchAction.UpdateEntity(transactionAction.getEntity(), TableEntityUpdateMode.REPLACE, transactionAction.getIfUnchanged())); break; case DELETE: operations.add( new TransactionalBatchAction.DeleteEntity(transactionAction.getEntity(), transactionAction.getIfUnchanged())); break; default: break; } } try { return Flux.fromIterable(operations) .flatMapSequential(op -> op.prepareRequest(transactionalBatchClient).zipWith(Mono.just(op))) .collect(TransactionalBatchRequestBody::new, (body, pair) -> body.addChangeOperation(new TransactionalBatchSubRequest(pair.getT2(), pair.getT1()))) .publishOn(Schedulers.boundedElastic()) .flatMap(body -> transactionalBatchImplementation.submitTransactionalBatchWithRestResponseAsync(body, null, finalContext).zipWith(Mono.just(body))) .onErrorMap(TableUtils::mapThrowableToTableServiceException) .flatMap(pair -> parseResponse(pair.getT2(), pair.getT1())) .map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), new TableTransactionResult(transactionActions, response.getValue()))); } catch (RuntimeException e) { return monoError(logger, e); } }
}
new IllegalArgumentException("A transaction must contain at least one operation.")); } final List<TransactionalBatchAction> operations = new ArrayList<>(); for (TableTransactionAction transactionAction : transactionActions) { switch (transactionAction.getActionType()) { case CREATE: operations.add(new TransactionalBatchAction.CreateEntity(transactionAction.getEntity())); break; case UPSERT_MERGE: operations.add(new TransactionalBatchAction.UpsertEntity(transactionAction.getEntity(), TableEntityUpdateMode.MERGE)); break; case UPSERT_REPLACE: operations.add(new TransactionalBatchAction.UpsertEntity(transactionAction.getEntity(), TableEntityUpdateMode.REPLACE)); break; case UPDATE_MERGE: operations.add(new TransactionalBatchAction.UpdateEntity(transactionAction.getEntity(), TableEntityUpdateMode.MERGE, transactionAction.getIfUnchanged())); break; case UPDATE_REPLACE: operations.add(new TransactionalBatchAction.UpdateEntity(transactionAction.getEntity(), TableEntityUpdateMode.REPLACE, transactionAction.getIfUnchanged())); break; case DELETE: operations.add( new TransactionalBatchAction.DeleteEntity(transactionAction.getEntity(), transactionAction.getIfUnchanged())); break; default: break; } }
class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } }
class EntityPaged<T extends TableEntity> implements PagedResponse<T> { private final Response<TableEntityQueryResponse> httpResponse; private final IterableStream<T> entityStream; private final String continuationToken; EntityPaged(Response<TableEntityQueryResponse> httpResponse, List<T> entityList, String nextPartitionKey, String nextRowKey) { if (nextPartitionKey == null || nextRowKey == null) { this.continuationToken = null; } else { this.continuationToken = String.join(DELIMITER_CONTINUATION_TOKEN, nextPartitionKey, nextRowKey); } this.httpResponse = httpResponse; this.entityStream = IterableStream.of(entityList); } @Override public int getStatusCode() { return httpResponse.getStatusCode(); } @Override public HttpHeaders getHeaders() { return httpResponse.getHeaders(); } @Override public HttpRequest getRequest() { return httpResponse.getRequest(); } @Override public IterableStream<T> getElements() { return entityStream; } @Override public String getContinuationToken() { return continuationToken; } @Override public void close() { } }
You are right, this is supported on the Table level by Cosmos. I will remove the assumption.
public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); }
Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints.");
public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } } @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } } @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
Why do we return different exceptions for the same transaction batch? Whether the request is made to Cosmos or to Storage, the user should get the same exception.
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } }
}
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
Checking for exception messages is not reliable. Service can change the error message and these tests will start failing. Are there other fields in the exception that are part of the service contract that we can use to validate?
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue)); return; } catch (TableServiceException e) { assertTrue(IS_COSMOS_TEST); assertTrue(e.getMessage().contains("Status code 400")); assertTrue(e.getMessage().contains("InvalidDuplicateRow")); assertTrue(e.getMessage().contains("The batch request contains multiple changes with same row key.")); assertTrue(e.getMessage().contains("An entity can appear only once in a batch request.")); return; } fail(); }
assertTrue(e.getMessage().contains("Status code 400"));
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue)); return; } catch (TableServiceException e) { assertTrue(IS_COSMOS_TEST); assertEquals(400, e.getResponse().getStatusCode()); assertTrue(e.getMessage().contains("InvalidDuplicateRow")); return; } fail(); }
class TableClientTest extends TestBase { private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildClient(); tableClient.createTable(); } @Test void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClient tableClient2 = getClientBuilder(tableName2, connectionString).buildClient(); assertNotNull(tableClient2.createTable()); } @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClient tableClient2 = getClientBuilder(tableName2, connectionString).buildClient(); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient2.createTableWithResponse(null, null).getStatusCode()); } @Test void createEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); assertDoesNotThrow(() -> tableClient.createEntity(tableEntity)); } @Test void createEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.createEntityWithResponse(entity, null, null).getStatusCode()); } @Test void createEntityWithAllSupportedDataTypes() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); } /*@Test void createEntitySubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }*/ @Test void deleteTable() { assertDoesNotThrow(() -> tableClient.deleteTable()); } @Test void deleteNonExistingTable() { tableClient.deleteTable(); assertDoesNotThrow(() -> tableClient.deleteTable()); } @Test void deleteTableWithResponse() { final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.deleteTableWithResponse(null, null).getStatusCode()); } @Test void deleteNonExistingTableWithResponse() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse(null, null); assertEquals(expectedStatusCode, tableClient.deleteTableWithResponse(null, null).getStatusCode()); } @Test void deleteEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertDoesNotThrow(() -> tableClient.deleteEntity(partitionKeyValue, rowKeyValue)); } @Test void deleteNonExistingEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); assertDoesNotThrow(() -> tableClient.deleteEntity(partitionKeyValue, rowKeyValue)); } @Test void deleteEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(createdEntity, false, null, null).getStatusCode()); } @Test void deleteNonExistingEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(entity, false, null, null).getStatusCode()); } @Test void deleteEntityWithResponseMatchETag() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(createdEntity, true, null, null).getStatusCode()); } @Test void getEntityWithResponse() { getEntityWithResponseImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseImpl(TableClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); } @Test void getEntityWithResponseWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList, null, null); final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); } /*@Test void getEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class, null, null); SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }*/ @Test void updateEntityWithResponseReplace() { updateEntityWithResponse(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMerge() { updateEntityWithResponse(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponse(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); assertEquals(expectedStatusCode, tableClient.updateEntityWithResponse(createdEntity, mode, true, null, null).getStatusCode()); TableEntity entity = tableClient.getEntity(partitionKeyValue, rowKeyValue); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); } /*@Test void updateEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity); tableEntity.setSubclassProperty("UpdatedValue"); assertEquals(expectedStatusCode, tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true, null, null) .getStatusCode())); TableEntity entity = tableClient.getEntity(partitionKeyValue, rowKeyValue); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }*/ @Test void listEntities() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities().iterableByPage().iterator(); assertTrue(iterator.hasNext()); List<TableEntity> retrievedEntities = iterator.next().getValue(); TableEntity retrievedEntity = retrievedEntities.get(0); TableEntity retrievedEntity2 = retrievedEntities.get(1); assertEquals(partitionKeyValue, retrievedEntity.getPartitionKey()); assertEquals(rowKeyValue, retrievedEntity.getRowKey()); assertEquals(partitionKeyValue, retrievedEntity2.getPartitionKey()); assertEquals(rowKeyValue2, retrievedEntity2.getRowKey()); } @Test void listEntitiesWithFilter() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); tableClient.listEntities(options, null, null).forEach(tableEntity -> { assertEquals(partitionKeyValue, tableEntity.getPartitionKey()); assertEquals(rowKeyValue, tableEntity.getRowKey()); }); } @Test void listEntitiesWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); TableEntity retrievedEntity = iterator.next().getValue().get(0); assertNull(retrievedEntity.getPartitionKey()); assertNull(retrievedEntity.getRowKey()); assertEquals("valueC", retrievedEntity.getProperties().get("propertyC")); assertNull(retrievedEntity.getProperties().get("propertyD")); } @Test void listEntitiesWithTop() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); assertEquals(2, iterator.next().getValue().size()); } /*@Test void listEntitiesSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(SampleEntity.class).iterableByPage().iterator(); assertTrue(iterator.hasNext()); List<TableEntity> retrievedEntities = iterator.next().getValue(); TableEntity retrievedEntity = retrievedEntities.get(0); TableEntity retrievedEntity2 = retrievedEntities.get(1); assertEquals(partitionKeyValue, retrievedEntity.getPartitionKey()); assertEquals(rowKeyValue, retrievedEntity.getRowKey()); assertEquals(partitionKeyValue, retrievedEntity2.getPartitionKey()); assertEquals(rowKeyValue2, retrievedEntity2.getRowKey()); }*/ @Test void submitTransaction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch, null, null); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); final Response<TableTransactionResult> response = tableClient.submitTransactionWithResponse(transactionalBatch, null, null); assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("DeleteEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue2)); return; } fail(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { if (IS_COSMOS_TEST) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue)); } else { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue2)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue2)); } return; } fail(); } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient = tableClientBuilder.buildClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.createEntityWithResponse(entity, null, null).getStatusCode()); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier), null, null) .getStatusCode()); TableAccessPolicies tableAccessPolicies = tableClient.getAccessPolicies(); assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers, null, null).getStatusCode()); TableAccessPolicies tableAccessPolicies = tableClient.getAccessPolicies(); assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } } }
class TableClientTest extends TestBase { private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildClient(); tableClient.createTable(); } @Test void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClient tableClient2 = getClientBuilder(tableName2, connectionString).buildClient(); assertNotNull(tableClient2.createTable()); } @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClient tableClient2 = getClientBuilder(tableName2, connectionString).buildClient(); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient2.createTableWithResponse(null, null).getStatusCode()); } @Test void createEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); assertDoesNotThrow(() -> tableClient.createEntity(tableEntity)); } @Test void createEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.createEntityWithResponse(entity, null, null).getStatusCode()); } @Test void createEntityWithAllSupportedDataTypes() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); } /*@Test void createEntitySubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }*/ @Test void deleteTable() { assertDoesNotThrow(() -> tableClient.deleteTable()); } @Test void deleteNonExistingTable() { tableClient.deleteTable(); assertDoesNotThrow(() -> tableClient.deleteTable()); } @Test void deleteTableWithResponse() { final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.deleteTableWithResponse(null, null).getStatusCode()); } @Test void deleteNonExistingTableWithResponse() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse(null, null); assertEquals(expectedStatusCode, tableClient.deleteTableWithResponse(null, null).getStatusCode()); } @Test void deleteEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertDoesNotThrow(() -> tableClient.deleteEntity(partitionKeyValue, rowKeyValue)); } @Test void deleteNonExistingEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); assertDoesNotThrow(() -> tableClient.deleteEntity(partitionKeyValue, rowKeyValue)); } @Test void deleteEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(createdEntity, false, null, null).getStatusCode()); } @Test void deleteNonExistingEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(entity, false, null, null).getStatusCode()); } @Test void deleteEntityWithResponseMatchETag() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(createdEntity, true, null, null).getStatusCode()); } @Test void getEntityWithResponse() { getEntityWithResponseImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseImpl(TableClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); } @Test void getEntityWithResponseWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList, null, null); final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); } /*@Test void getEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class, null, null); SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }*/ @Test void updateEntityWithResponseReplace() { updateEntityWithResponse(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMerge() { updateEntityWithResponse(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponse(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); assertEquals(expectedStatusCode, tableClient.updateEntityWithResponse(createdEntity, mode, true, null, null).getStatusCode()); TableEntity entity = tableClient.getEntity(partitionKeyValue, rowKeyValue); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); } /*@Test void updateEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity); tableEntity.setSubclassProperty("UpdatedValue"); assertEquals(expectedStatusCode, tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true, null, null) .getStatusCode())); TableEntity entity = tableClient.getEntity(partitionKeyValue, rowKeyValue); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }*/ @Test void listEntities() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities().iterableByPage().iterator(); assertTrue(iterator.hasNext()); List<TableEntity> retrievedEntities = iterator.next().getValue(); TableEntity retrievedEntity = retrievedEntities.get(0); TableEntity retrievedEntity2 = retrievedEntities.get(1); assertEquals(partitionKeyValue, retrievedEntity.getPartitionKey()); assertEquals(rowKeyValue, retrievedEntity.getRowKey()); assertEquals(partitionKeyValue, retrievedEntity2.getPartitionKey()); assertEquals(rowKeyValue2, retrievedEntity2.getRowKey()); } @Test void listEntitiesWithFilter() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); tableClient.listEntities(options, null, null).forEach(tableEntity -> { assertEquals(partitionKeyValue, tableEntity.getPartitionKey()); assertEquals(rowKeyValue, tableEntity.getRowKey()); }); } @Test void listEntitiesWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); TableEntity retrievedEntity = iterator.next().getValue().get(0); assertNull(retrievedEntity.getPartitionKey()); assertNull(retrievedEntity.getRowKey()); assertEquals("valueC", retrievedEntity.getProperties().get("propertyC")); assertNull(retrievedEntity.getProperties().get("propertyD")); } @Test void listEntitiesWithTop() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); assertEquals(2, iterator.next().getValue().size()); } /*@Test void listEntitiesSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(SampleEntity.class).iterableByPage().iterator(); assertTrue(iterator.hasNext()); List<TableEntity> retrievedEntities = iterator.next().getValue(); TableEntity retrievedEntity = retrievedEntities.get(0); TableEntity retrievedEntity2 = retrievedEntities.get(1); assertEquals(partitionKeyValue, retrievedEntity.getPartitionKey()); assertEquals(rowKeyValue, retrievedEntity.getRowKey()); assertEquals(partitionKeyValue, retrievedEntity2.getPartitionKey()); assertEquals(rowKeyValue2, retrievedEntity2.getRowKey()); }*/ @Test void submitTransaction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch, null, null); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); final Response<TableTransactionResult> response = tableClient.submitTransactionWithResponse(transactionalBatch, null, null); assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("DeleteEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue2)); return; } fail(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { if (IS_COSMOS_TEST) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue)); } else { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue2)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue2)); } return; } fail(); } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient newTableClient = tableClientBuilder.buildClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, newTableClient.createEntityWithResponse(entity, null, null).getStatusCode()); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier), null, null) .getStatusCode()); TableAccessPolicies tableAccessPolicies = tableClient.getAccessPolicies(); assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers, null, null).getStatusCode()); TableAccessPolicies tableAccessPolicies = tableClient.getAccessPolicies(); assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } } }
Because Cosmos is not consistent with Storage in this particular error scenario, it returns a `400` status code with the error message shown above instead of returning a `202` multipart response with the error message included within. I will talk to the Cosmos team about this and figure if it's intended or not.
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } }
}
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
I think we can check for the actual status code for now until we figure out if the Cosmos service not returning a multipart response is intended behavior.
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue)); return; } catch (TableServiceException e) { assertTrue(IS_COSMOS_TEST); assertTrue(e.getMessage().contains("Status code 400")); assertTrue(e.getMessage().contains("InvalidDuplicateRow")); assertTrue(e.getMessage().contains("The batch request contains multiple changes with same row key.")); assertTrue(e.getMessage().contains("An entity can appear only once in a batch request.")); return; } fail(); }
assertTrue(e.getMessage().contains("Status code 400"));
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue)); return; } catch (TableServiceException e) { assertTrue(IS_COSMOS_TEST); assertEquals(400, e.getResponse().getStatusCode()); assertTrue(e.getMessage().contains("InvalidDuplicateRow")); return; } fail(); }
class TableClientTest extends TestBase { private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildClient(); tableClient.createTable(); } @Test void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClient tableClient2 = getClientBuilder(tableName2, connectionString).buildClient(); assertNotNull(tableClient2.createTable()); } @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClient tableClient2 = getClientBuilder(tableName2, connectionString).buildClient(); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient2.createTableWithResponse(null, null).getStatusCode()); } @Test void createEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); assertDoesNotThrow(() -> tableClient.createEntity(tableEntity)); } @Test void createEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.createEntityWithResponse(entity, null, null).getStatusCode()); } @Test void createEntityWithAllSupportedDataTypes() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); } /*@Test void createEntitySubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }*/ @Test void deleteTable() { assertDoesNotThrow(() -> tableClient.deleteTable()); } @Test void deleteNonExistingTable() { tableClient.deleteTable(); assertDoesNotThrow(() -> tableClient.deleteTable()); } @Test void deleteTableWithResponse() { final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.deleteTableWithResponse(null, null).getStatusCode()); } @Test void deleteNonExistingTableWithResponse() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse(null, null); assertEquals(expectedStatusCode, tableClient.deleteTableWithResponse(null, null).getStatusCode()); } @Test void deleteEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertDoesNotThrow(() -> tableClient.deleteEntity(partitionKeyValue, rowKeyValue)); } @Test void deleteNonExistingEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); assertDoesNotThrow(() -> tableClient.deleteEntity(partitionKeyValue, rowKeyValue)); } @Test void deleteEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(createdEntity, false, null, null).getStatusCode()); } @Test void deleteNonExistingEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(entity, false, null, null).getStatusCode()); } @Test void deleteEntityWithResponseMatchETag() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(createdEntity, true, null, null).getStatusCode()); } @Test void getEntityWithResponse() { getEntityWithResponseImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseImpl(TableClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); } @Test void getEntityWithResponseWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList, null, null); final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); } /*@Test void getEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class, null, null); SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }*/ @Test void updateEntityWithResponseReplace() { updateEntityWithResponse(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMerge() { updateEntityWithResponse(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponse(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); assertEquals(expectedStatusCode, tableClient.updateEntityWithResponse(createdEntity, mode, true, null, null).getStatusCode()); TableEntity entity = tableClient.getEntity(partitionKeyValue, rowKeyValue); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); } /*@Test void updateEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity); tableEntity.setSubclassProperty("UpdatedValue"); assertEquals(expectedStatusCode, tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true, null, null) .getStatusCode())); TableEntity entity = tableClient.getEntity(partitionKeyValue, rowKeyValue); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }*/ @Test void listEntities() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities().iterableByPage().iterator(); assertTrue(iterator.hasNext()); List<TableEntity> retrievedEntities = iterator.next().getValue(); TableEntity retrievedEntity = retrievedEntities.get(0); TableEntity retrievedEntity2 = retrievedEntities.get(1); assertEquals(partitionKeyValue, retrievedEntity.getPartitionKey()); assertEquals(rowKeyValue, retrievedEntity.getRowKey()); assertEquals(partitionKeyValue, retrievedEntity2.getPartitionKey()); assertEquals(rowKeyValue2, retrievedEntity2.getRowKey()); } @Test void listEntitiesWithFilter() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); tableClient.listEntities(options, null, null).forEach(tableEntity -> { assertEquals(partitionKeyValue, tableEntity.getPartitionKey()); assertEquals(rowKeyValue, tableEntity.getRowKey()); }); } @Test void listEntitiesWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); TableEntity retrievedEntity = iterator.next().getValue().get(0); assertNull(retrievedEntity.getPartitionKey()); assertNull(retrievedEntity.getRowKey()); assertEquals("valueC", retrievedEntity.getProperties().get("propertyC")); assertNull(retrievedEntity.getProperties().get("propertyD")); } @Test void listEntitiesWithTop() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); assertEquals(2, iterator.next().getValue().size()); } /*@Test void listEntitiesSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(SampleEntity.class).iterableByPage().iterator(); assertTrue(iterator.hasNext()); List<TableEntity> retrievedEntities = iterator.next().getValue(); TableEntity retrievedEntity = retrievedEntities.get(0); TableEntity retrievedEntity2 = retrievedEntities.get(1); assertEquals(partitionKeyValue, retrievedEntity.getPartitionKey()); assertEquals(rowKeyValue, retrievedEntity.getRowKey()); assertEquals(partitionKeyValue, retrievedEntity2.getPartitionKey()); assertEquals(rowKeyValue2, retrievedEntity2.getRowKey()); }*/ @Test void submitTransaction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch, null, null); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); final Response<TableTransactionResult> response = tableClient.submitTransactionWithResponse(transactionalBatch, null, null); assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("DeleteEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue2)); return; } fail(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { if (IS_COSMOS_TEST) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue)); } else { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue2)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue2)); } return; } fail(); } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient = tableClientBuilder.buildClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.createEntityWithResponse(entity, null, null).getStatusCode()); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier), null, null) .getStatusCode()); TableAccessPolicies tableAccessPolicies = tableClient.getAccessPolicies(); assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers, null, null).getStatusCode()); TableAccessPolicies tableAccessPolicies = tableClient.getAccessPolicies(); assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } } }
class TableClientTest extends TestBase { private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildClient(); tableClient.createTable(); } @Test void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClient tableClient2 = getClientBuilder(tableName2, connectionString).buildClient(); assertNotNull(tableClient2.createTable()); } @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClient tableClient2 = getClientBuilder(tableName2, connectionString).buildClient(); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient2.createTableWithResponse(null, null).getStatusCode()); } @Test void createEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); assertDoesNotThrow(() -> tableClient.createEntity(tableEntity)); } @Test void createEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.createEntityWithResponse(entity, null, null).getStatusCode()); } @Test void createEntityWithAllSupportedDataTypes() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); } /*@Test void createEntitySubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }*/ @Test void deleteTable() { assertDoesNotThrow(() -> tableClient.deleteTable()); } @Test void deleteNonExistingTable() { tableClient.deleteTable(); assertDoesNotThrow(() -> tableClient.deleteTable()); } @Test void deleteTableWithResponse() { final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.deleteTableWithResponse(null, null).getStatusCode()); } @Test void deleteNonExistingTableWithResponse() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse(null, null); assertEquals(expectedStatusCode, tableClient.deleteTableWithResponse(null, null).getStatusCode()); } @Test void deleteEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertDoesNotThrow(() -> tableClient.deleteEntity(partitionKeyValue, rowKeyValue)); } @Test void deleteNonExistingEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); assertDoesNotThrow(() -> tableClient.deleteEntity(partitionKeyValue, rowKeyValue)); } @Test void deleteEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(createdEntity, false, null, null).getStatusCode()); } @Test void deleteNonExistingEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(entity, false, null, null).getStatusCode()); } @Test void deleteEntityWithResponseMatchETag() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); assertEquals(expectedStatusCode, tableClient.deleteEntityWithResponse(createdEntity, true, null, null).getStatusCode()); } @Test void getEntityWithResponse() { getEntityWithResponseImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseImpl(TableClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); } @Test void getEntityWithResponseWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList, null, null); final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); } /*@Test void getEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class, null, null); SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }*/ @Test void updateEntityWithResponseReplace() { updateEntityWithResponse(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMerge() { updateEntityWithResponse(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponse(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); assertEquals(expectedStatusCode, tableClient.updateEntityWithResponse(createdEntity, mode, true, null, null).getStatusCode()); TableEntity entity = tableClient.getEntity(partitionKeyValue, rowKeyValue); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); } /*@Test void updateEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity); tableEntity.setSubclassProperty("UpdatedValue"); assertEquals(expectedStatusCode, tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true, null, null) .getStatusCode())); TableEntity entity = tableClient.getEntity(partitionKeyValue, rowKeyValue); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }*/ @Test void listEntities() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities().iterableByPage().iterator(); assertTrue(iterator.hasNext()); List<TableEntity> retrievedEntities = iterator.next().getValue(); TableEntity retrievedEntity = retrievedEntities.get(0); TableEntity retrievedEntity2 = retrievedEntities.get(1); assertEquals(partitionKeyValue, retrievedEntity.getPartitionKey()); assertEquals(rowKeyValue, retrievedEntity.getRowKey()); assertEquals(partitionKeyValue, retrievedEntity2.getPartitionKey()); assertEquals(rowKeyValue2, retrievedEntity2.getRowKey()); } @Test void listEntitiesWithFilter() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); tableClient.listEntities(options, null, null).forEach(tableEntity -> { assertEquals(partitionKeyValue, tableEntity.getPartitionKey()); assertEquals(rowKeyValue, tableEntity.getRowKey()); }); } @Test void listEntitiesWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); TableEntity retrievedEntity = iterator.next().getValue().get(0); assertNull(retrievedEntity.getPartitionKey()); assertNull(retrievedEntity.getRowKey()); assertEquals("valueC", retrievedEntity.getProperties().get("propertyC")); assertNull(retrievedEntity.getProperties().get("propertyD")); } @Test void listEntitiesWithTop() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); assertEquals(2, iterator.next().getValue().size()); } /*@Test void listEntitiesSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)); Iterator<PagedResponse<TableEntity>> iterator = tableClient.listEntities(SampleEntity.class).iterableByPage().iterator(); assertTrue(iterator.hasNext()); List<TableEntity> retrievedEntities = iterator.next().getValue(); TableEntity retrievedEntity = retrievedEntities.get(0); TableEntity retrievedEntity2 = retrievedEntities.get(1); assertEquals(partitionKeyValue, retrievedEntity.getPartitionKey()); assertEquals(rowKeyValue, retrievedEntity.getRowKey()); assertEquals(partitionKeyValue, retrievedEntity2.getPartitionKey()); assertEquals(rowKeyValue2, retrievedEntity2.getRowKey()); }*/ @Test void submitTransaction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch, null, null); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); final Response<TableEntity> response = tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, null, null); final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); final Response<TableTransactionResult> response = tableClient.submitTransactionWithResponse(transactionalBatch, null, null); assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("DeleteEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue2)); return; } fail(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); try { tableClient.submitTransactionWithResponse(transactionalBatch, null, null); } catch (TableTransactionFailedException e) { if (IS_COSMOS_TEST) { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue)); } else { assertTrue(e.getMessage().contains("An action within the operation failed")); assertTrue(e.getMessage().contains("The failed operation was")); assertTrue(e.getMessage().contains("CreateEntity")); assertTrue(e.getMessage().contains("partitionKey='" + partitionKeyValue2)); assertTrue(e.getMessage().contains("rowKey='" + rowKeyValue2)); } return; } fail(); } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient newTableClient = tableClientBuilder.buildClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, newTableClient.createEntityWithResponse(entity, null, null).getStatusCode()); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier), null, null) .getStatusCode()); TableAccessPolicies tableAccessPolicies = tableClient.getAccessPolicies(); assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); final int expectedStatusCode = 204; assertEquals(expectedStatusCode, tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers, null, null).getStatusCode()); TableAccessPolicies tableAccessPolicies = tableClient.getAccessPolicies(); assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } } }
Though I can't help but wonder why these tests fail for Cosmos and not for Storage, since we use the same logic to generate both SAS tokens and we don't really need to do anything special for Cosmos.
public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); }
Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints.");
public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } } @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } } @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
Either way, is this something that we can handle inside Tables SDK to map it to a common exception type for both Storage and Cosmos? It would be odd for users to get `TableTransactionFailedException` and `TableServiceException` for the same transaction depending on the source service.
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } }
}
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
I think there is something I can do as a workaround in the meantime to return the same type of exception, but I would prefer to wait and see if this is a service bug.
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } }
}
void submitTransactionAsyncWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "SAS Tokens are not supported for Cosmos endpoints."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
class TableAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = System.getenv("AZURE_TABLES_CONNECTION_STRING") != null && System.getenv("AZURE_TABLES_CONNECTION_STRING").contains("cosmos.azure.com"); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; private TableClientBuilder getClientBuilder(String tableName, String connectionString) { final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } return builder; } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test void deleteTableAsync() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteNonExistingTableAsync() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteNonExistingTableWithResponseAsync() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteNonExistingEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteNonExistingEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer) { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } /*@Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test void submitTransactionAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void submitTransactionAsyncAllActions() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValueCreate = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName("rowKey", 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName("rowKey", 20); String rowKeyValueDelete = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test void submitTransactionAsyncWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test @Test void submitTransactionAsyncWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
Why are we replacing the extra character d at the end ?
private String generateQueryParameter(@NonNull String subject) { return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_"); }
return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_");
private String generateQueryParameter(@NonNull String subject) { return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_"); }
class AbstractQueryGenerator { protected AbstractQueryGenerator() { } private String generateUnaryQuery(@NonNull Criteria criteria) { Assert.isTrue(criteria.getSubjectValues().isEmpty(), "Unary criteria should have no one subject value"); Assert.isTrue(CriteriaType.isUnary(criteria.getType()), "Criteria type should be unary operation"); final String subject = criteria.getSubject(); if (CriteriaType.isFunction(criteria.getType())) { return String.format("%s(r.%s)", criteria.getType().getSqlKeyword(), subject); } else { return String.format("r.%s %s", subject, criteria.getType().getSqlKeyword()); } } private String generateBinaryQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Binary criteria should have only one subject value"); Assert.isTrue(CriteriaType.isBinary(criteria.getType()), "Criteria type should be binary operation"); final String subject = criteria.getSubject(); final Object subjectValue = toCosmosDbValue(criteria.getSubjectValues().get(0)); final String parameter = generateQueryParameter(subject); final Part.IgnoreCaseType ignoreCase = criteria.getIgnoreCase(); final String sqlKeyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter, subjectValue)); if (CriteriaType.isFunction(criteria.getType())) { return getFunctionCondition(ignoreCase, sqlKeyword, subject, parameter); } else { return getCondition(ignoreCase, sqlKeyword, subject, parameter); } } /** * Get condition string with function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("r.%s %s @%s", subject, sqlKeyword, parameter); } else { return String.format("UPPER(r.%s) %s UPPER(@%s)", subject, sqlKeyword, parameter); } } /** * Get condition string without function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getFunctionCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("%s(r.%s, @%s)", sqlKeyword, subject, parameter); } else { return String.format("%s(UPPER(r.%s), UPPER(@%s))", sqlKeyword, subject, parameter); } } private String generateBetween(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final String subject = criteria.getSubject(); final Object value1 = toCosmosDbValue(criteria.getSubjectValues().get(0)); final Object value2 = toCosmosDbValue(criteria.getSubjectValues().get(1)); final String subject1 = subject + "start"; final String subject2 = subject + "end"; final String parameter1 = generateQueryParameter(subject1); final String parameter2 = generateQueryParameter(subject2); final String keyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter1, value1)); parameters.add(Pair.of(parameter2, value2)); return String.format("(r.%s %s @%s AND @%s)", subject, keyword, parameter1, parameter2); } private String generateClosedQuery(@NonNull String left, @NonNull String right, CriteriaType type) { Assert.isTrue(CriteriaType.isClosed(type) && CriteriaType.isBinary(type), "Criteria type should be binary and closure operation"); return String.join(" ", left, type.getSqlKeyword(), right); } @SuppressWarnings("unchecked") private String generateInQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Criteria should have only one subject value"); if (!(criteria.getSubjectValues().get(0) instanceof Collection)) { throw new IllegalQueryException("IN keyword requires Collection type in parameters"); } final Collection<Object> values = (Collection<Object>) criteria.getSubjectValues().get(0); final List<String> paras = new ArrayList<>(); for (Object o : values) { if (o instanceof String || o instanceof Integer || o instanceof Long || o instanceof Boolean) { String key = "p" + parameters.size(); paras.add("@" + key); parameters.add(Pair.of(key, o)); } else { throw new IllegalQueryException("IN keyword Range only support Number and String type."); } } return String.format("r.%s %s (%s)", criteria.getSubject(), criteria.getType().getSqlKeyword(), String.join(",", paras)); } private String generateQueryBody(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final CriteriaType type = criteria.getType(); switch (type) { case ALL: return ""; case IN: case NOT_IN: return generateInQuery(criteria, parameters); case BETWEEN: return generateBetween(criteria, parameters); case IS_NULL: case IS_NOT_NULL: case FALSE: case TRUE: return generateUnaryQuery(criteria); case IS_EQUAL: case NOT: case BEFORE: case AFTER: case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: case CONTAINING: case ENDS_WITH: case STARTS_WITH: case ARRAY_CONTAINS: return generateBinaryQuery(criteria, parameters); case AND: case OR: Assert.isTrue(criteria.getSubCriteria().size() == 2, "criteria should have two SubCriteria"); final String left = generateQueryBody(criteria.getSubCriteria().get(0), parameters); final String right = generateQueryBody(criteria.getSubCriteria().get(1), parameters); return generateClosedQuery(left, right, type); default: throw new UnsupportedOperationException("unsupported Criteria type: " + type); } } /** * Generate a query body for interface QuerySpecGenerator. The query body compose of Sql query String and its' * parameters. The parameters organized as a list of Pair, for each pair compose parameter name and value. * * @param query the representation for query method. * @return A pair tuple compose of Sql query. */ @NonNull private Pair<String, List<Pair<String, Object>>> generateQueryBody(@NonNull CosmosQuery query) { final List<Pair<String, Object>> parameters = new ArrayList<>(); String queryString = this.generateQueryBody(query.getCriteria(), parameters); if (StringUtils.hasText(queryString)) { queryString = String.join(" ", "WHERE", queryString); } return Pair.of(queryString, parameters); } private static String getParameter(@NonNull Sort.Order order) { Assert.isTrue(!order.isIgnoreCase(), "Ignore case is not supported"); final String direction = order.isDescending() ? "DESC" : "ASC"; return String.format("r.%s %s", order.getProperty(), direction); } static String generateQuerySort(@NonNull Sort sort) { if (sort.isUnsorted()) { return ""; } final String queryTail = "ORDER BY"; final List<String> subjects = sort.stream().map(AbstractQueryGenerator::getParameter).collect(Collectors.toList()); return queryTail + " " + String.join(",", subjects); } @NonNull private String generateQueryTail(@NonNull CosmosQuery query) { final List<String> queryTails = new ArrayList<>(); queryTails.add(generateQuerySort(query.getSort())); return String.join(" ", queryTails.stream().filter(StringUtils::hasText).collect(Collectors.toList())); } protected SqlQuerySpec generateCosmosQuery(@NonNull CosmosQuery query, @NonNull String queryHead) { final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); String queryString = String.join(" ", queryHead, queryBody.getFirst(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getSecond(); List<SqlParameter> sqlParameters = parameters.stream() .map(p -> new SqlParameter("@" + p.getFirst(), toCosmosDbValue(p.getSecond()))) .collect(Collectors.toList()); if (query.getLimit() > 0) { queryString = new StringBuilder(queryString) .append(" OFFSET 0 LIMIT ") .append(query.getLimit()).toString(); } return new SqlQuerySpec(queryString, sqlParameters); } }
class AbstractQueryGenerator { protected AbstractQueryGenerator() { } private String generateUnaryQuery(@NonNull Criteria criteria) { Assert.isTrue(criteria.getSubjectValues().isEmpty(), "Unary criteria should have no one subject value"); Assert.isTrue(CriteriaType.isUnary(criteria.getType()), "Criteria type should be unary operation"); final String subject = criteria.getSubject(); if (CriteriaType.isFunction(criteria.getType())) { return String.format("%s(r.%s)", criteria.getType().getSqlKeyword(), subject); } else { return String.format("r.%s %s", subject, criteria.getType().getSqlKeyword()); } } private String generateBinaryQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Binary criteria should have only one subject value"); Assert.isTrue(CriteriaType.isBinary(criteria.getType()), "Criteria type should be binary operation"); final String subject = criteria.getSubject(); final Object subjectValue = toCosmosDbValue(criteria.getSubjectValues().get(0)); final String parameter = generateQueryParameter(subject); final Part.IgnoreCaseType ignoreCase = criteria.getIgnoreCase(); final String sqlKeyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter, subjectValue)); if (CriteriaType.isFunction(criteria.getType())) { return getFunctionCondition(ignoreCase, sqlKeyword, subject, parameter); } else { return getCondition(ignoreCase, sqlKeyword, subject, parameter); } } /** * Get condition string with function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("r.%s %s @%s", subject, sqlKeyword, parameter); } else { return String.format("UPPER(r.%s) %s UPPER(@%s)", subject, sqlKeyword, parameter); } } /** * Get condition string without function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getFunctionCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("%s(r.%s, @%s)", sqlKeyword, subject, parameter); } else { return String.format("%s(UPPER(r.%s), UPPER(@%s))", sqlKeyword, subject, parameter); } } private String generateBetween(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final String subject = criteria.getSubject(); final Object value1 = toCosmosDbValue(criteria.getSubjectValues().get(0)); final Object value2 = toCosmosDbValue(criteria.getSubjectValues().get(1)); final String subject1 = subject + "start"; final String subject2 = subject + "end"; final String parameter1 = generateQueryParameter(subject1); final String parameter2 = generateQueryParameter(subject2); final String keyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter1, value1)); parameters.add(Pair.of(parameter2, value2)); return String.format("(r.%s %s @%s AND @%s)", subject, keyword, parameter1, parameter2); } private String generateClosedQuery(@NonNull String left, @NonNull String right, CriteriaType type) { Assert.isTrue(CriteriaType.isClosed(type) && CriteriaType.isBinary(type), "Criteria type should be binary and closure operation"); return String.join(" ", left, type.getSqlKeyword(), right); } @SuppressWarnings("unchecked") private String generateInQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Criteria should have only one subject value"); if (!(criteria.getSubjectValues().get(0) instanceof Collection)) { throw new IllegalQueryException("IN keyword requires Collection type in parameters"); } final Collection<Object> values = (Collection<Object>) criteria.getSubjectValues().get(0); final List<String> paras = new ArrayList<>(); for (Object o : values) { if (o instanceof String || o instanceof Integer || o instanceof Long || o instanceof Boolean) { String key = "p" + parameters.size(); paras.add("@" + key); parameters.add(Pair.of(key, o)); } else { throw new IllegalQueryException("IN keyword Range only support Number and String type."); } } return String.format("r.%s %s (%s)", criteria.getSubject(), criteria.getType().getSqlKeyword(), String.join(",", paras)); } private String generateQueryBody(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final CriteriaType type = criteria.getType(); switch (type) { case ALL: return ""; case IN: case NOT_IN: return generateInQuery(criteria, parameters); case BETWEEN: return generateBetween(criteria, parameters); case IS_NULL: case IS_NOT_NULL: case FALSE: case TRUE: return generateUnaryQuery(criteria); case IS_EQUAL: case NOT: case BEFORE: case AFTER: case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: case CONTAINING: case ENDS_WITH: case STARTS_WITH: case ARRAY_CONTAINS: return generateBinaryQuery(criteria, parameters); case AND: case OR: Assert.isTrue(criteria.getSubCriteria().size() == 2, "criteria should have two SubCriteria"); final String left = generateQueryBody(criteria.getSubCriteria().get(0), parameters); final String right = generateQueryBody(criteria.getSubCriteria().get(1), parameters); return generateClosedQuery(left, right, type); default: throw new UnsupportedOperationException("unsupported Criteria type: " + type); } } /** * Generate a query body for interface QuerySpecGenerator. The query body compose of Sql query String and its' * parameters. The parameters organized as a list of Pair, for each pair compose parameter name and value. * * @param query the representation for query method. * @return A pair tuple compose of Sql query. */ @NonNull private Pair<String, List<Pair<String, Object>>> generateQueryBody(@NonNull CosmosQuery query) { final List<Pair<String, Object>> parameters = new ArrayList<>(); String queryString = this.generateQueryBody(query.getCriteria(), parameters); if (StringUtils.hasText(queryString)) { queryString = String.join(" ", "WHERE", queryString); } return Pair.of(queryString, parameters); } private static String getParameter(@NonNull Sort.Order order) { Assert.isTrue(!order.isIgnoreCase(), "Ignore case is not supported"); final String direction = order.isDescending() ? "DESC" : "ASC"; return String.format("r.%s %s", order.getProperty(), direction); } static String generateQuerySort(@NonNull Sort sort) { if (sort.isUnsorted()) { return ""; } final String queryTail = "ORDER BY"; final List<String> subjects = sort.stream().map(AbstractQueryGenerator::getParameter).collect(Collectors.toList()); return queryTail + " " + String.join(",", subjects); } @NonNull private String generateQueryTail(@NonNull CosmosQuery query) { final List<String> queryTails = new ArrayList<>(); queryTails.add(generateQuerySort(query.getSort())); return String.join(" ", queryTails.stream().filter(StringUtils::hasText).collect(Collectors.toList())); } protected SqlQuerySpec generateCosmosQuery(@NonNull CosmosQuery query, @NonNull String queryHead) { final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); String queryString = String.join(" ", queryHead, queryBody.getFirst(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getSecond(); List<SqlParameter> sqlParameters = parameters.stream() .map(p -> new SqlParameter("@" + p.getFirst(), toCosmosDbValue(p.getSecond()))) .collect(Collectors.toList()); if (query.getLimit() > 0) { queryString = new StringBuilder(queryString) .append(" OFFSET 0 LIMIT ") .append(query.getLimit()).toString(); } return new SqlQuerySpec(queryString, sqlParameters); } }
@kushagraThapar actually this results to `\d` only because of the way the Java compiler works (the compiler will replace `\\` with `\`), so after the compiler substitutes the two backslashes with a single one,`\d` would be interpreted by the regex engine as any digit (0-9). This renders the whole expression as anything that's not in the class of characters `a-z`, `A-Z` or `0-9`. So any non-alphanumeric character will be converted to a `_`.
private String generateQueryParameter(@NonNull String subject) { return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_"); }
return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_");
private String generateQueryParameter(@NonNull String subject) { return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_"); }
class AbstractQueryGenerator { protected AbstractQueryGenerator() { } private String generateUnaryQuery(@NonNull Criteria criteria) { Assert.isTrue(criteria.getSubjectValues().isEmpty(), "Unary criteria should have no one subject value"); Assert.isTrue(CriteriaType.isUnary(criteria.getType()), "Criteria type should be unary operation"); final String subject = criteria.getSubject(); if (CriteriaType.isFunction(criteria.getType())) { return String.format("%s(r.%s)", criteria.getType().getSqlKeyword(), subject); } else { return String.format("r.%s %s", subject, criteria.getType().getSqlKeyword()); } } private String generateBinaryQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Binary criteria should have only one subject value"); Assert.isTrue(CriteriaType.isBinary(criteria.getType()), "Criteria type should be binary operation"); final String subject = criteria.getSubject(); final Object subjectValue = toCosmosDbValue(criteria.getSubjectValues().get(0)); final String parameter = generateQueryParameter(subject); final Part.IgnoreCaseType ignoreCase = criteria.getIgnoreCase(); final String sqlKeyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter, subjectValue)); if (CriteriaType.isFunction(criteria.getType())) { return getFunctionCondition(ignoreCase, sqlKeyword, subject, parameter); } else { return getCondition(ignoreCase, sqlKeyword, subject, parameter); } } /** * Get condition string with function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("r.%s %s @%s", subject, sqlKeyword, parameter); } else { return String.format("UPPER(r.%s) %s UPPER(@%s)", subject, sqlKeyword, parameter); } } /** * Get condition string without function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getFunctionCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("%s(r.%s, @%s)", sqlKeyword, subject, parameter); } else { return String.format("%s(UPPER(r.%s), UPPER(@%s))", sqlKeyword, subject, parameter); } } private String generateBetween(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final String subject = criteria.getSubject(); final Object value1 = toCosmosDbValue(criteria.getSubjectValues().get(0)); final Object value2 = toCosmosDbValue(criteria.getSubjectValues().get(1)); final String subject1 = subject + "start"; final String subject2 = subject + "end"; final String parameter1 = generateQueryParameter(subject1); final String parameter2 = generateQueryParameter(subject2); final String keyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter1, value1)); parameters.add(Pair.of(parameter2, value2)); return String.format("(r.%s %s @%s AND @%s)", subject, keyword, parameter1, parameter2); } private String generateClosedQuery(@NonNull String left, @NonNull String right, CriteriaType type) { Assert.isTrue(CriteriaType.isClosed(type) && CriteriaType.isBinary(type), "Criteria type should be binary and closure operation"); return String.join(" ", left, type.getSqlKeyword(), right); } @SuppressWarnings("unchecked") private String generateInQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Criteria should have only one subject value"); if (!(criteria.getSubjectValues().get(0) instanceof Collection)) { throw new IllegalQueryException("IN keyword requires Collection type in parameters"); } final Collection<Object> values = (Collection<Object>) criteria.getSubjectValues().get(0); final List<String> paras = new ArrayList<>(); for (Object o : values) { if (o instanceof String || o instanceof Integer || o instanceof Long || o instanceof Boolean) { String key = "p" + parameters.size(); paras.add("@" + key); parameters.add(Pair.of(key, o)); } else { throw new IllegalQueryException("IN keyword Range only support Number and String type."); } } return String.format("r.%s %s (%s)", criteria.getSubject(), criteria.getType().getSqlKeyword(), String.join(",", paras)); } private String generateQueryBody(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final CriteriaType type = criteria.getType(); switch (type) { case ALL: return ""; case IN: case NOT_IN: return generateInQuery(criteria, parameters); case BETWEEN: return generateBetween(criteria, parameters); case IS_NULL: case IS_NOT_NULL: case FALSE: case TRUE: return generateUnaryQuery(criteria); case IS_EQUAL: case NOT: case BEFORE: case AFTER: case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: case CONTAINING: case ENDS_WITH: case STARTS_WITH: case ARRAY_CONTAINS: return generateBinaryQuery(criteria, parameters); case AND: case OR: Assert.isTrue(criteria.getSubCriteria().size() == 2, "criteria should have two SubCriteria"); final String left = generateQueryBody(criteria.getSubCriteria().get(0), parameters); final String right = generateQueryBody(criteria.getSubCriteria().get(1), parameters); return generateClosedQuery(left, right, type); default: throw new UnsupportedOperationException("unsupported Criteria type: " + type); } } /** * Generate a query body for interface QuerySpecGenerator. The query body compose of Sql query String and its' * parameters. The parameters organized as a list of Pair, for each pair compose parameter name and value. * * @param query the representation for query method. * @return A pair tuple compose of Sql query. */ @NonNull private Pair<String, List<Pair<String, Object>>> generateQueryBody(@NonNull CosmosQuery query) { final List<Pair<String, Object>> parameters = new ArrayList<>(); String queryString = this.generateQueryBody(query.getCriteria(), parameters); if (StringUtils.hasText(queryString)) { queryString = String.join(" ", "WHERE", queryString); } return Pair.of(queryString, parameters); } private static String getParameter(@NonNull Sort.Order order) { Assert.isTrue(!order.isIgnoreCase(), "Ignore case is not supported"); final String direction = order.isDescending() ? "DESC" : "ASC"; return String.format("r.%s %s", order.getProperty(), direction); } static String generateQuerySort(@NonNull Sort sort) { if (sort.isUnsorted()) { return ""; } final String queryTail = "ORDER BY"; final List<String> subjects = sort.stream().map(AbstractQueryGenerator::getParameter).collect(Collectors.toList()); return queryTail + " " + String.join(",", subjects); } @NonNull private String generateQueryTail(@NonNull CosmosQuery query) { final List<String> queryTails = new ArrayList<>(); queryTails.add(generateQuerySort(query.getSort())); return String.join(" ", queryTails.stream().filter(StringUtils::hasText).collect(Collectors.toList())); } protected SqlQuerySpec generateCosmosQuery(@NonNull CosmosQuery query, @NonNull String queryHead) { final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); String queryString = String.join(" ", queryHead, queryBody.getFirst(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getSecond(); List<SqlParameter> sqlParameters = parameters.stream() .map(p -> new SqlParameter("@" + p.getFirst(), toCosmosDbValue(p.getSecond()))) .collect(Collectors.toList()); if (query.getLimit() > 0) { queryString = new StringBuilder(queryString) .append(" OFFSET 0 LIMIT ") .append(query.getLimit()).toString(); } return new SqlQuerySpec(queryString, sqlParameters); } }
class AbstractQueryGenerator { protected AbstractQueryGenerator() { } private String generateUnaryQuery(@NonNull Criteria criteria) { Assert.isTrue(criteria.getSubjectValues().isEmpty(), "Unary criteria should have no one subject value"); Assert.isTrue(CriteriaType.isUnary(criteria.getType()), "Criteria type should be unary operation"); final String subject = criteria.getSubject(); if (CriteriaType.isFunction(criteria.getType())) { return String.format("%s(r.%s)", criteria.getType().getSqlKeyword(), subject); } else { return String.format("r.%s %s", subject, criteria.getType().getSqlKeyword()); } } private String generateBinaryQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Binary criteria should have only one subject value"); Assert.isTrue(CriteriaType.isBinary(criteria.getType()), "Criteria type should be binary operation"); final String subject = criteria.getSubject(); final Object subjectValue = toCosmosDbValue(criteria.getSubjectValues().get(0)); final String parameter = generateQueryParameter(subject); final Part.IgnoreCaseType ignoreCase = criteria.getIgnoreCase(); final String sqlKeyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter, subjectValue)); if (CriteriaType.isFunction(criteria.getType())) { return getFunctionCondition(ignoreCase, sqlKeyword, subject, parameter); } else { return getCondition(ignoreCase, sqlKeyword, subject, parameter); } } /** * Get condition string with function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("r.%s %s @%s", subject, sqlKeyword, parameter); } else { return String.format("UPPER(r.%s) %s UPPER(@%s)", subject, sqlKeyword, parameter); } } /** * Get condition string without function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getFunctionCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("%s(r.%s, @%s)", sqlKeyword, subject, parameter); } else { return String.format("%s(UPPER(r.%s), UPPER(@%s))", sqlKeyword, subject, parameter); } } private String generateBetween(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final String subject = criteria.getSubject(); final Object value1 = toCosmosDbValue(criteria.getSubjectValues().get(0)); final Object value2 = toCosmosDbValue(criteria.getSubjectValues().get(1)); final String subject1 = subject + "start"; final String subject2 = subject + "end"; final String parameter1 = generateQueryParameter(subject1); final String parameter2 = generateQueryParameter(subject2); final String keyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter1, value1)); parameters.add(Pair.of(parameter2, value2)); return String.format("(r.%s %s @%s AND @%s)", subject, keyword, parameter1, parameter2); } private String generateClosedQuery(@NonNull String left, @NonNull String right, CriteriaType type) { Assert.isTrue(CriteriaType.isClosed(type) && CriteriaType.isBinary(type), "Criteria type should be binary and closure operation"); return String.join(" ", left, type.getSqlKeyword(), right); } @SuppressWarnings("unchecked") private String generateInQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Criteria should have only one subject value"); if (!(criteria.getSubjectValues().get(0) instanceof Collection)) { throw new IllegalQueryException("IN keyword requires Collection type in parameters"); } final Collection<Object> values = (Collection<Object>) criteria.getSubjectValues().get(0); final List<String> paras = new ArrayList<>(); for (Object o : values) { if (o instanceof String || o instanceof Integer || o instanceof Long || o instanceof Boolean) { String key = "p" + parameters.size(); paras.add("@" + key); parameters.add(Pair.of(key, o)); } else { throw new IllegalQueryException("IN keyword Range only support Number and String type."); } } return String.format("r.%s %s (%s)", criteria.getSubject(), criteria.getType().getSqlKeyword(), String.join(",", paras)); } private String generateQueryBody(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final CriteriaType type = criteria.getType(); switch (type) { case ALL: return ""; case IN: case NOT_IN: return generateInQuery(criteria, parameters); case BETWEEN: return generateBetween(criteria, parameters); case IS_NULL: case IS_NOT_NULL: case FALSE: case TRUE: return generateUnaryQuery(criteria); case IS_EQUAL: case NOT: case BEFORE: case AFTER: case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: case CONTAINING: case ENDS_WITH: case STARTS_WITH: case ARRAY_CONTAINS: return generateBinaryQuery(criteria, parameters); case AND: case OR: Assert.isTrue(criteria.getSubCriteria().size() == 2, "criteria should have two SubCriteria"); final String left = generateQueryBody(criteria.getSubCriteria().get(0), parameters); final String right = generateQueryBody(criteria.getSubCriteria().get(1), parameters); return generateClosedQuery(left, right, type); default: throw new UnsupportedOperationException("unsupported Criteria type: " + type); } } /** * Generate a query body for interface QuerySpecGenerator. The query body compose of Sql query String and its' * parameters. The parameters organized as a list of Pair, for each pair compose parameter name and value. * * @param query the representation for query method. * @return A pair tuple compose of Sql query. */ @NonNull private Pair<String, List<Pair<String, Object>>> generateQueryBody(@NonNull CosmosQuery query) { final List<Pair<String, Object>> parameters = new ArrayList<>(); String queryString = this.generateQueryBody(query.getCriteria(), parameters); if (StringUtils.hasText(queryString)) { queryString = String.join(" ", "WHERE", queryString); } return Pair.of(queryString, parameters); } private static String getParameter(@NonNull Sort.Order order) { Assert.isTrue(!order.isIgnoreCase(), "Ignore case is not supported"); final String direction = order.isDescending() ? "DESC" : "ASC"; return String.format("r.%s %s", order.getProperty(), direction); } static String generateQuerySort(@NonNull Sort sort) { if (sort.isUnsorted()) { return ""; } final String queryTail = "ORDER BY"; final List<String> subjects = sort.stream().map(AbstractQueryGenerator::getParameter).collect(Collectors.toList()); return queryTail + " " + String.join(",", subjects); } @NonNull private String generateQueryTail(@NonNull CosmosQuery query) { final List<String> queryTails = new ArrayList<>(); queryTails.add(generateQuerySort(query.getSort())); return String.join(" ", queryTails.stream().filter(StringUtils::hasText).collect(Collectors.toList())); } protected SqlQuerySpec generateCosmosQuery(@NonNull CosmosQuery query, @NonNull String queryHead) { final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); String queryString = String.join(" ", queryHead, queryBody.getFirst(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getSecond(); List<SqlParameter> sqlParameters = parameters.stream() .map(p -> new SqlParameter("@" + p.getFirst(), toCosmosDbValue(p.getSecond()))) .collect(Collectors.toList()); if (query.getLimit() > 0) { queryString = new StringBuilder(queryString) .append(" OFFSET 0 LIMIT ") .append(query.getLimit()).toString(); } return new SqlQuerySpec(queryString, sqlParameters); } }
@gogopavl Thanks for the explanation.
private String generateQueryParameter(@NonNull String subject) { return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_"); }
return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_");
private String generateQueryParameter(@NonNull String subject) { return subject.replaceAll("[^a-zA-Z\\d]", "_") + UUID.randomUUID().toString().replaceAll("-", "_"); }
class AbstractQueryGenerator { protected AbstractQueryGenerator() { } private String generateUnaryQuery(@NonNull Criteria criteria) { Assert.isTrue(criteria.getSubjectValues().isEmpty(), "Unary criteria should have no one subject value"); Assert.isTrue(CriteriaType.isUnary(criteria.getType()), "Criteria type should be unary operation"); final String subject = criteria.getSubject(); if (CriteriaType.isFunction(criteria.getType())) { return String.format("%s(r.%s)", criteria.getType().getSqlKeyword(), subject); } else { return String.format("r.%s %s", subject, criteria.getType().getSqlKeyword()); } } private String generateBinaryQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Binary criteria should have only one subject value"); Assert.isTrue(CriteriaType.isBinary(criteria.getType()), "Criteria type should be binary operation"); final String subject = criteria.getSubject(); final Object subjectValue = toCosmosDbValue(criteria.getSubjectValues().get(0)); final String parameter = generateQueryParameter(subject); final Part.IgnoreCaseType ignoreCase = criteria.getIgnoreCase(); final String sqlKeyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter, subjectValue)); if (CriteriaType.isFunction(criteria.getType())) { return getFunctionCondition(ignoreCase, sqlKeyword, subject, parameter); } else { return getCondition(ignoreCase, sqlKeyword, subject, parameter); } } /** * Get condition string with function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("r.%s %s @%s", subject, sqlKeyword, parameter); } else { return String.format("UPPER(r.%s) %s UPPER(@%s)", subject, sqlKeyword, parameter); } } /** * Get condition string without function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getFunctionCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("%s(r.%s, @%s)", sqlKeyword, subject, parameter); } else { return String.format("%s(UPPER(r.%s), UPPER(@%s))", sqlKeyword, subject, parameter); } } private String generateBetween(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final String subject = criteria.getSubject(); final Object value1 = toCosmosDbValue(criteria.getSubjectValues().get(0)); final Object value2 = toCosmosDbValue(criteria.getSubjectValues().get(1)); final String subject1 = subject + "start"; final String subject2 = subject + "end"; final String parameter1 = generateQueryParameter(subject1); final String parameter2 = generateQueryParameter(subject2); final String keyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter1, value1)); parameters.add(Pair.of(parameter2, value2)); return String.format("(r.%s %s @%s AND @%s)", subject, keyword, parameter1, parameter2); } private String generateClosedQuery(@NonNull String left, @NonNull String right, CriteriaType type) { Assert.isTrue(CriteriaType.isClosed(type) && CriteriaType.isBinary(type), "Criteria type should be binary and closure operation"); return String.join(" ", left, type.getSqlKeyword(), right); } @SuppressWarnings("unchecked") private String generateInQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Criteria should have only one subject value"); if (!(criteria.getSubjectValues().get(0) instanceof Collection)) { throw new IllegalQueryException("IN keyword requires Collection type in parameters"); } final Collection<Object> values = (Collection<Object>) criteria.getSubjectValues().get(0); final List<String> paras = new ArrayList<>(); for (Object o : values) { if (o instanceof String || o instanceof Integer || o instanceof Long || o instanceof Boolean) { String key = "p" + parameters.size(); paras.add("@" + key); parameters.add(Pair.of(key, o)); } else { throw new IllegalQueryException("IN keyword Range only support Number and String type."); } } return String.format("r.%s %s (%s)", criteria.getSubject(), criteria.getType().getSqlKeyword(), String.join(",", paras)); } private String generateQueryBody(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final CriteriaType type = criteria.getType(); switch (type) { case ALL: return ""; case IN: case NOT_IN: return generateInQuery(criteria, parameters); case BETWEEN: return generateBetween(criteria, parameters); case IS_NULL: case IS_NOT_NULL: case FALSE: case TRUE: return generateUnaryQuery(criteria); case IS_EQUAL: case NOT: case BEFORE: case AFTER: case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: case CONTAINING: case ENDS_WITH: case STARTS_WITH: case ARRAY_CONTAINS: return generateBinaryQuery(criteria, parameters); case AND: case OR: Assert.isTrue(criteria.getSubCriteria().size() == 2, "criteria should have two SubCriteria"); final String left = generateQueryBody(criteria.getSubCriteria().get(0), parameters); final String right = generateQueryBody(criteria.getSubCriteria().get(1), parameters); return generateClosedQuery(left, right, type); default: throw new UnsupportedOperationException("unsupported Criteria type: " + type); } } /** * Generate a query body for interface QuerySpecGenerator. The query body compose of Sql query String and its' * parameters. The parameters organized as a list of Pair, for each pair compose parameter name and value. * * @param query the representation for query method. * @return A pair tuple compose of Sql query. */ @NonNull private Pair<String, List<Pair<String, Object>>> generateQueryBody(@NonNull CosmosQuery query) { final List<Pair<String, Object>> parameters = new ArrayList<>(); String queryString = this.generateQueryBody(query.getCriteria(), parameters); if (StringUtils.hasText(queryString)) { queryString = String.join(" ", "WHERE", queryString); } return Pair.of(queryString, parameters); } private static String getParameter(@NonNull Sort.Order order) { Assert.isTrue(!order.isIgnoreCase(), "Ignore case is not supported"); final String direction = order.isDescending() ? "DESC" : "ASC"; return String.format("r.%s %s", order.getProperty(), direction); } static String generateQuerySort(@NonNull Sort sort) { if (sort.isUnsorted()) { return ""; } final String queryTail = "ORDER BY"; final List<String> subjects = sort.stream().map(AbstractQueryGenerator::getParameter).collect(Collectors.toList()); return queryTail + " " + String.join(",", subjects); } @NonNull private String generateQueryTail(@NonNull CosmosQuery query) { final List<String> queryTails = new ArrayList<>(); queryTails.add(generateQuerySort(query.getSort())); return String.join(" ", queryTails.stream().filter(StringUtils::hasText).collect(Collectors.toList())); } protected SqlQuerySpec generateCosmosQuery(@NonNull CosmosQuery query, @NonNull String queryHead) { final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); String queryString = String.join(" ", queryHead, queryBody.getFirst(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getSecond(); List<SqlParameter> sqlParameters = parameters.stream() .map(p -> new SqlParameter("@" + p.getFirst(), toCosmosDbValue(p.getSecond()))) .collect(Collectors.toList()); if (query.getLimit() > 0) { queryString = new StringBuilder(queryString) .append(" OFFSET 0 LIMIT ") .append(query.getLimit()).toString(); } return new SqlQuerySpec(queryString, sqlParameters); } }
class AbstractQueryGenerator { protected AbstractQueryGenerator() { } private String generateUnaryQuery(@NonNull Criteria criteria) { Assert.isTrue(criteria.getSubjectValues().isEmpty(), "Unary criteria should have no one subject value"); Assert.isTrue(CriteriaType.isUnary(criteria.getType()), "Criteria type should be unary operation"); final String subject = criteria.getSubject(); if (CriteriaType.isFunction(criteria.getType())) { return String.format("%s(r.%s)", criteria.getType().getSqlKeyword(), subject); } else { return String.format("r.%s %s", subject, criteria.getType().getSqlKeyword()); } } private String generateBinaryQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Binary criteria should have only one subject value"); Assert.isTrue(CriteriaType.isBinary(criteria.getType()), "Criteria type should be binary operation"); final String subject = criteria.getSubject(); final Object subjectValue = toCosmosDbValue(criteria.getSubjectValues().get(0)); final String parameter = generateQueryParameter(subject); final Part.IgnoreCaseType ignoreCase = criteria.getIgnoreCase(); final String sqlKeyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter, subjectValue)); if (CriteriaType.isFunction(criteria.getType())) { return getFunctionCondition(ignoreCase, sqlKeyword, subject, parameter); } else { return getCondition(ignoreCase, sqlKeyword, subject, parameter); } } /** * Get condition string with function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("r.%s %s @%s", subject, sqlKeyword, parameter); } else { return String.format("UPPER(r.%s) %s UPPER(@%s)", subject, sqlKeyword, parameter); } } /** * Get condition string without function * * @param ignoreCase ignore case flag * @param sqlKeyword sql key word, operation name * @param subject sql column name * @param parameter sql filter value * @return condition string */ private String getFunctionCondition(final Part.IgnoreCaseType ignoreCase, final String sqlKeyword, final String subject, final String parameter) { if (Part.IgnoreCaseType.NEVER == ignoreCase) { return String.format("%s(r.%s, @%s)", sqlKeyword, subject, parameter); } else { return String.format("%s(UPPER(r.%s), UPPER(@%s))", sqlKeyword, subject, parameter); } } private String generateBetween(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final String subject = criteria.getSubject(); final Object value1 = toCosmosDbValue(criteria.getSubjectValues().get(0)); final Object value2 = toCosmosDbValue(criteria.getSubjectValues().get(1)); final String subject1 = subject + "start"; final String subject2 = subject + "end"; final String parameter1 = generateQueryParameter(subject1); final String parameter2 = generateQueryParameter(subject2); final String keyword = criteria.getType().getSqlKeyword(); parameters.add(Pair.of(parameter1, value1)); parameters.add(Pair.of(parameter2, value2)); return String.format("(r.%s %s @%s AND @%s)", subject, keyword, parameter1, parameter2); } private String generateClosedQuery(@NonNull String left, @NonNull String right, CriteriaType type) { Assert.isTrue(CriteriaType.isClosed(type) && CriteriaType.isBinary(type), "Criteria type should be binary and closure operation"); return String.join(" ", left, type.getSqlKeyword(), right); } @SuppressWarnings("unchecked") private String generateInQuery(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { Assert.isTrue(criteria.getSubjectValues().size() == 1, "Criteria should have only one subject value"); if (!(criteria.getSubjectValues().get(0) instanceof Collection)) { throw new IllegalQueryException("IN keyword requires Collection type in parameters"); } final Collection<Object> values = (Collection<Object>) criteria.getSubjectValues().get(0); final List<String> paras = new ArrayList<>(); for (Object o : values) { if (o instanceof String || o instanceof Integer || o instanceof Long || o instanceof Boolean) { String key = "p" + parameters.size(); paras.add("@" + key); parameters.add(Pair.of(key, o)); } else { throw new IllegalQueryException("IN keyword Range only support Number and String type."); } } return String.format("r.%s %s (%s)", criteria.getSubject(), criteria.getType().getSqlKeyword(), String.join(",", paras)); } private String generateQueryBody(@NonNull Criteria criteria, @NonNull List<Pair<String, Object>> parameters) { final CriteriaType type = criteria.getType(); switch (type) { case ALL: return ""; case IN: case NOT_IN: return generateInQuery(criteria, parameters); case BETWEEN: return generateBetween(criteria, parameters); case IS_NULL: case IS_NOT_NULL: case FALSE: case TRUE: return generateUnaryQuery(criteria); case IS_EQUAL: case NOT: case BEFORE: case AFTER: case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: case CONTAINING: case ENDS_WITH: case STARTS_WITH: case ARRAY_CONTAINS: return generateBinaryQuery(criteria, parameters); case AND: case OR: Assert.isTrue(criteria.getSubCriteria().size() == 2, "criteria should have two SubCriteria"); final String left = generateQueryBody(criteria.getSubCriteria().get(0), parameters); final String right = generateQueryBody(criteria.getSubCriteria().get(1), parameters); return generateClosedQuery(left, right, type); default: throw new UnsupportedOperationException("unsupported Criteria type: " + type); } } /** * Generate a query body for interface QuerySpecGenerator. The query body compose of Sql query String and its' * parameters. The parameters organized as a list of Pair, for each pair compose parameter name and value. * * @param query the representation for query method. * @return A pair tuple compose of Sql query. */ @NonNull private Pair<String, List<Pair<String, Object>>> generateQueryBody(@NonNull CosmosQuery query) { final List<Pair<String, Object>> parameters = new ArrayList<>(); String queryString = this.generateQueryBody(query.getCriteria(), parameters); if (StringUtils.hasText(queryString)) { queryString = String.join(" ", "WHERE", queryString); } return Pair.of(queryString, parameters); } private static String getParameter(@NonNull Sort.Order order) { Assert.isTrue(!order.isIgnoreCase(), "Ignore case is not supported"); final String direction = order.isDescending() ? "DESC" : "ASC"; return String.format("r.%s %s", order.getProperty(), direction); } static String generateQuerySort(@NonNull Sort sort) { if (sort.isUnsorted()) { return ""; } final String queryTail = "ORDER BY"; final List<String> subjects = sort.stream().map(AbstractQueryGenerator::getParameter).collect(Collectors.toList()); return queryTail + " " + String.join(",", subjects); } @NonNull private String generateQueryTail(@NonNull CosmosQuery query) { final List<String> queryTails = new ArrayList<>(); queryTails.add(generateQuerySort(query.getSort())); return String.join(" ", queryTails.stream().filter(StringUtils::hasText).collect(Collectors.toList())); } protected SqlQuerySpec generateCosmosQuery(@NonNull CosmosQuery query, @NonNull String queryHead) { final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); String queryString = String.join(" ", queryHead, queryBody.getFirst(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getSecond(); List<SqlParameter> sqlParameters = parameters.stream() .map(p -> new SqlParameter("@" + p.getFirst(), toCosmosDbValue(p.getSecond()))) .collect(Collectors.toList()); if (query.getLimit() > 0) { queryString = new StringBuilder(queryString) .append(" OFFSET 0 LIMIT ") .append(query.getLimit()).toString(); } return new SqlQuerySpec(queryString, sqlParameters); } }
when the service updates the model version, this test might fail on the confidence scores :/
static ExtractSummaryResult getExpectedExtractSummaryResultSortByOffset() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final ExtractSummaryResult extractSummaryResult = new ExtractSummaryResult("0", textDocumentStatistics, null); final IterableStream<SummarySentence> summarySentences = IterableStream.of(asList( getExpectedSummarySentence( "At Microsoft, we have been on a quest to advance AI beyond existing" + " techniques, by taking a more holistic, human-centric approach to learning and understanding.", 1.0, 0, 160), getExpectedSummarySentence( "In my role, I enjoy a unique perspective in viewing the relationship among three attributes of human" + " cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z).", 0.958, 324, 192), getExpectedSummarySentence( "At the intersection of all three, there’s magic—what we call XYZ-code as illustrated in Figure" + " 1—a joint representation to create more powerful AI that can speak, hear, see, and understand" + " humans better.", 0.929, 517, 203) )); SummarySentenceCollection sentences = new SummarySentenceCollection(summarySentences, null); ExtractSummaryResultPropertiesHelper.setSentences(extractSummaryResult, sentences); return extractSummaryResult; }
0.929, 517, 203)
static ExtractSummaryResult getExpectedExtractSummaryResultSortByOffset() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final ExtractSummaryResult extractSummaryResult = new ExtractSummaryResult("0", textDocumentStatistics, null); final IterableStream<SummarySentence> summarySentences = IterableStream.of(asList( getExpectedSummarySentence( "At Microsoft, we have been on a quest to advance AI beyond existing" + " techniques, by taking a more holistic, human-centric approach to learning and understanding.", 1.0, 0, 160), getExpectedSummarySentence( "In my role, I enjoy a unique perspective in viewing the relationship among three attributes of human" + " cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z).", 0.958, 324, 192), getExpectedSummarySentence( "At the intersection of all three, there’s magic—what we call XYZ-code as illustrated in Figure" + " 1—a joint representation to create more powerful AI that can speak, hear, see, and understand" + " humans better.", 0.929, 517, 203) )); SummarySentenceCollection sentences = new SummarySentenceCollection(summarySentences, null); ExtractSummaryResultPropertiesHelper.setSentences(extractSummaryResult, sentences); return extractSummaryResult; }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final OffsetDateTime TIME_NOW = OffsetDateTime.now(); static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SUMMARY_INPUTS = asList( "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic," + " human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI " + "Cognitive Services, I have been working with a team of amazing scientists and engineers to turn this" + " quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship among " + "three attributes of human cognition: monolingual text (X), audio or visual sensory signals, (Y) and" + " multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code as" + " illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear, see," + " and understand humans better. We believe XYZ-code will enable us to fulfill our long-term vision:" + " cross-domain transfer learning, spanning modalities and languages. The goal is to have pretrained" + " models that can jointly learn representations to support a broad range of downstream AI tasks, much" + " in the way humans do today. Over the past five years, we have achieved human performance on benchmarks" + " in conversational speech recognition, machine translation, conversational question answering, machine" + " reading comprehension, and image captioning. These five breakthroughs provided us with strong signals" + " toward our more ambitious aspiration to produce a leap in AI capabilities, achieving multisensory and" + " multilingual learning that is closer in line with how humans learn and understand. I believe the joint" + " XYZ-code is a foundational component of this aspiration, if grounded with external knowledge sources" + " in the downstream AI tasks." ); static final List<String> SENTIMENT_INPUTS = asList( "The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was unclean."; static final String HEALTHCARE_ENTITY_OFFSET_INPUT = "The patient is a 54-year-old"; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity2, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity3, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 10); return asList(categorizedEntity1); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 0); CategorizedEntity categorizedEntity2 = new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity2, 10); CategorizedEntity categorizedEntity3 = new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity3, 28); CategorizedEntity categorizedEntity4 = new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity4, 32); CategorizedEntity categorizedEntity5 = new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity5, 35); CategorizedEntity categorizedEntity6 = new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity6, 61); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3, categorizedEntity4, categorizedEntity5, categorizedEntity6); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(getPiiEntitiesList1ForDomainFilter()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, "Microsoft"); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.ORGANIZATION); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, null); PiiEntityPropertiesHelper.setOffset(piiEntity0, 0); final PiiEntity piiEntity1 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity1, "employee"); PiiEntityPropertiesHelper.setCategory(piiEntity1, PiiEntityCategory.fromString("PersonType")); PiiEntityPropertiesHelper.setSubcategory(piiEntity1, null); PiiEntityPropertiesHelper.setOffset(piiEntity1, 10); final PiiEntity piiEntity2 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity2, "859-98-0987"); PiiEntityPropertiesHelper.setCategory(piiEntity2, PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity2, null); PiiEntityPropertiesHelper.setOffset(piiEntity2, 28); return asList(piiEntity0, piiEntity1, piiEntity2); } static List<PiiEntity> getPiiEntitiesList1ForDomainFilter() { return Arrays.asList(getPiiEntitiesList1().get(0), getPiiEntitiesList1().get(2)); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { String expectedText = "111000025"; final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.PHONE_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity0, 0.8); PiiEntityPropertiesHelper.setOffset(piiEntity0, 18); final PiiEntity piiEntity1 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity1, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity1, PiiEntityCategory.ABA_ROUTING_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity1, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity1, 0.75); PiiEntityPropertiesHelper.setOffset(piiEntity1, 18); final PiiEntity piiEntity2 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity2, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity2, PiiEntityCategory.NZ_SOCIAL_WELFARE_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity2, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity2, 0.65); PiiEntityPropertiesHelper.setOffset(piiEntity2, 18); return asList(piiEntity0, piiEntity1, piiEntity2); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for categories filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForCategoriesFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(asList(getPiiEntitiesList1().get(2))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(asList(getPiiEntitiesList2().get(1))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", null, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", null, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } static List<LinkedEntity> getLinkedEntitiesList3() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 0); LinkedEntityMatch linkedEntityMatch1 = new LinkedEntityMatch("API's", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch1, 61); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); LinkedEntity linkedEntity1 = new LinkedEntity( "Application programming interface", new IterableStream<>(Collections.singletonList(linkedEntityMatch1)), "en", "Application programming interface", "https: "Wikipedia"); return asList(linkedEntity, linkedEntity1); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("Hello world", "input text")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(asList("Bonjour", "monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static ExtractSummaryResultCollection getExpectedExtractSummaryResultCollection( ExtractSummaryResult extractSummaryResult) { final ExtractSummaryResultCollection expectResultCollection = new ExtractSummaryResultCollection( asList(extractSummaryResult), null, null); return expectResultCollection; } static SummarySentence getExpectedSummarySentence(String text, double rankScore, int offset, int length) { final SummarySentence summarySentence = new SummarySentence(); SummarySentencePropertiesHelper.setText(summarySentence, text); SummarySentencePropertiesHelper.setRankScore(summarySentence, rankScore); SummarySentencePropertiesHelper.setOffset(summarySentence, offset); SummarySentencePropertiesHelper.setLength(summarySentence, length); return summarySentence; } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { final AssessmentSentiment assessmentSentiment1 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment1, "dark"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment1, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment1, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment1, 14); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment1, 0); final AssessmentSentiment assessmentSentiment2 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment2, "unclean"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment2, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment2, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment2, 23); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment2, 0); final AssessmentSentiment assessmentSentiment3 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment3, "amazing"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment3, TextSentiment.POSITIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment3, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment3, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment3, 51); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment3, 0); final TargetSentiment targetSentiment1 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment1, "hotel"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment1, TextSentiment.NEGATIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment1, 4); final SentenceOpinion sentenceOpinion1 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion1, targetSentiment1); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion1, new IterableStream<>(asList(assessmentSentiment1, assessmentSentiment2))); final TargetSentiment targetSentiment2 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment2, "gnocchi"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment2, TextSentiment.POSITIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment2, 59); final SentenceOpinion sentenceOpinion2 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion2, targetSentiment2); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion2, new IterableStream<>(asList(assessmentSentiment3))); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, new IterableStream<>(asList(sentenceOpinion1))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 31); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment( "The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment2, new IterableStream<>(asList(sentenceOpinion2))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 32); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 35); return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { final AssessmentSentiment assessmentSentiment1 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment1, "dark"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment1, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment1, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment1, 50); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment1, 0); final AssessmentSentiment assessmentSentiment2 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment2, "unclean"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment2, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment2, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment2, 59); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment2, 0); final AssessmentSentiment assessmentSentiment3 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment3, "amazing"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment3, TextSentiment.POSITIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment3, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment3, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment3, 19); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment3, 0); final TargetSentiment targetSentiment1 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment1, "gnocchi"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment1, TextSentiment.POSITIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment1, 27); final SentenceOpinion sentenceOpinion1 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion1, targetSentiment1); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion1, new IterableStream<>(asList(assessmentSentiment3))); final TargetSentiment targetSentiment2 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment2, "hotel"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment2, TextSentiment.NEGATIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment2, 40); final SentenceOpinion sentenceOpinion2 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion2, targetSentiment2); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion2, new IterableStream<>(asList(assessmentSentiment1, assessmentSentiment2))); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, new IterableStream<>(asList(sentenceOpinion1))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 35); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment( "The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment2, new IterableStream<>(asList(sentenceOpinion2))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 36); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 31); return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); } /* * This is the expected result for testing an input: * "I had a wonderful trip to Seattle last week." */ static DocumentSentiment getExpectedDocumentSentimentForActions() { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "I had a wonderful trip to Seattle last week.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, null); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 44); return new DocumentSentiment(TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1)), null); } /* * This is the expected result for testing an input: * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static DocumentSentiment getExpectedDocumentSentimentForActions2() { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, null); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 67); return new DocumentSentiment(TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1)), null); } /** * Helper method that get a single-page {@link AnalyzeHealthcareEntitiesResultCollection} list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage() { return asList( getExpectedAnalyzeHealthcareEntitiesResultCollection(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages {@link AnalyzeHealthcareEntitiesResultCollection} list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedAnalyzeHealthcareEntitiesResultCollectionListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<AnalyzeHealthcareEntitiesResultCollection> result = new ArrayList<>(); result.add(getExpectedAnalyzeHealthcareEntitiesResultCollection(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedAnalyzeHealthcareEntitiesResultCollection(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected {@link AnalyzeHealthcareEntitiesResultCollection} result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedAnalyzeHealthcareEntitiesResultCollection( int sizePerPage, List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final AnalyzeHealthcareEntitiesResultCollection analyzeHealthcareEntitiesResultCollection = new AnalyzeHealthcareEntitiesResultCollection(IterableStream.of(healthcareEntitiesResults)); AnalyzeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(analyzeHealthcareEntitiesResultCollection, "2020-09-03"); AnalyzeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(analyzeHealthcareEntitiesResultCollection, textDocumentBatchStatistics); return analyzeHealthcareEntitiesResultCollection; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, HealthcareEntityCategory.AGE); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setLength(healthcareEntity1, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity1, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity2, "Male population group"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, HealthcareEntityCategory.GENDER); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setLength(healthcareEntity2, 9); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.fromString("Course")); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setLength(healthcareEntity3, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity3, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity4, "Angina Pectoris"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setLength(healthcareEntity4, 6); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, HealthcareEntityCategory.TIME); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setLength(healthcareEntity5, 19); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity5, IterableStream.of(Collections.emptyList())); final AnalyzeHealthcareEntitiesResult healthcareEntitiesResult1 = new AnalyzeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role1 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role1, "Course"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role1, healthcareEntity3); final HealthcareEntityRelationRole role2 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role2, "Condition"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role2, healthcareEntity4); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, HealthcareEntityRelationType.fromString("CourseOfCondition")); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation1, IterableStream.of(asList(role1, role2))); final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role3 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role3, "Time"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role3, healthcareEntity5); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, HealthcareEntityRelationType.TIME_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation2, IterableStream.of(asList(role2, role3))); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(healthcareEntitiesResult1, IterableStream.of(asList(healthcareEntityRelation1, healthcareEntityRelation2))); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "six minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, HealthcareEntityCategory.TIME); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 21); HealthcareEntityPropertiesHelper.setLength(healthcareEntity1, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity1, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, HealthcareEntityCategory.CONDITION_QUALIFIER); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setLength(healthcareEntity2, 7); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity3, "ST segment depression (finding)"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setLength(healthcareEntity3, 14); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity3, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "anterior lateral"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, HealthcareEntityCategory.DIRECTION); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.6); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 68); HealthcareEntityPropertiesHelper.setLength(healthcareEntity4, 16); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "fatigue"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity5, "Fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 108); HealthcareEntityPropertiesHelper.setLength(healthcareEntity5, 7); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity5, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "wrist pain"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity6, "Pain in wrist"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 120); HealthcareEntityPropertiesHelper.setLength(healthcareEntity6, 10); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity6, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity7 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity7, "anginal equivalent"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity7, "Anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity7, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity7, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity7, 137); HealthcareEntityPropertiesHelper.setLength(healthcareEntity7, 18); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity7, IterableStream.of(Collections.emptyList())); final AnalyzeHealthcareEntitiesResult healthcareEntitiesResult = new AnalyzeHealthcareEntitiesResult("1", textDocumentStatistics, null); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6, healthcareEntity7))); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role1 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role1, "Time"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role1, healthcareEntity1); final HealthcareEntityRelationRole role2 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role2, "Condition"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role2, healthcareEntity3); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, HealthcareEntityRelationType.TIME_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation1, IterableStream.of(asList(role1, role2))); final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role3 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role3, "Qualifier"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role3, healthcareEntity2); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, HealthcareEntityRelationType.QUALIFIER_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation2, IterableStream.of(asList(role3, role2))); final HealthcareEntityRelation healthcareEntityRelation3 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role4 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role4, "Direction"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role4, healthcareEntity4); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation3, HealthcareEntityRelationType.DIRECTION_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation3, IterableStream.of(asList(role2, role4))); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(healthcareEntitiesResult, IterableStream.of(asList(healthcareEntityRelation1, healthcareEntityRelation2, healthcareEntityRelation3))); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", new TextDocumentStatistics(67, 1), null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, "last week"); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.fromString("DateTime")); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, "DateRange"); PiiEntityPropertiesHelper.setOffset(piiEntity0, 34); return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new PiiEntityCollection(new IterableStream<>(Arrays.asList(piiEntity0)), "I had a wonderful trip to Seattle *********.", null)), new RecognizePiiEntitiesResult("1", new TextDocumentStatistics(67, 1), null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); } /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", new TextDocumentStatistics(44, 1), null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle")), null)), new ExtractKeyPhraseResult("1", new TextDocumentStatistics(67, 1), null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome", "API")), null))), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollection() { return new RecognizeLinkedEntitiesResultCollection( asList(new RecognizeLinkedEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult("1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)) ), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollectionForActions() { return new RecognizeLinkedEntitiesResultCollection( asList(new RecognizeLinkedEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult("1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList3()), null)) ), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static AnalyzeSentimentResultCollection getAnalyzeSentimentResultCollectionForActions() { final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", null, null, getExpectedDocumentSentimentForActions()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", null, null, getExpectedDocumentSentimentForActions2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static AnalyzeSentimentActionResult getExpectedAnalyzeSentimentActionResult(boolean isError, OffsetDateTime completeAt, AnalyzeSentimentResultCollection resultCollection, TextAnalyticsError actionError) { AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static ExtractSummaryActionResult getExtractSummaryActionResult(boolean isError, OffsetDateTime completeAt, ExtractSummaryResultCollection resultCollection, TextAnalyticsError actionError) { ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } /** * Helper method that get the expected AnalyzeBatchActionsResult result. */ static AnalyzeActionsResult getExpectedAnalyzeBatchActionsResult( IterableStream<RecognizeEntitiesActionResult> recognizeEntitiesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults, IterableStream<ExtractSummaryActionResult> extractSummaryActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, analyzeSentimentActionResults); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, extractSummaryActionResults); return analyzeActionsResult; } /** * CategorizedEntityCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * RecognizePiiEntitiesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome", "API")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * RecognizeLinkedEntitiesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollectionForPagination( int startIndex, int documentCount) { List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeLinkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(Integer.toString(i), null, null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList3()), null))); } return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResults, "", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * AnalyzeSentimentResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static AnalyzeSentimentResultCollection getAnalyzeSentimentResultCollectionForPagination( int startIndex, int documentCount) { List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { analyzeSentimentResults.add(new AnalyzeSentimentResult(Integer.toString(i), null, null, getExpectedDocumentSentimentForActions2())); } return new AnalyzeSentimentResultCollection(analyzeSentimentResults, "", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * Helper method that get a multiple-pages (AnalyzeActionsResult) list. */ static List<AnalyzeActionsResult> getExpectedAnalyzeActionsResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeActionsResult> analyzeActionsResults = new ArrayList<>(); analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult( false, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult( false, TIME_NOW, getAnalyzeSentimentResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult( false, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult( false, TIME_NOW, getAnalyzeSentimentResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(Collections.emptyList()) )); return analyzeActionsResults; } /** * Helper method that get a customized TextAnalyticsError. */ static TextAnalyticsError getActionError(TextAnalyticsErrorCode errorCode, String taskName, String index) { return new TextAnalyticsError(errorCode, "", " } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(TextAnalyticsServiceVersion.values()).filter( TestUtils::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link TextAnalyticsServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) { return true; } String[] configuredServiceVersionList = serviceVersionFromEnv.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } private TestUtils() { } }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final OffsetDateTime TIME_NOW = OffsetDateTime.now(); static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SUMMARY_INPUTS = asList( "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic," + " human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI " + "Cognitive Services, I have been working with a team of amazing scientists and engineers to turn this" + " quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship among " + "three attributes of human cognition: monolingual text (X), audio or visual sensory signals, (Y) and" + " multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code as" + " illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear, see," + " and understand humans better. We believe XYZ-code will enable us to fulfill our long-term vision:" + " cross-domain transfer learning, spanning modalities and languages. The goal is to have pretrained" + " models that can jointly learn representations to support a broad range of downstream AI tasks, much" + " in the way humans do today. Over the past five years, we have achieved human performance on benchmarks" + " in conversational speech recognition, machine translation, conversational question answering, machine" + " reading comprehension, and image captioning. These five breakthroughs provided us with strong signals" + " toward our more ambitious aspiration to produce a leap in AI capabilities, achieving multisensory and" + " multilingual learning that is closer in line with how humans learn and understand. I believe the joint" + " XYZ-code is a foundational component of this aspiration, if grounded with external knowledge sources" + " in the downstream AI tasks." ); static final List<String> SENTIMENT_INPUTS = asList( "The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was unclean."; static final String HEALTHCARE_ENTITY_OFFSET_INPUT = "The patient is a 54-year-old"; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity2, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity3, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 10); return asList(categorizedEntity1); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 0); CategorizedEntity categorizedEntity2 = new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity2, 10); CategorizedEntity categorizedEntity3 = new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity3, 28); CategorizedEntity categorizedEntity4 = new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity4, 32); CategorizedEntity categorizedEntity5 = new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity5, 35); CategorizedEntity categorizedEntity6 = new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity6, 61); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3, categorizedEntity4, categorizedEntity5, categorizedEntity6); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(getPiiEntitiesList1ForDomainFilter()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, "Microsoft"); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.ORGANIZATION); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, null); PiiEntityPropertiesHelper.setOffset(piiEntity0, 0); final PiiEntity piiEntity1 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity1, "employee"); PiiEntityPropertiesHelper.setCategory(piiEntity1, PiiEntityCategory.fromString("PersonType")); PiiEntityPropertiesHelper.setSubcategory(piiEntity1, null); PiiEntityPropertiesHelper.setOffset(piiEntity1, 10); final PiiEntity piiEntity2 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity2, "859-98-0987"); PiiEntityPropertiesHelper.setCategory(piiEntity2, PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity2, null); PiiEntityPropertiesHelper.setOffset(piiEntity2, 28); return asList(piiEntity0, piiEntity1, piiEntity2); } static List<PiiEntity> getPiiEntitiesList1ForDomainFilter() { return Arrays.asList(getPiiEntitiesList1().get(0), getPiiEntitiesList1().get(2)); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { String expectedText = "111000025"; final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.PHONE_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity0, 0.8); PiiEntityPropertiesHelper.setOffset(piiEntity0, 18); final PiiEntity piiEntity1 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity1, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity1, PiiEntityCategory.ABA_ROUTING_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity1, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity1, 0.75); PiiEntityPropertiesHelper.setOffset(piiEntity1, 18); final PiiEntity piiEntity2 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity2, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity2, PiiEntityCategory.NZ_SOCIAL_WELFARE_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity2, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity2, 0.65); PiiEntityPropertiesHelper.setOffset(piiEntity2, 18); return asList(piiEntity0, piiEntity1, piiEntity2); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for categories filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForCategoriesFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(asList(getPiiEntitiesList1().get(2))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(asList(getPiiEntitiesList2().get(1))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", null, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", null, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } static List<LinkedEntity> getLinkedEntitiesList3() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 0); LinkedEntityMatch linkedEntityMatch1 = new LinkedEntityMatch("API's", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch1, 61); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); LinkedEntity linkedEntity1 = new LinkedEntity( "Application programming interface", new IterableStream<>(Collections.singletonList(linkedEntityMatch1)), "en", "Application programming interface", "https: "Wikipedia"); return asList(linkedEntity, linkedEntity1); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("Hello world", "input text")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(asList("Bonjour", "monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static ExtractSummaryResultCollection getExpectedExtractSummaryResultCollection( ExtractSummaryResult extractSummaryResult) { final ExtractSummaryResultCollection expectResultCollection = new ExtractSummaryResultCollection( asList(extractSummaryResult), null, null); return expectResultCollection; } static SummarySentence getExpectedSummarySentence(String text, double rankScore, int offset, int length) { final SummarySentence summarySentence = new SummarySentence(); SummarySentencePropertiesHelper.setText(summarySentence, text); SummarySentencePropertiesHelper.setRankScore(summarySentence, rankScore); SummarySentencePropertiesHelper.setOffset(summarySentence, offset); SummarySentencePropertiesHelper.setLength(summarySentence, length); return summarySentence; } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { final AssessmentSentiment assessmentSentiment1 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment1, "dark"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment1, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment1, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment1, 14); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment1, 0); final AssessmentSentiment assessmentSentiment2 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment2, "unclean"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment2, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment2, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment2, 23); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment2, 0); final AssessmentSentiment assessmentSentiment3 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment3, "amazing"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment3, TextSentiment.POSITIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment3, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment3, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment3, 51); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment3, 0); final TargetSentiment targetSentiment1 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment1, "hotel"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment1, TextSentiment.NEGATIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment1, 4); final SentenceOpinion sentenceOpinion1 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion1, targetSentiment1); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion1, new IterableStream<>(asList(assessmentSentiment1, assessmentSentiment2))); final TargetSentiment targetSentiment2 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment2, "gnocchi"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment2, TextSentiment.POSITIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment2, 59); final SentenceOpinion sentenceOpinion2 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion2, targetSentiment2); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion2, new IterableStream<>(asList(assessmentSentiment3))); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, new IterableStream<>(asList(sentenceOpinion1))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 31); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment( "The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment2, new IterableStream<>(asList(sentenceOpinion2))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 32); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 35); return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { final AssessmentSentiment assessmentSentiment1 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment1, "dark"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment1, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment1, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment1, 50); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment1, 0); final AssessmentSentiment assessmentSentiment2 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment2, "unclean"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment2, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment2, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment2, 59); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment2, 0); final AssessmentSentiment assessmentSentiment3 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment3, "amazing"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment3, TextSentiment.POSITIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment3, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment3, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment3, 19); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment3, 0); final TargetSentiment targetSentiment1 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment1, "gnocchi"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment1, TextSentiment.POSITIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment1, 27); final SentenceOpinion sentenceOpinion1 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion1, targetSentiment1); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion1, new IterableStream<>(asList(assessmentSentiment3))); final TargetSentiment targetSentiment2 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment2, "hotel"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment2, TextSentiment.NEGATIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment2, 40); final SentenceOpinion sentenceOpinion2 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion2, targetSentiment2); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion2, new IterableStream<>(asList(assessmentSentiment1, assessmentSentiment2))); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, new IterableStream<>(asList(sentenceOpinion1))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 35); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment( "The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment2, new IterableStream<>(asList(sentenceOpinion2))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 36); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 31); return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); } /* * This is the expected result for testing an input: * "I had a wonderful trip to Seattle last week." */ static DocumentSentiment getExpectedDocumentSentimentForActions() { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "I had a wonderful trip to Seattle last week.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, null); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 44); return new DocumentSentiment(TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1)), null); } /* * This is the expected result for testing an input: * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static DocumentSentiment getExpectedDocumentSentimentForActions2() { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, null); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 67); return new DocumentSentiment(TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1)), null); } /** * Helper method that get a single-page {@link AnalyzeHealthcareEntitiesResultCollection} list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage() { return asList( getExpectedAnalyzeHealthcareEntitiesResultCollection(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages {@link AnalyzeHealthcareEntitiesResultCollection} list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedAnalyzeHealthcareEntitiesResultCollectionListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<AnalyzeHealthcareEntitiesResultCollection> result = new ArrayList<>(); result.add(getExpectedAnalyzeHealthcareEntitiesResultCollection(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedAnalyzeHealthcareEntitiesResultCollection(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected {@link AnalyzeHealthcareEntitiesResultCollection} result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedAnalyzeHealthcareEntitiesResultCollection( int sizePerPage, List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final AnalyzeHealthcareEntitiesResultCollection analyzeHealthcareEntitiesResultCollection = new AnalyzeHealthcareEntitiesResultCollection(IterableStream.of(healthcareEntitiesResults)); AnalyzeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(analyzeHealthcareEntitiesResultCollection, "2020-09-03"); AnalyzeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(analyzeHealthcareEntitiesResultCollection, textDocumentBatchStatistics); return analyzeHealthcareEntitiesResultCollection; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, HealthcareEntityCategory.AGE); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setLength(healthcareEntity1, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity1, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity2, "Male population group"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, HealthcareEntityCategory.GENDER); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setLength(healthcareEntity2, 9); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.fromString("Course")); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setLength(healthcareEntity3, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity3, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity4, "Angina Pectoris"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setLength(healthcareEntity4, 6); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, HealthcareEntityCategory.TIME); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setLength(healthcareEntity5, 19); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity5, IterableStream.of(Collections.emptyList())); final AnalyzeHealthcareEntitiesResult healthcareEntitiesResult1 = new AnalyzeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role1 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role1, "Course"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role1, healthcareEntity3); final HealthcareEntityRelationRole role2 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role2, "Condition"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role2, healthcareEntity4); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, HealthcareEntityRelationType.fromString("CourseOfCondition")); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation1, IterableStream.of(asList(role1, role2))); final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role3 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role3, "Time"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role3, healthcareEntity5); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, HealthcareEntityRelationType.TIME_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation2, IterableStream.of(asList(role2, role3))); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(healthcareEntitiesResult1, IterableStream.of(asList(healthcareEntityRelation1, healthcareEntityRelation2))); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "six minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, HealthcareEntityCategory.TIME); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 21); HealthcareEntityPropertiesHelper.setLength(healthcareEntity1, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity1, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, HealthcareEntityCategory.CONDITION_QUALIFIER); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setLength(healthcareEntity2, 7); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity3, "ST segment depression (finding)"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setLength(healthcareEntity3, 14); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity3, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "anterior lateral"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, HealthcareEntityCategory.DIRECTION); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.6); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 68); HealthcareEntityPropertiesHelper.setLength(healthcareEntity4, 16); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "fatigue"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity5, "Fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 108); HealthcareEntityPropertiesHelper.setLength(healthcareEntity5, 7); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity5, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "wrist pain"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity6, "Pain in wrist"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 120); HealthcareEntityPropertiesHelper.setLength(healthcareEntity6, 10); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity6, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity7 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity7, "anginal equivalent"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity7, "Anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity7, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity7, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity7, 137); HealthcareEntityPropertiesHelper.setLength(healthcareEntity7, 18); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity7, IterableStream.of(Collections.emptyList())); final AnalyzeHealthcareEntitiesResult healthcareEntitiesResult = new AnalyzeHealthcareEntitiesResult("1", textDocumentStatistics, null); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6, healthcareEntity7))); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role1 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role1, "Time"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role1, healthcareEntity1); final HealthcareEntityRelationRole role2 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role2, "Condition"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role2, healthcareEntity3); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, HealthcareEntityRelationType.TIME_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation1, IterableStream.of(asList(role1, role2))); final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role3 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role3, "Qualifier"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role3, healthcareEntity2); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, HealthcareEntityRelationType.QUALIFIER_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation2, IterableStream.of(asList(role3, role2))); final HealthcareEntityRelation healthcareEntityRelation3 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role4 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role4, "Direction"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role4, healthcareEntity4); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation3, HealthcareEntityRelationType.DIRECTION_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation3, IterableStream.of(asList(role2, role4))); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(healthcareEntitiesResult, IterableStream.of(asList(healthcareEntityRelation1, healthcareEntityRelation2, healthcareEntityRelation3))); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", new TextDocumentStatistics(67, 1), null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, "last week"); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.fromString("DateTime")); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, "DateRange"); PiiEntityPropertiesHelper.setOffset(piiEntity0, 34); return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new PiiEntityCollection(new IterableStream<>(Arrays.asList(piiEntity0)), "I had a wonderful trip to Seattle *********.", null)), new RecognizePiiEntitiesResult("1", new TextDocumentStatistics(67, 1), null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); } /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", new TextDocumentStatistics(44, 1), null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle")), null)), new ExtractKeyPhraseResult("1", new TextDocumentStatistics(67, 1), null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome", "API")), null))), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollection() { return new RecognizeLinkedEntitiesResultCollection( asList(new RecognizeLinkedEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult("1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)) ), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollectionForActions() { return new RecognizeLinkedEntitiesResultCollection( asList(new RecognizeLinkedEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult("1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList3()), null)) ), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static AnalyzeSentimentResultCollection getAnalyzeSentimentResultCollectionForActions() { final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", null, null, getExpectedDocumentSentimentForActions()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", null, null, getExpectedDocumentSentimentForActions2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static AnalyzeSentimentActionResult getExpectedAnalyzeSentimentActionResult(boolean isError, OffsetDateTime completeAt, AnalyzeSentimentResultCollection resultCollection, TextAnalyticsError actionError) { AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static ExtractSummaryActionResult getExtractSummaryActionResult(boolean isError, OffsetDateTime completeAt, ExtractSummaryResultCollection resultCollection, TextAnalyticsError actionError) { ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } /** * Helper method that get the expected AnalyzeBatchActionsResult result. */ static AnalyzeActionsResult getExpectedAnalyzeBatchActionsResult( IterableStream<RecognizeEntitiesActionResult> recognizeEntitiesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults, IterableStream<ExtractSummaryActionResult> extractSummaryActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, analyzeSentimentActionResults); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, extractSummaryActionResults); return analyzeActionsResult; } /** * CategorizedEntityCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * RecognizePiiEntitiesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome", "API")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * RecognizeLinkedEntitiesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollectionForPagination( int startIndex, int documentCount) { List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeLinkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(Integer.toString(i), null, null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList3()), null))); } return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResults, "", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * AnalyzeSentimentResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static AnalyzeSentimentResultCollection getAnalyzeSentimentResultCollectionForPagination( int startIndex, int documentCount) { List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { analyzeSentimentResults.add(new AnalyzeSentimentResult(Integer.toString(i), null, null, getExpectedDocumentSentimentForActions2())); } return new AnalyzeSentimentResultCollection(analyzeSentimentResults, "", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * Helper method that get a multiple-pages (AnalyzeActionsResult) list. */ static List<AnalyzeActionsResult> getExpectedAnalyzeActionsResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeActionsResult> analyzeActionsResults = new ArrayList<>(); analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult( false, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult( false, TIME_NOW, getAnalyzeSentimentResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult( false, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult( false, TIME_NOW, getAnalyzeSentimentResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(Collections.emptyList()) )); return analyzeActionsResults; } /** * Helper method that get a customized TextAnalyticsError. */ static TextAnalyticsError getActionError(TextAnalyticsErrorCode errorCode, String taskName, String index) { return new TextAnalyticsError(errorCode, "", " } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(TextAnalyticsServiceVersion.values()).filter( TestUtils::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link TextAnalyticsServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) { return true; } String[] configuredServiceVersionList = serviceVersionFromEnv.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } private TestUtils() { } }
That is right. The rank score here is for view but will not be used for verification.
static ExtractSummaryResult getExpectedExtractSummaryResultSortByOffset() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final ExtractSummaryResult extractSummaryResult = new ExtractSummaryResult("0", textDocumentStatistics, null); final IterableStream<SummarySentence> summarySentences = IterableStream.of(asList( getExpectedSummarySentence( "At Microsoft, we have been on a quest to advance AI beyond existing" + " techniques, by taking a more holistic, human-centric approach to learning and understanding.", 1.0, 0, 160), getExpectedSummarySentence( "In my role, I enjoy a unique perspective in viewing the relationship among three attributes of human" + " cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z).", 0.958, 324, 192), getExpectedSummarySentence( "At the intersection of all three, there’s magic—what we call XYZ-code as illustrated in Figure" + " 1—a joint representation to create more powerful AI that can speak, hear, see, and understand" + " humans better.", 0.929, 517, 203) )); SummarySentenceCollection sentences = new SummarySentenceCollection(summarySentences, null); ExtractSummaryResultPropertiesHelper.setSentences(extractSummaryResult, sentences); return extractSummaryResult; }
0.929, 517, 203)
static ExtractSummaryResult getExpectedExtractSummaryResultSortByOffset() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final ExtractSummaryResult extractSummaryResult = new ExtractSummaryResult("0", textDocumentStatistics, null); final IterableStream<SummarySentence> summarySentences = IterableStream.of(asList( getExpectedSummarySentence( "At Microsoft, we have been on a quest to advance AI beyond existing" + " techniques, by taking a more holistic, human-centric approach to learning and understanding.", 1.0, 0, 160), getExpectedSummarySentence( "In my role, I enjoy a unique perspective in viewing the relationship among three attributes of human" + " cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z).", 0.958, 324, 192), getExpectedSummarySentence( "At the intersection of all three, there’s magic—what we call XYZ-code as illustrated in Figure" + " 1—a joint representation to create more powerful AI that can speak, hear, see, and understand" + " humans better.", 0.929, 517, 203) )); SummarySentenceCollection sentences = new SummarySentenceCollection(summarySentences, null); ExtractSummaryResultPropertiesHelper.setSentences(extractSummaryResult, sentences); return extractSummaryResult; }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final OffsetDateTime TIME_NOW = OffsetDateTime.now(); static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SUMMARY_INPUTS = asList( "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic," + " human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI " + "Cognitive Services, I have been working with a team of amazing scientists and engineers to turn this" + " quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship among " + "three attributes of human cognition: monolingual text (X), audio or visual sensory signals, (Y) and" + " multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code as" + " illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear, see," + " and understand humans better. We believe XYZ-code will enable us to fulfill our long-term vision:" + " cross-domain transfer learning, spanning modalities and languages. The goal is to have pretrained" + " models that can jointly learn representations to support a broad range of downstream AI tasks, much" + " in the way humans do today. Over the past five years, we have achieved human performance on benchmarks" + " in conversational speech recognition, machine translation, conversational question answering, machine" + " reading comprehension, and image captioning. These five breakthroughs provided us with strong signals" + " toward our more ambitious aspiration to produce a leap in AI capabilities, achieving multisensory and" + " multilingual learning that is closer in line with how humans learn and understand. I believe the joint" + " XYZ-code is a foundational component of this aspiration, if grounded with external knowledge sources" + " in the downstream AI tasks." ); static final List<String> SENTIMENT_INPUTS = asList( "The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was unclean."; static final String HEALTHCARE_ENTITY_OFFSET_INPUT = "The patient is a 54-year-old"; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity2, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity3, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 10); return asList(categorizedEntity1); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 0); CategorizedEntity categorizedEntity2 = new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity2, 10); CategorizedEntity categorizedEntity3 = new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity3, 28); CategorizedEntity categorizedEntity4 = new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity4, 32); CategorizedEntity categorizedEntity5 = new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity5, 35); CategorizedEntity categorizedEntity6 = new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity6, 61); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3, categorizedEntity4, categorizedEntity5, categorizedEntity6); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(getPiiEntitiesList1ForDomainFilter()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, "Microsoft"); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.ORGANIZATION); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, null); PiiEntityPropertiesHelper.setOffset(piiEntity0, 0); final PiiEntity piiEntity1 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity1, "employee"); PiiEntityPropertiesHelper.setCategory(piiEntity1, PiiEntityCategory.fromString("PersonType")); PiiEntityPropertiesHelper.setSubcategory(piiEntity1, null); PiiEntityPropertiesHelper.setOffset(piiEntity1, 10); final PiiEntity piiEntity2 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity2, "859-98-0987"); PiiEntityPropertiesHelper.setCategory(piiEntity2, PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity2, null); PiiEntityPropertiesHelper.setOffset(piiEntity2, 28); return asList(piiEntity0, piiEntity1, piiEntity2); } static List<PiiEntity> getPiiEntitiesList1ForDomainFilter() { return Arrays.asList(getPiiEntitiesList1().get(0), getPiiEntitiesList1().get(2)); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { String expectedText = "111000025"; final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.PHONE_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity0, 0.8); PiiEntityPropertiesHelper.setOffset(piiEntity0, 18); final PiiEntity piiEntity1 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity1, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity1, PiiEntityCategory.ABA_ROUTING_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity1, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity1, 0.75); PiiEntityPropertiesHelper.setOffset(piiEntity1, 18); final PiiEntity piiEntity2 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity2, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity2, PiiEntityCategory.NZ_SOCIAL_WELFARE_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity2, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity2, 0.65); PiiEntityPropertiesHelper.setOffset(piiEntity2, 18); return asList(piiEntity0, piiEntity1, piiEntity2); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for categories filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForCategoriesFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(asList(getPiiEntitiesList1().get(2))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(asList(getPiiEntitiesList2().get(1))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", null, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", null, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } static List<LinkedEntity> getLinkedEntitiesList3() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 0); LinkedEntityMatch linkedEntityMatch1 = new LinkedEntityMatch("API's", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch1, 61); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); LinkedEntity linkedEntity1 = new LinkedEntity( "Application programming interface", new IterableStream<>(Collections.singletonList(linkedEntityMatch1)), "en", "Application programming interface", "https: "Wikipedia"); return asList(linkedEntity, linkedEntity1); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("Hello world", "input text")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(asList("Bonjour", "monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static ExtractSummaryResultCollection getExpectedExtractSummaryResultCollection( ExtractSummaryResult extractSummaryResult) { final ExtractSummaryResultCollection expectResultCollection = new ExtractSummaryResultCollection( asList(extractSummaryResult), null, null); return expectResultCollection; } static SummarySentence getExpectedSummarySentence(String text, double rankScore, int offset, int length) { final SummarySentence summarySentence = new SummarySentence(); SummarySentencePropertiesHelper.setText(summarySentence, text); SummarySentencePropertiesHelper.setRankScore(summarySentence, rankScore); SummarySentencePropertiesHelper.setOffset(summarySentence, offset); SummarySentencePropertiesHelper.setLength(summarySentence, length); return summarySentence; } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { final AssessmentSentiment assessmentSentiment1 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment1, "dark"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment1, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment1, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment1, 14); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment1, 0); final AssessmentSentiment assessmentSentiment2 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment2, "unclean"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment2, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment2, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment2, 23); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment2, 0); final AssessmentSentiment assessmentSentiment3 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment3, "amazing"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment3, TextSentiment.POSITIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment3, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment3, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment3, 51); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment3, 0); final TargetSentiment targetSentiment1 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment1, "hotel"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment1, TextSentiment.NEGATIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment1, 4); final SentenceOpinion sentenceOpinion1 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion1, targetSentiment1); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion1, new IterableStream<>(asList(assessmentSentiment1, assessmentSentiment2))); final TargetSentiment targetSentiment2 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment2, "gnocchi"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment2, TextSentiment.POSITIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment2, 59); final SentenceOpinion sentenceOpinion2 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion2, targetSentiment2); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion2, new IterableStream<>(asList(assessmentSentiment3))); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, new IterableStream<>(asList(sentenceOpinion1))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 31); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment( "The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment2, new IterableStream<>(asList(sentenceOpinion2))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 32); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 35); return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { final AssessmentSentiment assessmentSentiment1 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment1, "dark"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment1, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment1, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment1, 50); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment1, 0); final AssessmentSentiment assessmentSentiment2 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment2, "unclean"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment2, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment2, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment2, 59); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment2, 0); final AssessmentSentiment assessmentSentiment3 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment3, "amazing"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment3, TextSentiment.POSITIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment3, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment3, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment3, 19); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment3, 0); final TargetSentiment targetSentiment1 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment1, "gnocchi"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment1, TextSentiment.POSITIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment1, 27); final SentenceOpinion sentenceOpinion1 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion1, targetSentiment1); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion1, new IterableStream<>(asList(assessmentSentiment3))); final TargetSentiment targetSentiment2 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment2, "hotel"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment2, TextSentiment.NEGATIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment2, 40); final SentenceOpinion sentenceOpinion2 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion2, targetSentiment2); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion2, new IterableStream<>(asList(assessmentSentiment1, assessmentSentiment2))); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, new IterableStream<>(asList(sentenceOpinion1))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 35); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment( "The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment2, new IterableStream<>(asList(sentenceOpinion2))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 36); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 31); return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); } /* * This is the expected result for testing an input: * "I had a wonderful trip to Seattle last week." */ static DocumentSentiment getExpectedDocumentSentimentForActions() { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "I had a wonderful trip to Seattle last week.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, null); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 44); return new DocumentSentiment(TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1)), null); } /* * This is the expected result for testing an input: * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static DocumentSentiment getExpectedDocumentSentimentForActions2() { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, null); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 67); return new DocumentSentiment(TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1)), null); } /** * Helper method that get a single-page {@link AnalyzeHealthcareEntitiesResultCollection} list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage() { return asList( getExpectedAnalyzeHealthcareEntitiesResultCollection(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages {@link AnalyzeHealthcareEntitiesResultCollection} list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedAnalyzeHealthcareEntitiesResultCollectionListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<AnalyzeHealthcareEntitiesResultCollection> result = new ArrayList<>(); result.add(getExpectedAnalyzeHealthcareEntitiesResultCollection(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedAnalyzeHealthcareEntitiesResultCollection(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected {@link AnalyzeHealthcareEntitiesResultCollection} result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedAnalyzeHealthcareEntitiesResultCollection( int sizePerPage, List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final AnalyzeHealthcareEntitiesResultCollection analyzeHealthcareEntitiesResultCollection = new AnalyzeHealthcareEntitiesResultCollection(IterableStream.of(healthcareEntitiesResults)); AnalyzeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(analyzeHealthcareEntitiesResultCollection, "2020-09-03"); AnalyzeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(analyzeHealthcareEntitiesResultCollection, textDocumentBatchStatistics); return analyzeHealthcareEntitiesResultCollection; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, HealthcareEntityCategory.AGE); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setLength(healthcareEntity1, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity1, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity2, "Male population group"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, HealthcareEntityCategory.GENDER); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setLength(healthcareEntity2, 9); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.fromString("Course")); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setLength(healthcareEntity3, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity3, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity4, "Angina Pectoris"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setLength(healthcareEntity4, 6); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, HealthcareEntityCategory.TIME); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setLength(healthcareEntity5, 19); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity5, IterableStream.of(Collections.emptyList())); final AnalyzeHealthcareEntitiesResult healthcareEntitiesResult1 = new AnalyzeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role1 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role1, "Course"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role1, healthcareEntity3); final HealthcareEntityRelationRole role2 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role2, "Condition"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role2, healthcareEntity4); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, HealthcareEntityRelationType.fromString("CourseOfCondition")); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation1, IterableStream.of(asList(role1, role2))); final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role3 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role3, "Time"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role3, healthcareEntity5); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, HealthcareEntityRelationType.TIME_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation2, IterableStream.of(asList(role2, role3))); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(healthcareEntitiesResult1, IterableStream.of(asList(healthcareEntityRelation1, healthcareEntityRelation2))); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "six minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, HealthcareEntityCategory.TIME); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 21); HealthcareEntityPropertiesHelper.setLength(healthcareEntity1, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity1, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, HealthcareEntityCategory.CONDITION_QUALIFIER); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setLength(healthcareEntity2, 7); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity3, "ST segment depression (finding)"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setLength(healthcareEntity3, 14); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity3, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "anterior lateral"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, HealthcareEntityCategory.DIRECTION); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.6); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 68); HealthcareEntityPropertiesHelper.setLength(healthcareEntity4, 16); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "fatigue"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity5, "Fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 108); HealthcareEntityPropertiesHelper.setLength(healthcareEntity5, 7); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity5, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "wrist pain"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity6, "Pain in wrist"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 120); HealthcareEntityPropertiesHelper.setLength(healthcareEntity6, 10); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity6, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity7 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity7, "anginal equivalent"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity7, "Anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity7, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity7, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity7, 137); HealthcareEntityPropertiesHelper.setLength(healthcareEntity7, 18); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity7, IterableStream.of(Collections.emptyList())); final AnalyzeHealthcareEntitiesResult healthcareEntitiesResult = new AnalyzeHealthcareEntitiesResult("1", textDocumentStatistics, null); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6, healthcareEntity7))); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role1 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role1, "Time"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role1, healthcareEntity1); final HealthcareEntityRelationRole role2 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role2, "Condition"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role2, healthcareEntity3); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, HealthcareEntityRelationType.TIME_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation1, IterableStream.of(asList(role1, role2))); final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role3 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role3, "Qualifier"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role3, healthcareEntity2); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, HealthcareEntityRelationType.QUALIFIER_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation2, IterableStream.of(asList(role3, role2))); final HealthcareEntityRelation healthcareEntityRelation3 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role4 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role4, "Direction"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role4, healthcareEntity4); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation3, HealthcareEntityRelationType.DIRECTION_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation3, IterableStream.of(asList(role2, role4))); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(healthcareEntitiesResult, IterableStream.of(asList(healthcareEntityRelation1, healthcareEntityRelation2, healthcareEntityRelation3))); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", new TextDocumentStatistics(67, 1), null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, "last week"); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.fromString("DateTime")); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, "DateRange"); PiiEntityPropertiesHelper.setOffset(piiEntity0, 34); return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new PiiEntityCollection(new IterableStream<>(Arrays.asList(piiEntity0)), "I had a wonderful trip to Seattle *********.", null)), new RecognizePiiEntitiesResult("1", new TextDocumentStatistics(67, 1), null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); } /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", new TextDocumentStatistics(44, 1), null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle")), null)), new ExtractKeyPhraseResult("1", new TextDocumentStatistics(67, 1), null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome", "API")), null))), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollection() { return new RecognizeLinkedEntitiesResultCollection( asList(new RecognizeLinkedEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult("1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)) ), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollectionForActions() { return new RecognizeLinkedEntitiesResultCollection( asList(new RecognizeLinkedEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult("1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList3()), null)) ), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static AnalyzeSentimentResultCollection getAnalyzeSentimentResultCollectionForActions() { final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", null, null, getExpectedDocumentSentimentForActions()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", null, null, getExpectedDocumentSentimentForActions2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static AnalyzeSentimentActionResult getExpectedAnalyzeSentimentActionResult(boolean isError, OffsetDateTime completeAt, AnalyzeSentimentResultCollection resultCollection, TextAnalyticsError actionError) { AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static ExtractSummaryActionResult getExtractSummaryActionResult(boolean isError, OffsetDateTime completeAt, ExtractSummaryResultCollection resultCollection, TextAnalyticsError actionError) { ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } /** * Helper method that get the expected AnalyzeBatchActionsResult result. */ static AnalyzeActionsResult getExpectedAnalyzeBatchActionsResult( IterableStream<RecognizeEntitiesActionResult> recognizeEntitiesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults, IterableStream<ExtractSummaryActionResult> extractSummaryActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, analyzeSentimentActionResults); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, extractSummaryActionResults); return analyzeActionsResult; } /** * CategorizedEntityCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * RecognizePiiEntitiesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome", "API")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * RecognizeLinkedEntitiesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollectionForPagination( int startIndex, int documentCount) { List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeLinkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(Integer.toString(i), null, null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList3()), null))); } return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResults, "", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * AnalyzeSentimentResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static AnalyzeSentimentResultCollection getAnalyzeSentimentResultCollectionForPagination( int startIndex, int documentCount) { List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { analyzeSentimentResults.add(new AnalyzeSentimentResult(Integer.toString(i), null, null, getExpectedDocumentSentimentForActions2())); } return new AnalyzeSentimentResultCollection(analyzeSentimentResults, "", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * Helper method that get a multiple-pages (AnalyzeActionsResult) list. */ static List<AnalyzeActionsResult> getExpectedAnalyzeActionsResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeActionsResult> analyzeActionsResults = new ArrayList<>(); analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult( false, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult( false, TIME_NOW, getAnalyzeSentimentResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult( false, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult( false, TIME_NOW, getAnalyzeSentimentResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(Collections.emptyList()) )); return analyzeActionsResults; } /** * Helper method that get a customized TextAnalyticsError. */ static TextAnalyticsError getActionError(TextAnalyticsErrorCode errorCode, String taskName, String index) { return new TextAnalyticsError(errorCode, "", " } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(TextAnalyticsServiceVersion.values()).filter( TestUtils::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link TextAnalyticsServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) { return true; } String[] configuredServiceVersionList = serviceVersionFromEnv.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } private TestUtils() { } }
class TestUtils { private static final String DEFAULT_MODEL_VERSION = "2019-10-01"; static final OffsetDateTime TIME_NOW = OffsetDateTime.now(); static final String INVALID_URL = "htttttttps: static final String VALID_HTTPS_LOCALHOST = "https: static final String FAKE_API_KEY = "1234567890"; static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY"; static final List<String> SUMMARY_INPUTS = asList( "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic," + " human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI " + "Cognitive Services, I have been working with a team of amazing scientists and engineers to turn this" + " quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship among " + "three attributes of human cognition: monolingual text (X), audio or visual sensory signals, (Y) and" + " multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code as" + " illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear, see," + " and understand humans better. We believe XYZ-code will enable us to fulfill our long-term vision:" + " cross-domain transfer learning, spanning modalities and languages. The goal is to have pretrained" + " models that can jointly learn representations to support a broad range of downstream AI tasks, much" + " in the way humans do today. Over the past five years, we have achieved human performance on benchmarks" + " in conversational speech recognition, machine translation, conversational question answering, machine" + " reading comprehension, and image captioning. These five breakthroughs provided us with strong signals" + " toward our more ambitious aspiration to produce a leap in AI capabilities, achieving multisensory and" + " multilingual learning that is closer in line with how humans learn and understand. I believe the joint" + " XYZ-code is a foundational component of this aspiration, if grounded with external knowledge sources" + " in the downstream AI tasks." ); static final List<String> SENTIMENT_INPUTS = asList( "The hotel was dark and unclean. The restaurant had amazing gnocchi.", "The restaurant had amazing gnocchi. The hotel was dark and unclean."); static final List<String> CATEGORIZED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> PII_ENTITY_INPUTS = asList( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); static final List<String> LINKED_ENTITY_INPUTS = asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); static final List<String> KEY_PHRASE_INPUTS = asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!"; static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList( "Bonjour tout le monde.", "Je m'appelle Mondly."); static final List<String> DETECT_LANGUAGE_INPUTS = asList( "This is written in English", "Este es un documento escrito en Español.", "~@!~:)"); static final String PII_ENTITY_OFFSET_INPUT = "SSN: 859-98-0987"; static final String SENTIMENT_OFFSET_INPUT = "The hotel was unclean."; static final String HEALTHCARE_ENTITY_OFFSET_INPUT = "The patient is a 54-year-old"; static final List<String> HEALTHCARE_INPUTS = asList( "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent."); static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social"); static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null); static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null); static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH); static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList( DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH); static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null); static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS = "AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS"; static List<DetectLanguageInput> getDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"), new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US") ); } static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() { return asList( new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"), new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US") ); } static List<TextDocumentInput> getDuplicateTextDocumentInputs() { return asList( new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)), new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)) ); } static List<TextDocumentInput> getWarningsTextDocumentInputs() { return asList( new TextDocumentInput("0", TOO_LONG_INPUT), new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1)) ); } static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) { return IntStream.range(0, inputs.size()) .mapToObj(index -> new TextDocumentInput(String.valueOf(index), inputs.get(index))) .collect(Collectors.toList()); } /** * Helper method to get the expected Batch Detected Languages * * @return A {@link DetectLanguageResultCollection}. */ static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); final List<DetectLanguageResult> detectLanguageResultList = asList( new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()), new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()), new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage())); return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static DetectedLanguage getDetectedLanguageEnglish() { return new DetectedLanguage("English", "en", 0.0, null); } static DetectedLanguage getDetectedLanguageSpanish() { return new DetectedLanguage("Spanish", "es", 0.0, null); } static DetectedLanguage getUnknownDetectedLanguage() { return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null); } /** * Helper method to get the expected Batch Categorized Entities * * @return A {@link RecognizeEntitiesResultCollection}. */ static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() { return new RecognizeEntitiesResultCollection( asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<CategorizedEntity> getCategorizedEntitiesList1() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 18); CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity2, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity3, 34); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 10); return asList(categorizedEntity1); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { CategorizedEntity categorizedEntity1 = new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity1, 0); CategorizedEntity categorizedEntity2 = new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity2, 10); CategorizedEntity categorizedEntity3 = new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity3, 28); CategorizedEntity categorizedEntity4 = new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity4, 32); CategorizedEntity categorizedEntity5 = new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity5, 35); CategorizedEntity categorizedEntity6 = new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0); CategorizedEntityPropertiesHelper.setOffset(categorizedEntity6, 61); return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3, categorizedEntity4, categorizedEntity5, categorizedEntity6); } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() { IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1()); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null)); return recognizeEntitiesResult1; } /** * Helper method to get the expected Batch Categorized Entities */ static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() { IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2()); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null)); return recognizeEntitiesResult2; } /** * Helper method to get the expected batch of Personally Identifiable Information entities */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for domain filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForDomainFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(getPiiEntitiesList1ForDomainFilter()), "********* employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(Arrays.asList(getPiiEntitiesList2().get(0), getPiiEntitiesList2().get(1), getPiiEntitiesList2().get(2))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Categorized Entities List 1 */ static List<PiiEntity> getPiiEntitiesList1() { final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, "Microsoft"); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.ORGANIZATION); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, null); PiiEntityPropertiesHelper.setOffset(piiEntity0, 0); final PiiEntity piiEntity1 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity1, "employee"); PiiEntityPropertiesHelper.setCategory(piiEntity1, PiiEntityCategory.fromString("PersonType")); PiiEntityPropertiesHelper.setSubcategory(piiEntity1, null); PiiEntityPropertiesHelper.setOffset(piiEntity1, 10); final PiiEntity piiEntity2 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity2, "859-98-0987"); PiiEntityPropertiesHelper.setCategory(piiEntity2, PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity2, null); PiiEntityPropertiesHelper.setOffset(piiEntity2, 28); return asList(piiEntity0, piiEntity1, piiEntity2); } static List<PiiEntity> getPiiEntitiesList1ForDomainFilter() { return Arrays.asList(getPiiEntitiesList1().get(0), getPiiEntitiesList1().get(2)); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<PiiEntity> getPiiEntitiesList2() { String expectedText = "111000025"; final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.PHONE_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity0, 0.8); PiiEntityPropertiesHelper.setOffset(piiEntity0, 18); final PiiEntity piiEntity1 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity1, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity1, PiiEntityCategory.ABA_ROUTING_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity1, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity1, 0.75); PiiEntityPropertiesHelper.setOffset(piiEntity1, 18); final PiiEntity piiEntity2 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity2, expectedText); PiiEntityPropertiesHelper.setCategory(piiEntity2, PiiEntityCategory.NZ_SOCIAL_WELFARE_NUMBER); PiiEntityPropertiesHelper.setSubcategory(piiEntity2, null); PiiEntityPropertiesHelper.setConfidenceScore(piiEntity2, 0.65); PiiEntityPropertiesHelper.setOffset(piiEntity2, 18); return asList(piiEntity0, piiEntity1, piiEntity2); } /** * Helper method to get the expected batch of Personally Identifiable Information entities for categories filter */ static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntitiesForCategoriesFilter() { PiiEntityCollection piiEntityCollection = new PiiEntityCollection( new IterableStream<>(asList(getPiiEntitiesList1().get(2))), "Microsoft employee with ssn *********** is using our awesome API's.", null); PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection( new IterableStream<>(asList(getPiiEntitiesList2().get(1))), "Your ABA number - ********* - is the first 9 digits in the lower left hand corner of your personal check.", null); RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", null, null, piiEntityCollection); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", null, null, piiEntityCollection2); return new RecognizePiiEntitiesResultCollection( asList(recognizeEntitiesResult1, recognizeEntitiesResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method to get the expected Batch Linked Entities * @return A {@link RecognizeLinkedEntitiesResultCollection}. */ static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() { final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList = asList( new RecognizeLinkedEntitiesResult( "0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult( "1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null))); return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } /** * Helper method to get the expected linked Entities List 1 */ static List<LinkedEntity> getLinkedEntitiesList1() { final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "5fbba6b8-85e1-4d41-9444-d9055436e473"); return asList(linkedEntity); } /** * Helper method to get the expected linked Entities List 2 */ static List<LinkedEntity> getLinkedEntitiesList2() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } static List<LinkedEntity> getLinkedEntitiesList3() { LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch, 0); LinkedEntityMatch linkedEntityMatch1 = new LinkedEntityMatch("API's", 0.0); LinkedEntityMatchPropertiesHelper.setOffset(linkedEntityMatch1, 61); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia"); LinkedEntityPropertiesHelper.setBingEntitySearchApiId(linkedEntity, "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); LinkedEntity linkedEntity1 = new LinkedEntity( "Application programming interface", new IterableStream<>(Collections.singletonList(linkedEntityMatch1)), "en", "Application programming interface", "https: "Wikipedia"); return asList(linkedEntity, linkedEntity1); } /** * Helper method to get the expected Batch Key Phrases. */ static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("Hello world", "input text")), null)); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(asList("Bonjour", "monde")), null)); TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics); } static ExtractSummaryResultCollection getExpectedExtractSummaryResultCollection( ExtractSummaryResult extractSummaryResult) { final ExtractSummaryResultCollection expectResultCollection = new ExtractSummaryResultCollection( asList(extractSummaryResult), null, null); return expectResultCollection; } static SummarySentence getExpectedSummarySentence(String text, double rankScore, int offset, int length) { final SummarySentence summarySentence = new SummarySentence(); SummarySentencePropertiesHelper.setText(summarySentence, text); SummarySentencePropertiesHelper.setRankScore(summarySentence, rankScore); SummarySentencePropertiesHelper.setOffset(summarySentence, offset); SummarySentencePropertiesHelper.setLength(summarySentence, length); return summarySentence; } /** * Helper method to get the expected Batch Text Sentiments */ static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() { final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1); final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics, null, getExpectedDocumentSentiment()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics, null, getExpectedDocumentSentiment2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * Helper method that get the first expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment() { final AssessmentSentiment assessmentSentiment1 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment1, "dark"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment1, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment1, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment1, 14); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment1, 0); final AssessmentSentiment assessmentSentiment2 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment2, "unclean"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment2, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment2, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment2, 23); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment2, 0); final AssessmentSentiment assessmentSentiment3 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment3, "amazing"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment3, TextSentiment.POSITIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment3, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment3, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment3, 51); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment3, 0); final TargetSentiment targetSentiment1 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment1, "hotel"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment1, TextSentiment.NEGATIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment1, 4); final SentenceOpinion sentenceOpinion1 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion1, targetSentiment1); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion1, new IterableStream<>(asList(assessmentSentiment1, assessmentSentiment2))); final TargetSentiment targetSentiment2 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment2, "gnocchi"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment2, TextSentiment.POSITIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment2, 59); final SentenceOpinion sentenceOpinion2 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion2, targetSentiment2); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion2, new IterableStream<>(asList(assessmentSentiment3))); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, new IterableStream<>(asList(sentenceOpinion1))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 31); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment( "The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment2, new IterableStream<>(asList(sentenceOpinion2))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 32); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 35); return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); } /** * Helper method that get the second expected DocumentSentiment result. */ static DocumentSentiment getExpectedDocumentSentiment2() { final AssessmentSentiment assessmentSentiment1 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment1, "dark"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment1, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment1, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment1, 50); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment1, 0); final AssessmentSentiment assessmentSentiment2 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment2, "unclean"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment2, TextSentiment.NEGATIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment2, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment2, 59); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment2, 0); final AssessmentSentiment assessmentSentiment3 = new AssessmentSentiment(); AssessmentSentimentPropertiesHelper.setText(assessmentSentiment3, "amazing"); AssessmentSentimentPropertiesHelper.setSentiment(assessmentSentiment3, TextSentiment.POSITIVE); AssessmentSentimentPropertiesHelper.setConfidenceScores(assessmentSentiment3, new SentimentConfidenceScores(0.0, 0.0, 0.0)); AssessmentSentimentPropertiesHelper.setNegated(assessmentSentiment3, false); AssessmentSentimentPropertiesHelper.setOffset(assessmentSentiment3, 19); AssessmentSentimentPropertiesHelper.setLength(assessmentSentiment3, 0); final TargetSentiment targetSentiment1 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment1, "gnocchi"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment1, TextSentiment.POSITIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment1, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment1, 27); final SentenceOpinion sentenceOpinion1 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion1, targetSentiment1); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion1, new IterableStream<>(asList(assessmentSentiment3))); final TargetSentiment targetSentiment2 = new TargetSentiment(); TargetSentimentPropertiesHelper.setText(targetSentiment2, "hotel"); TargetSentimentPropertiesHelper.setSentiment(targetSentiment2, TextSentiment.NEGATIVE); TargetSentimentPropertiesHelper.setConfidenceScores(targetSentiment2, new SentimentConfidenceScores(0.0, 0.0, 0.0)); TargetSentimentPropertiesHelper.setOffset(targetSentiment2, 40); final SentenceOpinion sentenceOpinion2 = new SentenceOpinion(); SentenceOpinionPropertiesHelper.setTarget(sentenceOpinion2, targetSentiment2); SentenceOpinionPropertiesHelper.setAssessments(sentenceOpinion2, new IterableStream<>(asList(assessmentSentiment1, assessmentSentiment2))); final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "The restaurant had amazing gnocchi.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, new IterableStream<>(asList(sentenceOpinion1))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 35); final SentenceSentiment sentenceSentiment2 = new SentenceSentiment( "The hotel was dark and unclean.", TextSentiment.NEGATIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment2, new IterableStream<>(asList(sentenceOpinion2))); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment2, 36); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment2, 31); return new DocumentSentiment(TextSentiment.MIXED, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1, sentenceSentiment2)), null); } /* * This is the expected result for testing an input: * "I had a wonderful trip to Seattle last week." */ static DocumentSentiment getExpectedDocumentSentimentForActions() { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "I had a wonderful trip to Seattle last week.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, null); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 44); return new DocumentSentiment(TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1)), null); } /* * This is the expected result for testing an input: * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static DocumentSentiment getExpectedDocumentSentimentForActions2() { final SentenceSentiment sentenceSentiment1 = new SentenceSentiment( "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0)); SentenceSentimentPropertiesHelper.setOpinions(sentenceSentiment1, null); SentenceSentimentPropertiesHelper.setOffset(sentenceSentiment1, 0); SentenceSentimentPropertiesHelper.setLength(sentenceSentiment1, 67); return new DocumentSentiment(TextSentiment.POSITIVE, new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(sentenceSentiment1)), null); } /** * Helper method that get a single-page {@link AnalyzeHealthcareEntitiesResultCollection} list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage() { return asList( getExpectedAnalyzeHealthcareEntitiesResultCollection(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages {@link AnalyzeHealthcareEntitiesResultCollection} list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedAnalyzeHealthcareEntitiesResultCollectionListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults1 = new ArrayList<>(); int i = startIndex; for (; i < startIndex + firstPage; i++) { healthcareEntitiesResults1.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults2 = new ArrayList<>(); for (; i < startIndex + firstPage + secondPage; i++) { healthcareEntitiesResults2.add(getRecognizeHealthcareEntitiesResult1(Integer.toString(i))); } List<AnalyzeHealthcareEntitiesResultCollection> result = new ArrayList<>(); result.add(getExpectedAnalyzeHealthcareEntitiesResultCollection(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedAnalyzeHealthcareEntitiesResultCollection(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected {@link AnalyzeHealthcareEntitiesResultCollection} result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedAnalyzeHealthcareEntitiesResultCollection( int sizePerPage, List<AnalyzeHealthcareEntitiesResult> healthcareEntitiesResults) { TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics( sizePerPage, sizePerPage, 0, sizePerPage); final AnalyzeHealthcareEntitiesResultCollection analyzeHealthcareEntitiesResultCollection = new AnalyzeHealthcareEntitiesResultCollection(IterableStream.of(healthcareEntitiesResults)); AnalyzeHealthcareEntitiesResultCollectionPropertiesHelper.setModelVersion(analyzeHealthcareEntitiesResultCollection, "2020-09-03"); AnalyzeHealthcareEntitiesResultCollectionPropertiesHelper.setStatistics(analyzeHealthcareEntitiesResultCollection, textDocumentBatchStatistics); return analyzeHealthcareEntitiesResultCollection; } /** * Result for * "The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.", */ static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult1(String documentId) { TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(105, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "54-year-old"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, HealthcareEntityCategory.AGE); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 17); HealthcareEntityPropertiesHelper.setLength(healthcareEntity1, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity1, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "gentleman"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity2, "Male population group"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, HealthcareEntityCategory.GENDER); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 29); HealthcareEntityPropertiesHelper.setLength(healthcareEntity2, 9); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "progressive"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.fromString("Course")); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 0.91); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 57); HealthcareEntityPropertiesHelper.setLength(healthcareEntity3, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity3, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "angina"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity4, "Angina Pectoris"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.81); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 69); HealthcareEntityPropertiesHelper.setLength(healthcareEntity4, 6); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "past several months"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, HealthcareEntityCategory.TIME); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 85); HealthcareEntityPropertiesHelper.setLength(healthcareEntity5, 19); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity5, IterableStream.of(Collections.emptyList())); final AnalyzeHealthcareEntitiesResult healthcareEntitiesResult1 = new AnalyzeHealthcareEntitiesResult(documentId, textDocumentStatistics1, null); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult1, new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5))); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role1 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role1, "Course"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role1, healthcareEntity3); final HealthcareEntityRelationRole role2 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role2, "Condition"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role2, healthcareEntity4); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, HealthcareEntityRelationType.fromString("CourseOfCondition")); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation1, IterableStream.of(asList(role1, role2))); final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role3 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role3, "Time"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role3, healthcareEntity5); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, HealthcareEntityRelationType.TIME_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation2, IterableStream.of(asList(role2, role3))); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(healthcareEntitiesResult1, IterableStream.of(asList(healthcareEntityRelation1, healthcareEntityRelation2))); return healthcareEntitiesResult1; } /** * Result for * "The patient went for six minutes with minimal ST depressions in the anterior lateral leads , * thought due to fatigue and wrist pain , his anginal equivalent." */ static AnalyzeHealthcareEntitiesResult getRecognizeHealthcareEntitiesResult2() { TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(156, 1); final HealthcareEntity healthcareEntity1 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity1, "six minutes"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity1, HealthcareEntityCategory.TIME); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity1, 0.87); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity1, 21); HealthcareEntityPropertiesHelper.setLength(healthcareEntity1, 11); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity1, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity2 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity2, "minimal"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity2, HealthcareEntityCategory.CONDITION_QUALIFIER); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity2, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity2, 38); HealthcareEntityPropertiesHelper.setLength(healthcareEntity2, 7); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity2, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity3 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity3, "ST depressions"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity3, "ST segment depression (finding)"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity3, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity3, 46); HealthcareEntityPropertiesHelper.setLength(healthcareEntity3, 14); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity3, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity4 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity4, "anterior lateral"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity4, HealthcareEntityCategory.DIRECTION); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity4, 0.6); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity4, 68); HealthcareEntityPropertiesHelper.setLength(healthcareEntity4, 16); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity4, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity5 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity5, "fatigue"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity5, "Fatigue"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity5, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity5, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity5, 108); HealthcareEntityPropertiesHelper.setLength(healthcareEntity5, 7); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity5, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity6 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity6, "wrist pain"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity6, "Pain in wrist"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity6, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity6, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity6, 120); HealthcareEntityPropertiesHelper.setLength(healthcareEntity6, 10); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity6, IterableStream.of(Collections.emptyList())); final HealthcareEntity healthcareEntity7 = new HealthcareEntity(); HealthcareEntityPropertiesHelper.setText(healthcareEntity7, "anginal equivalent"); HealthcareEntityPropertiesHelper.setNormalizedText(healthcareEntity7, "Anginal equivalent"); HealthcareEntityPropertiesHelper.setCategory(healthcareEntity7, HealthcareEntityCategory.SYMPTOM_OR_SIGN); HealthcareEntityPropertiesHelper.setConfidenceScore(healthcareEntity7, 1.0); HealthcareEntityPropertiesHelper.setOffset(healthcareEntity7, 137); HealthcareEntityPropertiesHelper.setLength(healthcareEntity7, 18); HealthcareEntityPropertiesHelper.setDataSources(healthcareEntity7, IterableStream.of(Collections.emptyList())); final AnalyzeHealthcareEntitiesResult healthcareEntitiesResult = new AnalyzeHealthcareEntitiesResult("1", textDocumentStatistics, null); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntities(healthcareEntitiesResult, new IterableStream<>(asList(healthcareEntity1, healthcareEntity2, healthcareEntity3, healthcareEntity4, healthcareEntity5, healthcareEntity6, healthcareEntity7))); final HealthcareEntityRelation healthcareEntityRelation1 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role1 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role1, "Time"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role1, healthcareEntity1); final HealthcareEntityRelationRole role2 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role2, "Condition"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role2, healthcareEntity3); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation1, HealthcareEntityRelationType.TIME_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation1, IterableStream.of(asList(role1, role2))); final HealthcareEntityRelation healthcareEntityRelation2 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role3 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role3, "Qualifier"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role3, healthcareEntity2); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation2, HealthcareEntityRelationType.QUALIFIER_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation2, IterableStream.of(asList(role3, role2))); final HealthcareEntityRelation healthcareEntityRelation3 = new HealthcareEntityRelation(); final HealthcareEntityRelationRole role4 = new HealthcareEntityRelationRole(); HealthcareEntityRelationRolePropertiesHelper.setName(role4, "Direction"); HealthcareEntityRelationRolePropertiesHelper.setEntity(role4, healthcareEntity4); HealthcareEntityRelationPropertiesHelper.setRelationType(healthcareEntityRelation3, HealthcareEntityRelationType.DIRECTION_OF_CONDITION); HealthcareEntityRelationPropertiesHelper.setRoles(healthcareEntityRelation3, IterableStream.of(asList(role2, role4))); AnalyzeHealthcareEntitiesResultPropertiesHelper.setEntityRelations(healthcareEntitiesResult, IterableStream.of(asList(healthcareEntityRelation1, healthcareEntityRelation2, healthcareEntityRelation3))); return healthcareEntitiesResult; } /** * RecognizeEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollection() { return new RecognizeEntitiesResultCollection( asList(new RecognizeEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesList1()), null)), new RecognizeEntitiesResult("1", new TextDocumentStatistics(67, 1), null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null)) ), "2020-04-01", new TextDocumentBatchStatistics(2, 2, 0, 2)); } /** * RecognizePiiEntitiesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollection() { final PiiEntity piiEntity0 = new PiiEntity(); PiiEntityPropertiesHelper.setText(piiEntity0, "last week"); PiiEntityPropertiesHelper.setCategory(piiEntity0, PiiEntityCategory.fromString("DateTime")); PiiEntityPropertiesHelper.setSubcategory(piiEntity0, "DateRange"); PiiEntityPropertiesHelper.setOffset(piiEntity0, 34); return new RecognizePiiEntitiesResultCollection( asList( new RecognizePiiEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new PiiEntityCollection(new IterableStream<>(Arrays.asList(piiEntity0)), "I had a wonderful trip to Seattle *********.", null)), new RecognizePiiEntitiesResult("1", new TextDocumentStatistics(67, 1), null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null))), "2020-07-01", new TextDocumentBatchStatistics(2, 2, 0, 2) ); } /** * ExtractKeyPhrasesResultCollection result for * "I had a wonderful trip to Seattle last week." * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollection() { return new ExtractKeyPhrasesResultCollection( asList(new ExtractKeyPhraseResult("0", new TextDocumentStatistics(44, 1), null, new KeyPhrasesCollection(new IterableStream<>(asList("wonderful trip", "Seattle")), null)), new ExtractKeyPhraseResult("1", new TextDocumentStatistics(67, 1), null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome", "API")), null))), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollection() { return new RecognizeLinkedEntitiesResultCollection( asList(new RecognizeLinkedEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult("1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)) ), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollectionForActions() { return new RecognizeLinkedEntitiesResultCollection( asList(new RecognizeLinkedEntitiesResult("0", new TextDocumentStatistics(44, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)), new RecognizeLinkedEntitiesResult("1", new TextDocumentStatistics(20, 1), null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList3()), null)) ), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static AnalyzeSentimentResultCollection getAnalyzeSentimentResultCollectionForActions() { final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", null, null, getExpectedDocumentSentimentForActions()); final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", null, null, getExpectedDocumentSentimentForActions2()); return new AnalyzeSentimentResultCollection( asList(analyzeSentimentResult1, analyzeSentimentResult2), DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2)); } static RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static AnalyzeSentimentActionResult getExpectedAnalyzeSentimentActionResult(boolean isError, OffsetDateTime completeAt, AnalyzeSentimentResultCollection resultCollection, TextAnalyticsError actionError) { AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } static ExtractSummaryActionResult getExtractSummaryActionResult(boolean isError, OffsetDateTime completeAt, ExtractSummaryResultCollection resultCollection, TextAnalyticsError actionError) { ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult(); ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, actionError); return actionResult; } /** * Helper method that get the expected AnalyzeBatchActionsResult result. */ static AnalyzeActionsResult getExpectedAnalyzeBatchActionsResult( IterableStream<RecognizeEntitiesActionResult> recognizeEntitiesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults, IterableStream<ExtractSummaryActionResult> extractSummaryActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, analyzeSentimentActionResults); AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult, extractSummaryActionResults); return analyzeActionsResult; } /** * CategorizedEntityCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeEntitiesResultCollection getRecognizeEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizeEntitiesResult> recognizeEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeEntitiesResults.add(new RecognizeEntitiesResult(Integer.toString(i), null, null, new CategorizedEntityCollection(new IterableStream<>(getCategorizedEntitiesForPiiInput()), null))); } return new RecognizeEntitiesResultCollection(recognizeEntitiesResults, "2020-04-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * RecognizePiiEntitiesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizePiiEntitiesResultCollection getRecognizePiiEntitiesResultCollectionForPagination(int startIndex, int documentCount) { List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(Integer.toString(i), null, null, new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), "********* ******** with ssn *********** is using our awesome API's.", null))); } return new RecognizePiiEntitiesResultCollection(recognizePiiEntitiesResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * ExtractKeyPhrasesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static ExtractKeyPhrasesResultCollection getExtractKeyPhrasesResultCollectionForPagination(int startIndex, int documentCount) { List<ExtractKeyPhraseResult> extractKeyPhraseResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { extractKeyPhraseResults.add(new ExtractKeyPhraseResult(Integer.toString(i), null, null, new KeyPhrasesCollection(new IterableStream<>(asList("Microsoft employee", "ssn", "awesome", "API")), null))); } return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResults, "2020-07-01", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount)); } /** * RecognizeLinkedEntitiesResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static RecognizeLinkedEntitiesResultCollection getRecognizeLinkedEntitiesResultCollectionForPagination( int startIndex, int documentCount) { List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { recognizeLinkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(Integer.toString(i), null, null, new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList3()), null))); } return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResults, "", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * AnalyzeSentimentResultCollection result for * "Microsoft employee with ssn 859-98-0987 is using our awesome API's." */ static AnalyzeSentimentResultCollection getAnalyzeSentimentResultCollectionForPagination( int startIndex, int documentCount) { List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (int i = startIndex; i < startIndex + documentCount; i++) { analyzeSentimentResults.add(new AnalyzeSentimentResult(Integer.toString(i), null, null, getExpectedDocumentSentimentForActions2())); } return new AnalyzeSentimentResultCollection(analyzeSentimentResults, "", new TextDocumentBatchStatistics(documentCount, documentCount, 0, documentCount) ); } /** * Helper method that get a multiple-pages (AnalyzeActionsResult) list. */ static List<AnalyzeActionsResult> getExpectedAnalyzeActionsResultListForMultiplePages(int startIndex, int firstPage, int secondPage) { List<AnalyzeActionsResult> analyzeActionsResults = new ArrayList<>(); analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult( false, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult( false, TIME_NOW, getAnalyzeSentimentResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult( false, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult( false, TIME_NOW, getAnalyzeSentimentResultCollectionForPagination(startIndex, secondPage), null))), IterableStream.of(Collections.emptyList()) )); return analyzeActionsResults; } /** * Helper method that get a customized TextAnalyticsError. */ static TextAnalyticsError getActionError(TextAnalyticsErrorCode errorCode, String taskName, String index) { return new TextAnalyticsError(errorCode, "", " } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients() .forEach(httpClient -> { Arrays.stream(TextAnalyticsServiceVersion.values()).filter( TestUtils::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion))); }); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link TextAnalyticsServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(TextAnalyticsServiceVersion serviceVersion) { String serviceVersionFromEnv = Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS); if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) { return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) { return true; } String[] configuredServiceVersionList = serviceVersionFromEnv.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } private TestUtils() { } }
If an error is thrown by our own parsing method do we want to fallback to OffsetDateTime's parse method?
public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); }
this.dateTime = parse(formattedString);
public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); }
class DateTimeRfc1123 { private final ClientLogger logger = new ClientLogger(DateTimeRfc1123.class); /** * The pattern of the datetime used for RFC1123 datetime format. */ private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZone(ZoneId.of("UTC")).withLocale(Locale.US); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. */ private OffsetDateTime parse(final String date) { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8, 11), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } private int parseInt(final CharSequence date, final int start, final int end) { int num = 0; for (int i = start; i < end; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw logger.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } private int parseMonth(final String date, final int start, final int end) { switch (date.charAt(start)) { case 'J': switch (date.charAt(start + 1)) { case 'a': return 1; case 'u': switch (date.charAt(start + 2)) { case 'n': return 6; case 'l': return 7; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(start + 2)) { case 'r': return 3; case 'y': return 5; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(start + 2)) { case 'r': return 4; case 'g': return 8; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } @Override public String toString() { return RFC1123_DATE_TIME_FORMATTER.format(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
class DateTimeRfc1123 { private static final ClientLogger LOGGER = new ClientLogger(DateTimeRfc1123.class); /** * The pattern of the datetime used for RFC1123 datetime format. */ private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZone(ZoneId.of("UTC")).withLocale(Locale.US); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. * * @throws DateTimeException If the processing character is not a digit character. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static OffsetDateTime parse(final String date) { try { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } catch (DateTimeException | IllegalArgumentException | IndexOutOfBoundsException e) { return OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME); } } /** * Parses the specified substring of datetime to a 'int' value. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive. * @param endIndex The ending index, exclusive. * @return The specified substring. * * @throws DateTimeException If the processing character is not digit character. */ private static int parseInt(final CharSequence date, final int beginIndex, final int endIndex) { int num = 0; for (int i = beginIndex; i < endIndex; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw LOGGER.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } /** * Parses the specified month substring of datetime to a number value, '1' represents the month of January, * '12' represents the month of December. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive, to the * @return The number value which represents the month of year. '1' represents the month of January, * '12' represents the month of December. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static int parseMonth(final CharSequence date, final int beginIndex) { switch (date.charAt(beginIndex)) { case 'J': switch (date.charAt(beginIndex + 1)) { case 'a': return 1; case 'u': switch (date.charAt(beginIndex + 2)) { case 'n': return 6; case 'l': return 7; default: throw LOGGER.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(beginIndex + 2)) { case 'r': return 3; case 'y': return 5; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(beginIndex + 2)) { case 'r': return 4; case 'g': return 8; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } @Override public String toString() { return RFC1123_DATE_TIME_FORMATTER.format(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
This was my expectation. We should fall back to the code that we know works.
public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); }
this.dateTime = parse(formattedString);
public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); }
class DateTimeRfc1123 { private final ClientLogger logger = new ClientLogger(DateTimeRfc1123.class); /** * The pattern of the datetime used for RFC1123 datetime format. */ private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZone(ZoneId.of("UTC")).withLocale(Locale.US); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. */ private OffsetDateTime parse(final String date) { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8, 11), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } private int parseInt(final CharSequence date, final int start, final int end) { int num = 0; for (int i = start; i < end; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw logger.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } private int parseMonth(final String date, final int start, final int end) { switch (date.charAt(start)) { case 'J': switch (date.charAt(start + 1)) { case 'a': return 1; case 'u': switch (date.charAt(start + 2)) { case 'n': return 6; case 'l': return 7; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(start + 2)) { case 'r': return 3; case 'y': return 5; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(start + 2)) { case 'r': return 4; case 'g': return 8; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } @Override public String toString() { return RFC1123_DATE_TIME_FORMATTER.format(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
class DateTimeRfc1123 { private static final ClientLogger LOGGER = new ClientLogger(DateTimeRfc1123.class); /** * The pattern of the datetime used for RFC1123 datetime format. */ private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZone(ZoneId.of("UTC")).withLocale(Locale.US); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. * * @throws DateTimeException If the processing character is not a digit character. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static OffsetDateTime parse(final String date) { try { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } catch (DateTimeException | IllegalArgumentException | IndexOutOfBoundsException e) { return OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME); } } /** * Parses the specified substring of datetime to a 'int' value. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive. * @param endIndex The ending index, exclusive. * @return The specified substring. * * @throws DateTimeException If the processing character is not digit character. */ private static int parseInt(final CharSequence date, final int beginIndex, final int endIndex) { int num = 0; for (int i = beginIndex; i < endIndex; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw LOGGER.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } /** * Parses the specified month substring of datetime to a number value, '1' represents the month of January, * '12' represents the month of December. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive, to the * @return The number value which represents the month of year. '1' represents the month of January, * '12' represents the month of December. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static int parseMonth(final CharSequence date, final int beginIndex) { switch (date.charAt(beginIndex)) { case 'J': switch (date.charAt(beginIndex + 1)) { case 'a': return 1; case 'u': switch (date.charAt(beginIndex + 2)) { case 'n': return 6; case 'l': return 7; default: throw LOGGER.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(beginIndex + 2)) { case 'r': return 3; case 'y': return 5; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(beginIndex + 2)) { case 'r': return 4; case 'g': return 8; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } @Override public String toString() { return RFC1123_DATE_TIME_FORMATTER.format(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
Added the fallback to OffsetDateTime's parse method in parse() now
public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); }
this.dateTime = parse(formattedString);
public DateTimeRfc1123(String formattedString) { this.dateTime = parse(formattedString); }
class DateTimeRfc1123 { private final ClientLogger logger = new ClientLogger(DateTimeRfc1123.class); /** * The pattern of the datetime used for RFC1123 datetime format. */ private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZone(ZoneId.of("UTC")).withLocale(Locale.US); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. */ private OffsetDateTime parse(final String date) { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8, 11), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } private int parseInt(final CharSequence date, final int start, final int end) { int num = 0; for (int i = start; i < end; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw logger.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } private int parseMonth(final String date, final int start, final int end) { switch (date.charAt(start)) { case 'J': switch (date.charAt(start + 1)) { case 'a': return 1; case 'u': switch (date.charAt(start + 2)) { case 'n': return 6; case 'l': return 7; default: throw logger.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(start + 2)) { case 'r': return 3; case 'y': return 5; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(start + 2)) { case 'r': return 4; case 'g': return 8; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } @Override public String toString() { return RFC1123_DATE_TIME_FORMATTER.format(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
class DateTimeRfc1123 { private static final ClientLogger LOGGER = new ClientLogger(DateTimeRfc1123.class); /** * The pattern of the datetime used for RFC1123 datetime format. */ private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZone(ZoneId.of("UTC")).withLocale(Locale.US); /** * The actual datetime object. */ private final OffsetDateTime dateTime; /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param dateTime The DateTime object to wrap. */ public DateTimeRfc1123(OffsetDateTime dateTime) { this.dateTime = dateTime; } /** * Creates a new DateTimeRfc1123 object with the specified DateTime. * @param formattedString The datetime string in RFC1123 format */ /** * Returns the underlying DateTime. * @return The underlying DateTime. */ public OffsetDateTime getDateTime() { return this.dateTime; } /** * Parses the RFC1123 format datetime string into OffsetDateTime. * * @param date The datetime string in RFC1123 format * @return The underlying OffsetDateTime. * * @throws DateTimeException If the processing character is not a digit character. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static OffsetDateTime parse(final String date) { try { return OffsetDateTime.of( parseInt(date, 12, 16), parseMonth(date, 8), parseInt(date, 5, 7), parseInt(date, 17, 19), parseInt(date, 20, 22), parseInt(date, 23, 25), 0, ZoneOffset.UTC); } catch (DateTimeException | IllegalArgumentException | IndexOutOfBoundsException e) { return OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME); } } /** * Parses the specified substring of datetime to a 'int' value. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive. * @param endIndex The ending index, exclusive. * @return The specified substring. * * @throws DateTimeException If the processing character is not digit character. */ private static int parseInt(final CharSequence date, final int beginIndex, final int endIndex) { int num = 0; for (int i = beginIndex; i < endIndex; i++) { final char c = date.charAt(i); if (c < '0' || c > '9') { throw LOGGER.logExceptionAsError(new DateTimeException("Invalid date time: " + date)); } num = num * 10 + (c - '0'); } return num; } /** * Parses the specified month substring of datetime to a number value, '1' represents the month of January, * '12' represents the month of December. * * @param date The datetime string in RFC1123 format. * @param beginIndex The beginning index, inclusive, to the * @return The number value which represents the month of year. '1' represents the month of January, * '12' represents the month of December. * @throws IllegalArgumentException if the given character is not recognized in the pattern of Month. such as 'Jan'. * @throws IndexOutOfBoundsException if the {@code beginIndex} is negative, or beginIndex is larger than length of * {@code date}. */ private static int parseMonth(final CharSequence date, final int beginIndex) { switch (date.charAt(beginIndex)) { case 'J': switch (date.charAt(beginIndex + 1)) { case 'a': return 1; case 'u': switch (date.charAt(beginIndex + 2)) { case 'n': return 6; case 'l': return 7; default: throw LOGGER.logExceptionAsError( new IllegalArgumentException("Unknown month " + date)); } default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'F': return 2; case 'M': switch (date.charAt(beginIndex + 2)) { case 'r': return 3; case 'y': return 5; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'A': switch (date.charAt(beginIndex + 2)) { case 'r': return 4; case 'g': return 8; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } case 'S': return 9; case 'O': return 10; case 'N': return 11; case 'D': return 12; default: throw LOGGER.logExceptionAsError(new IllegalArgumentException("Unknown month " + date)); } } @Override public String toString() { return RFC1123_DATE_TIME_FORMATTER.format(this.dateTime); } @Override public int hashCode() { return this.dateTime.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof DateTimeRfc1123)) { return false; } DateTimeRfc1123 rhs = (DateTimeRfc1123) obj; return this.dateTime.equals(rhs.getDateTime()); } }
For this class would the expectation be a more verbose string or something that matches the ISO8601 time interval format?
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (duration != null) { return sb.append("duration: ").append(duration).append("]").toString(); } if (startTime != null) { sb.append("start time: ").append(startTime); } if (startDuration != null) { sb.append("start duration: ").append(startDuration); } sb.append(", "); if (endTime != null) { sb.append("end time: ").append(endTime); } if (endDuration != null) { sb.append("end duration: ").append(endDuration); } sb.append("]"); return sb.toString(); }
return sb.toString();
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (duration != null && endTime != null) { sb.append("duration: ") .append(duration) .append(", ") .append("end time: ") .append(endTime); } else if (startTime != null && endTime != null) { sb.append("start time: ") .append(startTime) .append(", ") .append("end time: ") .append(endTime); } else if (startTime != null && duration != null) { sb.append("start time: ") .append(startTime) .append(", ") .append("duration: ") .append(duration); } else { sb.append("duration: ").append(duration); } sb.append("]"); return sb.toString(); }
class TimeInterval { public static final TimeInterval ALL = new TimeInterval(OffsetDateTime.MIN, OffsetDateTime.MAX); public static final TimeInterval LAST_5_MINUTES = new TimeInterval(Duration.ofMinutes(5)); public static final TimeInterval LAST_30_MINUTES = new TimeInterval(Duration.ofMinutes(30)); public static final TimeInterval LAST_1_HOUR = new TimeInterval(Duration.ofHours(1)); public static final TimeInterval LAST_4_HOURS = new TimeInterval(Duration.ofHours(4)); public static final TimeInterval LAST_12_HOURS = new TimeInterval(Duration.ofHours(12)); public static final TimeInterval LAST_DAY = new TimeInterval(Duration.ofDays(1)); public static final TimeInterval LAST_2_DAYS = new TimeInterval(Duration.ofDays(2)); public static final TimeInterval LAST_3_DAYS = new TimeInterval(Duration.ofDays(3)); public static final TimeInterval LAST_7_DAYS = new TimeInterval(Duration.ofDays(7)); private static final ClientLogger LOGGER = new ClientLogger(TimeInterval.class); private static final String ERROR_MESSAGE = "%s is an invalid time interval. It must be in one of the " + "following ISO 8601 time interval formats: duration, startDuration/endTime, " + "startTime/endTime, startTime/endDuration"; private final Duration duration; private final Duration startDuration; private final Duration endDuration; private final OffsetDateTime startTime; private final OffsetDateTime endTime; /** * Creates an instance of {@link TimeInterval} using the provided duration. * @param duration the duration for this query time span. */ public TimeInterval(Duration duration) { this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startDuration = null; this.endDuration = null; this.startTime = null; this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end {@link OffsetDateTime OffsetDateTimes}. * @param startTime The start time of the interval. * @param endTime The end time of the interval. */ public TimeInterval(OffsetDateTime startTime, OffsetDateTime endTime) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = null; this.startDuration = null; this.endDuration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startTime The start time of the interval. * @param endDuration The end duration of the interval. */ public TimeInterval(OffsetDateTime startTime, Duration endDuration) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endDuration = Objects.requireNonNull(endDuration, "'endDuration' cannot be null"); this.duration = null; this.endTime = null; this.startDuration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startDuration The duration of the interval. * @param endTime The end time of the interval. */ public TimeInterval(Duration startDuration, OffsetDateTime endTime) { this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.startDuration = Objects.requireNonNull(startDuration, "'startDuration' cannot be null"); this.duration = null; this.startTime = null; this.endDuration = null; } /** * Returns the duration of this {@link TimeInterval} instance. * @return the duration of this {@link TimeInterval} instance. */ public Duration getDuration() { return duration; } /** * Returns the start duration of this {@link TimeInterval} instance. * @return the start duration of this {@link TimeInterval} instance. */ public Duration getStartDuration() { return startDuration; } /** * Returns the end duration of this {@link TimeInterval} instance. * @return the end duration of this {@link TimeInterval} instance. */ public Duration getEndDuration() { return endDuration; } /** * Returns the start time of this {@link TimeInterval} instance. * @return the start time of this {@link TimeInterval} instance. */ public OffsetDateTime getStartTime() { return startTime; } /** * Returns the end time of this {@link TimeInterval} instance. * @return the end time of this {@link TimeInterval} instance. */ public OffsetDateTime getEndTime() { return endTime; } /** * Returns this {@link TimeInterval} in ISO 8601 string format. * @return ISO 8601 formatted string representation of this {@link TimeInterval} instance. */ public String toIso8601Format() { if (startTime != null && endTime != null) { return startTime + "/" + endTime; } if (startTime != null && endDuration != null) { return startTime + "/" + endDuration; } if (startDuration != null && endTime != null) { return startDuration + "/" + endTime; } if (duration != null) { return duration.toString(); } throw LOGGER.logExceptionAsError(new IllegalStateException("Invalid date time range")); } /** * This method takes an ISO 8601 formatted time interval string and returns an instance of {@link TimeInterval}. * @param value The ISO 8601 formatted time interval string. * @return An instance of {@link TimeInterval}. * @throws IllegalArgumentException if {@code value} is not in the correct format. */ public static TimeInterval parse(String value) { Objects.requireNonNull(value); String[] parts = value.split("/"); if (parts.length == 1) { Duration duration = parseDuration(parts[0]); if (duration == null || parts[0].length() + 1 == value.length()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } return new TimeInterval(duration); } if (parts.length == 2) { Duration startDuration = parseDuration(parts[0]); OffsetDateTime startTime = parseTime(parts[0]); Duration endDuration = parseDuration(parts[1]); OffsetDateTime endTime = parseTime(parts[1]); if (startDuration != null && endTime != null) { return new TimeInterval(startDuration, endTime); } if (startTime != null && endTime != null) { return new TimeInterval(startTime, endTime); } if (startTime != null && endDuration != null) { return new TimeInterval(startTime, endDuration); } } throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } @Override @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeInterval that = (TimeInterval) o; return Objects.equals(this.duration, that.duration) && Objects.equals(this.startDuration, that.startDuration) && Objects.equals(this.endDuration, that.endDuration) && Objects.equals(this.startTime, that.startTime) && Objects.equals(this.endTime, that.endTime); } @Override public int hashCode() { return Objects.hash(duration, startDuration, endDuration, startTime, endTime); } private static OffsetDateTime parseTime(String value) { try { return OffsetDateTime.parse(value); } catch (Exception exception) { return null; } } private static Duration parseDuration(String value) { try { return Duration.parse(value); } catch (Exception exception) { return null; } } }
class TimeInterval { public static final TimeInterval ALL = new TimeInterval(OffsetDateTime.MIN, OffsetDateTime.MAX); public static final TimeInterval LAST_5_MINUTES = new TimeInterval(Duration.ofMinutes(5)); public static final TimeInterval LAST_30_MINUTES = new TimeInterval(Duration.ofMinutes(30)); public static final TimeInterval LAST_1_HOUR = new TimeInterval(Duration.ofHours(1)); public static final TimeInterval LAST_4_HOURS = new TimeInterval(Duration.ofHours(4)); public static final TimeInterval LAST_12_HOURS = new TimeInterval(Duration.ofHours(12)); public static final TimeInterval LAST_DAY = new TimeInterval(Duration.ofDays(1)); public static final TimeInterval LAST_2_DAYS = new TimeInterval(Duration.ofDays(2)); public static final TimeInterval LAST_3_DAYS = new TimeInterval(Duration.ofDays(3)); public static final TimeInterval LAST_7_DAYS = new TimeInterval(Duration.ofDays(7)); private static final ClientLogger LOGGER = new ClientLogger(TimeInterval.class); private static final String ERROR_MESSAGE = "%s is an invalid time interval. It must be in one of the " + "following ISO 8601 time interval formats: duration, startDuration/endTime, " + "startTime/endTime, startTime/endDuration"; private final Duration duration; private final OffsetDateTime startTime; private final OffsetDateTime endTime; /** * Creates an instance of {@link TimeInterval} using the provided duration. The duration is the interval that * starts from the provided duration and ends at the current time. * @param duration the duration for this query time span. */ public TimeInterval(Duration duration) { this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startTime = null; this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end {@link OffsetDateTime OffsetDateTimes}. * @param startTime The start time of the interval. * @param endTime The end time of the interval. */ public TimeInterval(OffsetDateTime startTime, OffsetDateTime endTime) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startTime The start time of the interval. * @param duration The end duration of the interval. */ public TimeInterval(OffsetDateTime startTime, Duration duration) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param duration The duration of the interval. * @param endTime The end time of the interval. */ TimeInterval(Duration duration, OffsetDateTime endTime) { this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startTime = null; } /** * Returns the duration of this {@link TimeInterval} instance. * @return the duration of this {@link TimeInterval} instance. */ public Duration getDuration() { return duration; } /** * Returns the start time of this {@link TimeInterval} instance. * @return the start time of this {@link TimeInterval} instance. */ public OffsetDateTime getStartTime() { if (startTime != null) { return startTime; } if (duration != null && endTime != null) { return endTime.minusNanos(duration.toNanos()); } return null; } /** * Returns the end time of this {@link TimeInterval} instance. * @return the end time of this {@link TimeInterval} instance. */ public OffsetDateTime getEndTime() { if (endTime != null) { return endTime; } if (startTime != null && duration != null) { return startTime.plusNanos(duration.toNanos()); } return null; } /** * Returns this {@link TimeInterval} in ISO 8601 string format. * @return ISO 8601 formatted string representation of this {@link TimeInterval} instance. */ public String toIso8601Format() { if (startTime != null && endTime != null) { return startTime + "/" + endTime; } if (startTime != null && duration != null) { return startTime + "/" + duration; } if (duration != null && endTime != null) { return duration + "/" + endTime; } return duration == null ? null : duration.toString(); } /** * This method takes an ISO 8601 formatted time interval string and returns an instance of {@link TimeInterval}. * @param value The ISO 8601 formatted time interval string. * @return An instance of {@link TimeInterval}. * @throws IllegalArgumentException if {@code value} is not in the correct format. */ public static TimeInterval parse(String value) { Objects.requireNonNull(value); String[] parts = value.split("/"); if (parts.length == 1) { Duration duration = parseDuration(parts[0]); if (duration == null || parts[0].length() + 1 == value.length()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } return new TimeInterval(duration); } if (parts.length == 2) { Duration startDuration = parseDuration(parts[0]); OffsetDateTime startTime = parseTime(parts[0]); Duration endDuration = parseDuration(parts[1]); OffsetDateTime endTime = parseTime(parts[1]); if (startDuration != null && endTime != null) { return new TimeInterval(startDuration, endTime); } if (startTime != null && endTime != null) { return new TimeInterval(startTime, endTime); } if (startTime != null && endDuration != null) { return new TimeInterval(startTime, endDuration); } } throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } @Override @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeInterval that = (TimeInterval) o; return Objects.equals(this.duration, that.duration) && Objects.equals(this.startTime, that.startTime) && Objects.equals(this.endTime, that.endTime); } @Override public int hashCode() { return Objects.hash(duration, startTime, endTime); } private static OffsetDateTime parseTime(String value) { try { return OffsetDateTime.parse(value); } catch (Exception exception) { return null; } } private static Duration parseDuration(String value) { try { return Duration.parse(value); } catch (Exception exception) { return null; } } }
You could simplify this with using `instanceof`
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeInterval that = (TimeInterval) o; return Objects.equals(this.duration, that.duration) && Objects.equals(this.startDuration, that.startDuration) && Objects.equals(this.endDuration, that.endDuration) && Objects.equals(this.startTime, that.startTime) && Objects.equals(this.endTime, that.endTime); }
if (o == null || getClass() != o.getClass()) {
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeInterval that = (TimeInterval) o; return Objects.equals(this.duration, that.duration) && Objects.equals(this.startTime, that.startTime) && Objects.equals(this.endTime, that.endTime); }
class TimeInterval { public static final TimeInterval ALL = new TimeInterval(OffsetDateTime.MIN, OffsetDateTime.MAX); public static final TimeInterval LAST_5_MINUTES = new TimeInterval(Duration.ofMinutes(5)); public static final TimeInterval LAST_30_MINUTES = new TimeInterval(Duration.ofMinutes(30)); public static final TimeInterval LAST_1_HOUR = new TimeInterval(Duration.ofHours(1)); public static final TimeInterval LAST_4_HOURS = new TimeInterval(Duration.ofHours(4)); public static final TimeInterval LAST_12_HOURS = new TimeInterval(Duration.ofHours(12)); public static final TimeInterval LAST_DAY = new TimeInterval(Duration.ofDays(1)); public static final TimeInterval LAST_2_DAYS = new TimeInterval(Duration.ofDays(2)); public static final TimeInterval LAST_3_DAYS = new TimeInterval(Duration.ofDays(3)); public static final TimeInterval LAST_7_DAYS = new TimeInterval(Duration.ofDays(7)); private static final ClientLogger LOGGER = new ClientLogger(TimeInterval.class); private static final String ERROR_MESSAGE = "%s is an invalid time interval. It must be in one of the " + "following ISO 8601 time interval formats: duration, startDuration/endTime, " + "startTime/endTime, startTime/endDuration"; private final Duration duration; private final Duration startDuration; private final Duration endDuration; private final OffsetDateTime startTime; private final OffsetDateTime endTime; /** * Creates an instance of {@link TimeInterval} using the provided duration. * @param duration the duration for this query time span. */ public TimeInterval(Duration duration) { this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startDuration = null; this.endDuration = null; this.startTime = null; this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end {@link OffsetDateTime OffsetDateTimes}. * @param startTime The start time of the interval. * @param endTime The end time of the interval. */ public TimeInterval(OffsetDateTime startTime, OffsetDateTime endTime) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = null; this.startDuration = null; this.endDuration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startTime The start time of the interval. * @param endDuration The end duration of the interval. */ public TimeInterval(OffsetDateTime startTime, Duration endDuration) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endDuration = Objects.requireNonNull(endDuration, "'endDuration' cannot be null"); this.duration = null; this.endTime = null; this.startDuration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startDuration The duration of the interval. * @param endTime The end time of the interval. */ public TimeInterval(Duration startDuration, OffsetDateTime endTime) { this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.startDuration = Objects.requireNonNull(startDuration, "'startDuration' cannot be null"); this.duration = null; this.startTime = null; this.endDuration = null; } /** * Returns the duration of this {@link TimeInterval} instance. * @return the duration of this {@link TimeInterval} instance. */ public Duration getDuration() { return duration; } /** * Returns the start duration of this {@link TimeInterval} instance. * @return the start duration of this {@link TimeInterval} instance. */ public Duration getStartDuration() { return startDuration; } /** * Returns the end duration of this {@link TimeInterval} instance. * @return the end duration of this {@link TimeInterval} instance. */ public Duration getEndDuration() { return endDuration; } /** * Returns the start time of this {@link TimeInterval} instance. * @return the start time of this {@link TimeInterval} instance. */ public OffsetDateTime getStartTime() { return startTime; } /** * Returns the end time of this {@link TimeInterval} instance. * @return the end time of this {@link TimeInterval} instance. */ public OffsetDateTime getEndTime() { return endTime; } /** * Returns this {@link TimeInterval} in ISO 8601 string format. * @return ISO 8601 formatted string representation of this {@link TimeInterval} instance. */ public String toIso8601Format() { if (startTime != null && endTime != null) { return startTime + "/" + endTime; } if (startTime != null && endDuration != null) { return startTime + "/" + endDuration; } if (startDuration != null && endTime != null) { return startDuration + "/" + endTime; } if (duration != null) { return duration.toString(); } throw LOGGER.logExceptionAsError(new IllegalStateException("Invalid date time range")); } /** * This method takes an ISO 8601 formatted time interval string and returns an instance of {@link TimeInterval}. * @param value The ISO 8601 formatted time interval string. * @return An instance of {@link TimeInterval}. * @throws IllegalArgumentException if {@code value} is not in the correct format. */ public static TimeInterval parse(String value) { Objects.requireNonNull(value); String[] parts = value.split("/"); if (parts.length == 1) { Duration duration = parseDuration(parts[0]); if (duration == null || parts[0].length() + 1 == value.length()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } return new TimeInterval(duration); } if (parts.length == 2) { Duration startDuration = parseDuration(parts[0]); OffsetDateTime startTime = parseTime(parts[0]); Duration endDuration = parseDuration(parts[1]); OffsetDateTime endTime = parseTime(parts[1]); if (startDuration != null && endTime != null) { return new TimeInterval(startDuration, endTime); } if (startTime != null && endTime != null) { return new TimeInterval(startTime, endTime); } if (startTime != null && endDuration != null) { return new TimeInterval(startTime, endDuration); } } throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (duration != null) { return sb.append("duration: ").append(duration).append("]").toString(); } if (startTime != null) { sb.append("start time: ").append(startTime); } if (startDuration != null) { sb.append("start duration: ").append(startDuration); } sb.append(", "); if (endTime != null) { sb.append("end time: ").append(endTime); } if (endDuration != null) { sb.append("end duration: ").append(endDuration); } sb.append("]"); return sb.toString(); } @Override @Override public int hashCode() { return Objects.hash(duration, startDuration, endDuration, startTime, endTime); } private static OffsetDateTime parseTime(String value) { try { return OffsetDateTime.parse(value); } catch (Exception exception) { return null; } } private static Duration parseDuration(String value) { try { return Duration.parse(value); } catch (Exception exception) { return null; } } }
class TimeInterval { public static final TimeInterval ALL = new TimeInterval(OffsetDateTime.MIN, OffsetDateTime.MAX); public static final TimeInterval LAST_5_MINUTES = new TimeInterval(Duration.ofMinutes(5)); public static final TimeInterval LAST_30_MINUTES = new TimeInterval(Duration.ofMinutes(30)); public static final TimeInterval LAST_1_HOUR = new TimeInterval(Duration.ofHours(1)); public static final TimeInterval LAST_4_HOURS = new TimeInterval(Duration.ofHours(4)); public static final TimeInterval LAST_12_HOURS = new TimeInterval(Duration.ofHours(12)); public static final TimeInterval LAST_DAY = new TimeInterval(Duration.ofDays(1)); public static final TimeInterval LAST_2_DAYS = new TimeInterval(Duration.ofDays(2)); public static final TimeInterval LAST_3_DAYS = new TimeInterval(Duration.ofDays(3)); public static final TimeInterval LAST_7_DAYS = new TimeInterval(Duration.ofDays(7)); private static final ClientLogger LOGGER = new ClientLogger(TimeInterval.class); private static final String ERROR_MESSAGE = "%s is an invalid time interval. It must be in one of the " + "following ISO 8601 time interval formats: duration, startDuration/endTime, " + "startTime/endTime, startTime/endDuration"; private final Duration duration; private final OffsetDateTime startTime; private final OffsetDateTime endTime; /** * Creates an instance of {@link TimeInterval} using the provided duration. The duration is the interval that * starts from the provided duration and ends at the current time. * @param duration the duration for this query time span. */ public TimeInterval(Duration duration) { this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startTime = null; this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end {@link OffsetDateTime OffsetDateTimes}. * @param startTime The start time of the interval. * @param endTime The end time of the interval. */ public TimeInterval(OffsetDateTime startTime, OffsetDateTime endTime) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startTime The start time of the interval. * @param duration The end duration of the interval. */ public TimeInterval(OffsetDateTime startTime, Duration duration) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param duration The duration of the interval. * @param endTime The end time of the interval. */ TimeInterval(Duration duration, OffsetDateTime endTime) { this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startTime = null; } /** * Returns the duration of this {@link TimeInterval} instance. * @return the duration of this {@link TimeInterval} instance. */ public Duration getDuration() { return duration; } /** * Returns the start time of this {@link TimeInterval} instance. * @return the start time of this {@link TimeInterval} instance. */ public OffsetDateTime getStartTime() { if (startTime != null) { return startTime; } if (duration != null && endTime != null) { return endTime.minusNanos(duration.toNanos()); } return null; } /** * Returns the end time of this {@link TimeInterval} instance. * @return the end time of this {@link TimeInterval} instance. */ public OffsetDateTime getEndTime() { if (endTime != null) { return endTime; } if (startTime != null && duration != null) { return startTime.plusNanos(duration.toNanos()); } return null; } /** * Returns this {@link TimeInterval} in ISO 8601 string format. * @return ISO 8601 formatted string representation of this {@link TimeInterval} instance. */ public String toIso8601Format() { if (startTime != null && endTime != null) { return startTime + "/" + endTime; } if (startTime != null && duration != null) { return startTime + "/" + duration; } if (duration != null && endTime != null) { return duration + "/" + endTime; } return duration == null ? null : duration.toString(); } /** * This method takes an ISO 8601 formatted time interval string and returns an instance of {@link TimeInterval}. * @param value The ISO 8601 formatted time interval string. * @return An instance of {@link TimeInterval}. * @throws IllegalArgumentException if {@code value} is not in the correct format. */ public static TimeInterval parse(String value) { Objects.requireNonNull(value); String[] parts = value.split("/"); if (parts.length == 1) { Duration duration = parseDuration(parts[0]); if (duration == null || parts[0].length() + 1 == value.length()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } return new TimeInterval(duration); } if (parts.length == 2) { Duration startDuration = parseDuration(parts[0]); OffsetDateTime startTime = parseTime(parts[0]); Duration endDuration = parseDuration(parts[1]); OffsetDateTime endTime = parseTime(parts[1]); if (startDuration != null && endTime != null) { return new TimeInterval(startDuration, endTime); } if (startTime != null && endTime != null) { return new TimeInterval(startTime, endTime); } if (startTime != null && endDuration != null) { return new TimeInterval(startTime, endDuration); } } throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (duration != null && endTime != null) { sb.append("duration: ") .append(duration) .append(", ") .append("end time: ") .append(endTime); } else if (startTime != null && endTime != null) { sb.append("start time: ") .append(startTime) .append(", ") .append("end time: ") .append(endTime); } else if (startTime != null && duration != null) { sb.append("start time: ") .append(startTime) .append(", ") .append("duration: ") .append(duration); } else { sb.append("duration: ").append(duration); } sb.append("]"); return sb.toString(); } @Override @Override public int hashCode() { return Objects.hash(duration, startTime, endTime); } private static OffsetDateTime parseTime(String value) { try { return OffsetDateTime.parse(value); } catch (Exception exception) { return null; } } private static Duration parseDuration(String value) { try { return Duration.parse(value); } catch (Exception exception) { return null; } } }
The `toString` method is a more verbose representation. We have another method `toIso8601Format` to return ISO 8601 standardized format.
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (duration != null) { return sb.append("duration: ").append(duration).append("]").toString(); } if (startTime != null) { sb.append("start time: ").append(startTime); } if (startDuration != null) { sb.append("start duration: ").append(startDuration); } sb.append(", "); if (endTime != null) { sb.append("end time: ").append(endTime); } if (endDuration != null) { sb.append("end duration: ").append(endDuration); } sb.append("]"); return sb.toString(); }
return sb.toString();
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); if (duration != null && endTime != null) { sb.append("duration: ") .append(duration) .append(", ") .append("end time: ") .append(endTime); } else if (startTime != null && endTime != null) { sb.append("start time: ") .append(startTime) .append(", ") .append("end time: ") .append(endTime); } else if (startTime != null && duration != null) { sb.append("start time: ") .append(startTime) .append(", ") .append("duration: ") .append(duration); } else { sb.append("duration: ").append(duration); } sb.append("]"); return sb.toString(); }
class TimeInterval { public static final TimeInterval ALL = new TimeInterval(OffsetDateTime.MIN, OffsetDateTime.MAX); public static final TimeInterval LAST_5_MINUTES = new TimeInterval(Duration.ofMinutes(5)); public static final TimeInterval LAST_30_MINUTES = new TimeInterval(Duration.ofMinutes(30)); public static final TimeInterval LAST_1_HOUR = new TimeInterval(Duration.ofHours(1)); public static final TimeInterval LAST_4_HOURS = new TimeInterval(Duration.ofHours(4)); public static final TimeInterval LAST_12_HOURS = new TimeInterval(Duration.ofHours(12)); public static final TimeInterval LAST_DAY = new TimeInterval(Duration.ofDays(1)); public static final TimeInterval LAST_2_DAYS = new TimeInterval(Duration.ofDays(2)); public static final TimeInterval LAST_3_DAYS = new TimeInterval(Duration.ofDays(3)); public static final TimeInterval LAST_7_DAYS = new TimeInterval(Duration.ofDays(7)); private static final ClientLogger LOGGER = new ClientLogger(TimeInterval.class); private static final String ERROR_MESSAGE = "%s is an invalid time interval. It must be in one of the " + "following ISO 8601 time interval formats: duration, startDuration/endTime, " + "startTime/endTime, startTime/endDuration"; private final Duration duration; private final Duration startDuration; private final Duration endDuration; private final OffsetDateTime startTime; private final OffsetDateTime endTime; /** * Creates an instance of {@link TimeInterval} using the provided duration. * @param duration the duration for this query time span. */ public TimeInterval(Duration duration) { this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startDuration = null; this.endDuration = null; this.startTime = null; this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end {@link OffsetDateTime OffsetDateTimes}. * @param startTime The start time of the interval. * @param endTime The end time of the interval. */ public TimeInterval(OffsetDateTime startTime, OffsetDateTime endTime) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = null; this.startDuration = null; this.endDuration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startTime The start time of the interval. * @param endDuration The end duration of the interval. */ public TimeInterval(OffsetDateTime startTime, Duration endDuration) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endDuration = Objects.requireNonNull(endDuration, "'endDuration' cannot be null"); this.duration = null; this.endTime = null; this.startDuration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startDuration The duration of the interval. * @param endTime The end time of the interval. */ public TimeInterval(Duration startDuration, OffsetDateTime endTime) { this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.startDuration = Objects.requireNonNull(startDuration, "'startDuration' cannot be null"); this.duration = null; this.startTime = null; this.endDuration = null; } /** * Returns the duration of this {@link TimeInterval} instance. * @return the duration of this {@link TimeInterval} instance. */ public Duration getDuration() { return duration; } /** * Returns the start duration of this {@link TimeInterval} instance. * @return the start duration of this {@link TimeInterval} instance. */ public Duration getStartDuration() { return startDuration; } /** * Returns the end duration of this {@link TimeInterval} instance. * @return the end duration of this {@link TimeInterval} instance. */ public Duration getEndDuration() { return endDuration; } /** * Returns the start time of this {@link TimeInterval} instance. * @return the start time of this {@link TimeInterval} instance. */ public OffsetDateTime getStartTime() { return startTime; } /** * Returns the end time of this {@link TimeInterval} instance. * @return the end time of this {@link TimeInterval} instance. */ public OffsetDateTime getEndTime() { return endTime; } /** * Returns this {@link TimeInterval} in ISO 8601 string format. * @return ISO 8601 formatted string representation of this {@link TimeInterval} instance. */ public String toIso8601Format() { if (startTime != null && endTime != null) { return startTime + "/" + endTime; } if (startTime != null && endDuration != null) { return startTime + "/" + endDuration; } if (startDuration != null && endTime != null) { return startDuration + "/" + endTime; } if (duration != null) { return duration.toString(); } throw LOGGER.logExceptionAsError(new IllegalStateException("Invalid date time range")); } /** * This method takes an ISO 8601 formatted time interval string and returns an instance of {@link TimeInterval}. * @param value The ISO 8601 formatted time interval string. * @return An instance of {@link TimeInterval}. * @throws IllegalArgumentException if {@code value} is not in the correct format. */ public static TimeInterval parse(String value) { Objects.requireNonNull(value); String[] parts = value.split("/"); if (parts.length == 1) { Duration duration = parseDuration(parts[0]); if (duration == null || parts[0].length() + 1 == value.length()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } return new TimeInterval(duration); } if (parts.length == 2) { Duration startDuration = parseDuration(parts[0]); OffsetDateTime startTime = parseTime(parts[0]); Duration endDuration = parseDuration(parts[1]); OffsetDateTime endTime = parseTime(parts[1]); if (startDuration != null && endTime != null) { return new TimeInterval(startDuration, endTime); } if (startTime != null && endTime != null) { return new TimeInterval(startTime, endTime); } if (startTime != null && endDuration != null) { return new TimeInterval(startTime, endDuration); } } throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } @Override @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeInterval that = (TimeInterval) o; return Objects.equals(this.duration, that.duration) && Objects.equals(this.startDuration, that.startDuration) && Objects.equals(this.endDuration, that.endDuration) && Objects.equals(this.startTime, that.startTime) && Objects.equals(this.endTime, that.endTime); } @Override public int hashCode() { return Objects.hash(duration, startDuration, endDuration, startTime, endTime); } private static OffsetDateTime parseTime(String value) { try { return OffsetDateTime.parse(value); } catch (Exception exception) { return null; } } private static Duration parseDuration(String value) { try { return Duration.parse(value); } catch (Exception exception) { return null; } } }
class TimeInterval { public static final TimeInterval ALL = new TimeInterval(OffsetDateTime.MIN, OffsetDateTime.MAX); public static final TimeInterval LAST_5_MINUTES = new TimeInterval(Duration.ofMinutes(5)); public static final TimeInterval LAST_30_MINUTES = new TimeInterval(Duration.ofMinutes(30)); public static final TimeInterval LAST_1_HOUR = new TimeInterval(Duration.ofHours(1)); public static final TimeInterval LAST_4_HOURS = new TimeInterval(Duration.ofHours(4)); public static final TimeInterval LAST_12_HOURS = new TimeInterval(Duration.ofHours(12)); public static final TimeInterval LAST_DAY = new TimeInterval(Duration.ofDays(1)); public static final TimeInterval LAST_2_DAYS = new TimeInterval(Duration.ofDays(2)); public static final TimeInterval LAST_3_DAYS = new TimeInterval(Duration.ofDays(3)); public static final TimeInterval LAST_7_DAYS = new TimeInterval(Duration.ofDays(7)); private static final ClientLogger LOGGER = new ClientLogger(TimeInterval.class); private static final String ERROR_MESSAGE = "%s is an invalid time interval. It must be in one of the " + "following ISO 8601 time interval formats: duration, startDuration/endTime, " + "startTime/endTime, startTime/endDuration"; private final Duration duration; private final OffsetDateTime startTime; private final OffsetDateTime endTime; /** * Creates an instance of {@link TimeInterval} using the provided duration. The duration is the interval that * starts from the provided duration and ends at the current time. * @param duration the duration for this query time span. */ public TimeInterval(Duration duration) { this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startTime = null; this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end {@link OffsetDateTime OffsetDateTimes}. * @param startTime The start time of the interval. * @param endTime The end time of the interval. */ public TimeInterval(OffsetDateTime startTime, OffsetDateTime endTime) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param startTime The start time of the interval. * @param duration The end duration of the interval. */ public TimeInterval(OffsetDateTime startTime, Duration duration) { this.startTime = Objects.requireNonNull(startTime, "'startTime' cannot be null"); this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.endTime = null; } /** * Creates an instance of {@link TimeInterval} using the start and end duration of the interval. * @param duration The duration of the interval. * @param endTime The end time of the interval. */ TimeInterval(Duration duration, OffsetDateTime endTime) { this.endTime = Objects.requireNonNull(endTime, "'endTime' cannot be null"); this.duration = Objects.requireNonNull(duration, "'duration' cannot be null"); this.startTime = null; } /** * Returns the duration of this {@link TimeInterval} instance. * @return the duration of this {@link TimeInterval} instance. */ public Duration getDuration() { return duration; } /** * Returns the start time of this {@link TimeInterval} instance. * @return the start time of this {@link TimeInterval} instance. */ public OffsetDateTime getStartTime() { if (startTime != null) { return startTime; } if (duration != null && endTime != null) { return endTime.minusNanos(duration.toNanos()); } return null; } /** * Returns the end time of this {@link TimeInterval} instance. * @return the end time of this {@link TimeInterval} instance. */ public OffsetDateTime getEndTime() { if (endTime != null) { return endTime; } if (startTime != null && duration != null) { return startTime.plusNanos(duration.toNanos()); } return null; } /** * Returns this {@link TimeInterval} in ISO 8601 string format. * @return ISO 8601 formatted string representation of this {@link TimeInterval} instance. */ public String toIso8601Format() { if (startTime != null && endTime != null) { return startTime + "/" + endTime; } if (startTime != null && duration != null) { return startTime + "/" + duration; } if (duration != null && endTime != null) { return duration + "/" + endTime; } return duration == null ? null : duration.toString(); } /** * This method takes an ISO 8601 formatted time interval string and returns an instance of {@link TimeInterval}. * @param value The ISO 8601 formatted time interval string. * @return An instance of {@link TimeInterval}. * @throws IllegalArgumentException if {@code value} is not in the correct format. */ public static TimeInterval parse(String value) { Objects.requireNonNull(value); String[] parts = value.split("/"); if (parts.length == 1) { Duration duration = parseDuration(parts[0]); if (duration == null || parts[0].length() + 1 == value.length()) { throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } return new TimeInterval(duration); } if (parts.length == 2) { Duration startDuration = parseDuration(parts[0]); OffsetDateTime startTime = parseTime(parts[0]); Duration endDuration = parseDuration(parts[1]); OffsetDateTime endTime = parseTime(parts[1]); if (startDuration != null && endTime != null) { return new TimeInterval(startDuration, endTime); } if (startTime != null && endTime != null) { return new TimeInterval(startTime, endTime); } if (startTime != null && endDuration != null) { return new TimeInterval(startTime, endDuration); } } throw LOGGER.logExceptionAsError( new IllegalArgumentException(String.format(ERROR_MESSAGE, value))); } @Override @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeInterval that = (TimeInterval) o; return Objects.equals(this.duration, that.duration) && Objects.equals(this.startTime, that.startTime) && Objects.equals(this.endTime, that.endTime); } @Override public int hashCode() { return Objects.hash(duration, startTime, endTime); } private static OffsetDateTime parseTime(String value) { try { return OffsetDateTime.parse(value); } catch (Exception exception) { return null; } } private static Duration parseDuration(String value) { try { return Duration.parse(value); } catch (Exception exception) { return null; } } }
Move this inside `try` block. This should be printed only if there's no exception when writing to file. #Resolved
public void generateReport() { System.out.println("Starting to write HTML report (" + OffsetDateTime.now() + ")"); out("<!DOCTYPE html>"); out("<html>"); out(" <head>"); out(" <title>Dependency Issues Report</title>"); out(" <meta charset=\"UTF-8\"/>"); out(" <style>"); try ( BufferedReader r = new BufferedReader(new InputStreamReader(BOMReport.class.getResourceAsStream("report.css")))) { r.lines().forEach(line -> out(" " + line)); } catch (Exception e) { System.out.println("Can't find file: " + BOMReport.class.getResource("report.css")); } out(" </style>"); out(" </head>"); out(" <body>"); out(" <center>"); out(" <h1>Dependency Conflicts Report</h1>"); out(" <p>This report analyzed all track 2 GA data plane libraries and found the following conflicts in its dependency management.<br/>" + "It is important to resolve these conflicts to ensure convergence of the dependencies.<br/></p>"); out(" <table>"); out(" <thead>"); out("<tr>"); out("<th>"); out("Dropped dependency"); out("</th>"); out("<th>"); out("Reasons"); out("</th>"); out("</tr>"); dependencyConflicts.keySet().stream().forEach(dependency -> { out("<tr>"); out("<td>"); out(dependency.toString()); out("</td>"); out("<td>"); dependencyConflicts.get(dependency).forEach(conflict -> { out(String.format("Includes dependency %s, Expected dependency %s", conflict.getActualDependency(), conflict.getExpectedDependency())); out("<br/>"); }); out("</td>"); out("</tr>"); }); out(" <small>Report generated at " + DateTimeFormatter.ofPattern("HH:mm:ss 'on' yyyy-MM-dd").format(LocalDateTime.now()) + "<br/>"); out(" </center>"); out(" </body>"); out("</html>"); File outFile = new File(reportFileName); try (BufferedWriter writer = new BufferedWriter(new FileWriter(outFile))) { writer.write(sb.toString()); } catch (IOException e) { e.printStackTrace(); } System.out.println("HTML report written to " + outFile + " (" + OffsetDateTime.now() + ")"); }
System.out.println("HTML report written to " + outFile + " (" + OffsetDateTime.now() + ")");
public void generateReport() { System.out.println("Starting to write HTML report (" + OffsetDateTime.now() + ")"); out("<!DOCTYPE html>"); out("<html>"); out(" <head>"); out(" <title>Dependency Issues Report</title>"); out(" <meta charset=\"UTF-8\"/>"); out(" <style>"); try ( BufferedReader r = new BufferedReader(new InputStreamReader(BOMReport.class.getResourceAsStream("report.css")))) { r.lines().forEach(line -> out(" " + line)); } catch (Exception e) { System.out.println("Can't find file: " + BOMReport.class.getResource("report.css")); } out(" </style>"); out(" </head>"); out(" <body>"); out(" <center>"); out(" <h1>Dependency Conflicts Report</h1>"); out(" <p>This report analyzed all track 2 GA data plane libraries and found the following conflicts in its dependency management.<br/>" + "It is important to resolve these conflicts to ensure convergence of the dependencies.<br/></p>"); out(" <table>"); out(" <thead>"); out("<tr>"); out("<th>"); out("Dropped dependency"); out("</th>"); out("<th>"); out("Reasons"); out("</th>"); out("</tr>"); dependencyConflicts.keySet().stream().forEach(dependency -> { out("<tr>"); out("<td>"); out(dependency.toString()); out("</td>"); out("<td>"); dependencyConflicts.get(dependency).forEach(conflict -> { out(String.format("Includes dependency %s, Expected dependency %s", conflict.getActualDependency(), conflict.getExpectedDependency())); out("<br/>"); }); out("</td>"); out("</tr>"); }); out(" <small>Report generated at " + DateTimeFormatter.ofPattern("HH:mm:ss 'on' yyyy-MM-dd").format(LocalDateTime.now()) + "<br/>"); out(" </center>"); out(" </body>"); out("</html>"); File outFile = new File(reportFileName); try (BufferedWriter writer = new BufferedWriter(new FileWriter(outFile))) { writer.write(sb.toString()); System.out.println("HTML report written to " + outFile + " (" + OffsetDateTime.now() + ")"); } catch (IOException e) { e.printStackTrace(); } }
class BOMReport { private final StringBuilder sb; Map<BomDependency, List<ConflictingDependency>> dependencyConflicts; private final String reportFileName; public BOMReport(String reportFileName) { sb = new StringBuilder(); dependencyConflicts = new HashMap<>(); this.reportFileName = reportFileName; } public void insertConflict(BomDependency dependencyWithConflict, ConflictingDependency conflictingDependency) { if (!dependencyConflicts.containsKey(dependencyWithConflict)) { dependencyConflicts.put(dependencyWithConflict, new ArrayList<>()); } dependencyConflicts.get(dependencyWithConflict).add(conflictingDependency); } private void out(String s) { sb.append(s); sb.append("\r\n"); } }
class BOMReport { private final StringBuilder sb; private final Map<BomDependency, List<ConflictingDependency>> dependencyConflicts; private final String reportFileName; public BOMReport(String reportFileName, Map<BomDependency, List<ConflictingDependency>> dependencyConflicts) { sb = new StringBuilder(); this.dependencyConflicts = dependencyConflicts; this.reportFileName = reportFileName; } private void out(String s) { sb.append(s); sb.append("\r\n"); } }
we can set the initial size to 2.
public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure Powershell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure Powershell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
List<PowershellManager> powershellManagers = new ArrayList<>();
public Mono<AccessToken> authenticateWithAzurePowerShell(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(2); PowershellManager defaultPowerShellManager = new PowershellManager(Platform.isWindows() ? DEFAULT_WINDOWS_PS_EXECUTABLE : DEFAULT_LINUX_PS_EXECUTABLE); PowershellManager legacyPowerShellManager = Platform.isWindows() ? new PowershellManager(LEGACY_WINDOWS_PS_EXECUTABLE) : null; List<PowershellManager> powershellManagers = new ArrayList<>(2); powershellManagers.add(defaultPowerShellManager); if (legacyPowerShellManager != null) { powershellManagers.add(legacyPowerShellManager); } return Flux.fromIterable(powershellManagers) .flatMap(powershellManager -> getAccessTokenFromPowerShell(request, powershellManager) .onErrorResume(t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( "Azure Powershell authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException("Azure Powershell authentication failed using default" + "powershell(pwsh) with following error: " + current.getMessage() + "\r\n" + "Azure Powershell authentication failed using powershell-core(powershell)" + " with following error: " + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
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 String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String clientSecret; private final InputStream certificate; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<PublicClientApplication>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<ConfidentialClientApplication>(() -> getConfidentialClientApplication()); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { InputStream pfxCertificateStream = getCertificateInputStream(); try { credential = ClientCredentialFactory.createFromCertificate( pfxCertificateStream, certificatePassword); } finally { if (pfxCertificateStream != null) { pfxCertificateStream.close(); } } } } catch (IOException | GeneralSecurityException e) { return Mono.error(logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else { return Mono.error(logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path"))); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(logger.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { if (isADFSTenant()) { return Mono.error(new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported.")); } JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> manager.runCommand("Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru") .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to use" + "Azure PowerShell Credential.")); } StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell.")); } try { Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(logger .logExceptionAsError(new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); })).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(MsalToken::new)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported.")); } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(new CredentialUnavailableException("Failed to acquire token with" + " VS code credential", t)); } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(logger.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", "UTF-8")); URL url = new URL(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw logger.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw logger.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw logger.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw logger.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw logger.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(getClass().getSimpleName(), connection, thumbprint); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the msi secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, "UTF-8")); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = Configuration.getGlobalConfiguration().get( Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, IdentityConstants.DEFAULT_IMDS_ENDPOINT); return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("%s?%s", endpoint, payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw logger.logExceptionAsError( new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw logger.logExceptionAsError( new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("%s?%s", endpoint, payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw logger.logExceptionAsError( new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new FileInputStream(certificatePath); } else if (certificate != null) { return certificate; } else { return null; } } }
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 String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_WINDOWS_PS_EXECUTABLE = "pwsh.exe"; private static final String LEGACY_WINDOWS_PS_EXECUTABLE = "powershell.exe"; private static final String DEFAULT_LINUX_PS_EXECUTABLE = "pwsh"; private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); private static final String IDENTITY_ENDPOINT_VERSION = "2019-08-01"; private static final String MSI_ENDPOINT_VERSION = "2017-09-01"; private static final String ADFS_TENANT = "adfs"; private static final String HTTP_LOCALHOST = "http: private static final String SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION = "2019-07-01-preview"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final String tenantId; private final String clientId; private final String clientSecret; private final InputStream certificate; private final String certificatePath; private final String certificatePassword; private HttpPipelineAdapter httpPipelineAdapter; private final SynchronizedAccessor<PublicClientApplication> publicClientApplicationAccessor; private final SynchronizedAccessor<ConfidentialClientApplication> confidentialClientApplicationAccessor; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param clientSecret the client secret of the application. * @param certificatePath the path to the PKCS12 or PEM certificate of the application. * @param certificate the PKCS12 or PEM certificate of the application. * @param certificatePassword the password protecting the PFX certificate. * @param isSharedTokenCacheCredential Indicate whether the credential is * {@link com.azure.identity.SharedTokenCacheCredential} or not. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, String clientSecret, String certificatePath, InputStream certificate, String certificatePassword, boolean isSharedTokenCacheCredential, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.clientSecret = clientSecret; this.certificatePath = certificatePath; this.certificate = certificate; this.certificatePassword = certificatePassword; this.options = options; this.publicClientApplicationAccessor = new SynchronizedAccessor<PublicClientApplication>(() -> getPublicClientApplication(isSharedTokenCacheCredential)); this.confidentialClientApplicationAccessor = new SynchronizedAccessor<ConfidentialClientApplication>(() -> getConfidentialClientApplication()); } private Mono<ConfidentialClientApplication> getConfidentialClientApplication() { return Mono.defer(() -> { if (clientId == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication."))); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; IClientCredential credential; if (clientSecret != null) { credential = ClientCredentialFactory.createFromSecret(clientSecret); } else if (certificate != null || certificatePath != null) { try { if (certificatePassword == null) { byte[] pemCertificateBytes = getCertificateBytes(); List<X509Certificate> x509CertificateList = CertificateUtil.publicKeyFromPem(pemCertificateBytes); PrivateKey privateKey = CertificateUtil.privateKeyFromPem(pemCertificateBytes); if (x509CertificateList.size() == 1) { credential = ClientCredentialFactory.createFromCertificate( privateKey, x509CertificateList.get(0)); } else { credential = ClientCredentialFactory.createFromCertificateChain( privateKey, x509CertificateList); } } else { InputStream pfxCertificateStream = getCertificateInputStream(); try { credential = ClientCredentialFactory.createFromCertificate( pfxCertificateStream, certificatePassword); } finally { if (pfxCertificateStream != null) { pfxCertificateStream.close(); } } } } catch (IOException | GeneralSecurityException e) { return Mono.error(logger.logExceptionAsError(new RuntimeException( "Failed to parse the certificate for the credential: " + e.getMessage(), e))); } } else { return Mono.error(logger.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path"))); } ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, credential); try { applicationBuilder = applicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { return Mono.error(logger.logExceptionAsWarning(new IllegalStateException(e))); } applicationBuilder.sendX5c(options.isIncludeX5c()); initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); applicationBuilder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { return Mono.error(logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t))); } } if (options.getRegionalAuthority() != null) { if (options.getRegionalAuthority() == RegionalAuthority.AUTO_DISCOVER_REGION) { applicationBuilder.autoDetectRegion(true); } else { applicationBuilder.azureRegion(options.getRegionalAuthority().toString()); } } ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> confidentialClientApplication) : Mono.just(confidentialClientApplication); }); } private Mono<PublicClientApplication> getPublicClientApplication(boolean sharedTokenCacheCredential) { return Mono.defer(() -> { if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } initializeHttpPipelineAdapter(); if (httpPipelineAdapter != null) { publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (!options.isCp1Disabled()) { Set<String> set = new HashSet<>(1); set.add("CP1"); publicClientApplicationBuilder.clientCapabilities(set); } return Mono.just(publicClientApplicationBuilder); }).flatMap(builder -> { TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); PersistentTokenCacheImpl tokenCache = null; if (tokenCachePersistenceOptions != null) { try { tokenCache = new PersistentTokenCacheImpl() .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) .setName(tokenCachePersistenceOptions.getName()); builder.setTokenCacheAccessAspect(tokenCache); } catch (Throwable t) { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } PublicClientApplication publicClientApplication = builder.build(); return tokenCache != null ? tokenCache.registerCache() .map(ignored -> publicClientApplication) : Mono.just(publicClientApplication); }); } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())).map(MsalToken::new); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { if (isADFSTenant()) { return Mono.error(new CredentialUnavailableException("IntelliJCredential " + "authentication unavailable. ADFS tenant/authorities are not supported.")); } JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters.RefreshTokenParametersBuilder refreshTokenParametersBuilder = RefreshTokenParameters.builder(new HashSet<>(request.getScopes()), refreshToken); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); refreshTokenParametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(refreshTokenParametersBuilder.build())) .map(MsalToken::new)); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException( "AzureCliCredential authentication unavailable. Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException( "AzureCliCredential authentication unavailable." + " Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new AccessToken(accessToken, expiresOn); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with Azure Power Shell. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ private Mono<AccessToken> getAccessTokenFromPowerShell(TokenRequestContext request, PowershellManager powershellManager) { return powershellManager.initSession() .flatMap(manager -> manager.runCommand("Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru") .flatMap(output -> { if (output.contains("The specified module 'Az.Accounts' with version '2.2.0' was not loaded " + "because no valid module file")) { return Mono.error(new CredentialUnavailableException( "Az.Account module with version >= 2.2.0 is not installed. It needs to be installed to use" + "Azure PowerShell Credential.")); } StringBuilder accessTokenCommand = new StringBuilder("Get-AzAccessToken -ResourceUrl "); accessTokenCommand.append(ScopeUtil.scopesToResource(request.getScopes())); accessTokenCommand.append(" | ConvertTo-Json"); return manager.runCommand(accessTokenCommand.toString()) .flatMap(out -> { if (out.contains("Run Connect-AzAccount to login")) { return Mono.error(new CredentialUnavailableException( "Run Connect-AzAccount to login to Azure account in PowerShell.")); } try { Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(out, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("Token"); String time = objectMap.get("ExpiresOn"); OffsetDateTime expiresOn = OffsetDateTime.parse(time) .withOffsetSameInstant(ZoneOffset.UTC); return Mono.just(new AccessToken(accessToken, expiresOn)); } catch (IOException e) { return Mono.error(logger .logExceptionAsError(new CredentialUnavailableException( "Encountered error when deserializing response from Azure Power Shell.", e))); } }); })).doFinally(ignored -> powershellManager.close()); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClient(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> confidentialClient.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build())) .map(MsalToken::new)); } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { UserNamePasswordParameters.UserNamePasswordParametersBuilder userNamePasswordParametersBuilder = UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); userNamePasswordParametersBuilder.claims(customClaimRequest); } return pc.acquireToken(userNamePasswordParametersBuilder.build()); } )).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and " + "password", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); parametersBuilder.forceRefresh(true); } if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return pc.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET))) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest .formatAsClaimsRequest(request.getClaims()); forceParametersBuilder.claims(customClaimRequest); } if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return pc.acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(MsalToken::new))); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return confidentialClientApplicationAccessor.getValue() .flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return confidentialClient.acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar)) .filter(t -> OffsetDateTime.now().isBefore(t.getExpiresAt().minus(REFRESH_OFFSET)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return publicClientApplicationAccessor.getValue().flatMap(pc -> Mono.fromFuture(() -> { DeviceCodeFlowParameters.DeviceCodeFlowParametersBuilder parametersBuilder = DeviceCodeFlowParameters.builder( new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept( new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return pc.acquireToken(parametersBuilder.build()); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { if (isADFSTenant()) { return Mono.error(new CredentialUnavailableException("VsCodeCredential " + "authentication unavailable. ADFS tenant/authorities are not supported.")); } VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters.RefreshTokenParametersBuilder parametersBuilder = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(pc.acquireToken(parametersBuilder.build())) .onErrorResume(t -> { if (t instanceof MsalInteractionRequiredException) { return Mono.error(new CredentialUnavailableException("Failed to acquire token with" + " VS code credential", t)); } return Mono.error(new ClientAuthenticationException("Failed to acquire token with" + " VS code credential", null, t)); }) .map(MsalToken::new)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { AuthorizationCodeParameters.AuthorizationCodeParametersBuilder parametersBuilder = AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); parametersBuilder.claims(customClaimRequest); } Mono<IAuthenticationResult> acquireToken; if (clientSecret != null) { acquireToken = confidentialClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } else { acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(parametersBuilder.build()))); } return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with authorization code", null, t)).map(MsalToken::new); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @param redirectUrl the redirect URL to listen on and receive security code * @param loginHint the username suggestion to pre-fill the login page's username/email address field * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, String loginHint) { URI redirectUri; String redirect; if (port != null) { redirect = HTTP_LOCALHOST + ":" + port; } else if (redirectUrl != null) { redirect = redirectUrl; } else { redirect = HTTP_LOCALHOST; } try { redirectUri = new URI(redirect); } catch (URISyntaxException e) { return Mono.error(logger.logExceptionAsError(new RuntimeException(e))); } InteractiveRequestParameters.InteractiveRequestParametersBuilder builder = InteractiveRequestParameters.builder(redirectUri) .scopes(new HashSet<>(request.getScopes())) .prompt(Prompt.SELECT_ACCOUNT); if (request.getClaims() != null) { ClaimsRequest customClaimRequest = CustomClaimRequest.formatAsClaimsRequest(request.getClaims()); builder.claims(customClaimRequest); } if (loginHint != null) { builder.loginHint(loginHint); } Mono<IAuthenticationResult> acquireToken = publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.acquireToken(builder.build()))); return acquireToken.onErrorMap(t -> new ClientAuthenticationException( "Failed to acquire token with Interactive Browser Authentication.", null, t)).map(MsalToken::new); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return publicClientApplicationAccessor.getValue() .flatMap(pc -> Mono.fromFuture(() -> pc.getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithPublicClientCache(request, requestedAccount); })); } /** * Asynchronously acquire a token from the Azure Arc Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToArcManagedIdentityEndpoint(String identityEndpoint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(ScopeUtil.scopesToResource(request.getScopes()), "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2019-11-01", "UTF-8")); URL url = new URL(String.format("%s?%s", identityEndpoint, payload)); String secretKey = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\\A"); } catch (IOException e) { if (connection == null) { throw logger.logExceptionAsError(new ClientAuthenticationException("Failed to initialize " + "Http URL connection to the endpoint.", null, e)); } int status = connection.getResponseCode(); if (status != 401) { throw logger.logExceptionAsError(new ClientAuthenticationException(String.format("Expected a 401" + " Unauthorized response from Azure Arc Managed Identity Endpoint, received: %d", status), null, e)); } String realm = connection.getHeaderField("WWW-Authenticate"); if (realm == null) { throw logger.logExceptionAsError(new ClientAuthenticationException("Did not receive a value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } int separatorIndex = realm.indexOf("="); if (separatorIndex == -1) { throw logger.logExceptionAsError(new ClientAuthenticationException("Did not receive a correct value" + " for WWW-Authenticate header in the response from Azure Arc Managed Identity Endpoint", null)); } String secretKeyPath = realm.substring(separatorIndex + 1); secretKey = new String(Files.readAllBytes(Paths.get(secretKeyPath)), StandardCharsets.UTF_8); } finally { if (connection != null) { connection.disconnect(); } } if (secretKey == null) { throw logger.logExceptionAsError(new ClientAuthenticationException("Did not receive a secret value" + " in the response from Azure Arc Managed Identity Endpoint", null)); } try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", secretKey)); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner scanner = new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\\A"); String result = scanner.hasNext() ? scanner.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Azure Service Fabric Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToServiceFabricManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String thumbprint, TokenRequestContext request) { return Mono.fromCallable(() -> { HttpsURLConnection connection = null; String endpoint = identityEndpoint; String headerValue = identityHeader; String endpointVersion = SERVICE_FABRIC_MANAGED_IDENTITY_API_VERSION; String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", endpoint, payload)); connection = (HttpsURLConnection) url.openConnection(); IdentitySslUtil.addTrustedCertificateThumbprint(getClass().getSimpleName(), connection, thumbprint); connection.setRequestMethod("GET"); if (headerValue != null) { connection.setRequestProperty("Secret", headerValue); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param identityEndpoint the Identity endpoint to acquire token from * @param identityHeader the identity header to acquire token with * @param msiEndpoint the MSI endpoint to acquire token from * @param msiSecret the msi secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String identityEndpoint, String identityHeader, String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String endpoint; String headerValue; String endpointVersion; if (identityEndpoint != null) { endpoint = identityEndpoint; headerValue = identityHeader; endpointVersion = IDENTITY_ENDPOINT_VERSION; } else { endpoint = msiEndpoint; headerValue = msiSecret; endpointVersion = MSI_ENDPOINT_VERSION; } String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode(endpointVersion, "UTF-8")); if (clientId != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { payload.append("&client_id="); } else { payload.append("&clientid="); } payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", endpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (headerValue != null) { if (endpointVersion.equals(IDENTITY_ENDPOINT_VERSION)) { connection.setRequestProperty("X-IDENTITY-HEADER", headerValue); } else { connection.setRequestProperty("Secret", headerValue); } } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } String endpoint = Configuration.getGlobalConfiguration().get( Configuration.PROPERTY_AZURE_POD_IDENTITY_TOKEN_URL, IdentityConstants.DEFAULT_IMDS_ENDPOINT); return checkIMDSAvailable(endpoint).flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("%s?%s", endpoint, payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode; try { responseCode = connection.getResponseCode(); } catch (Exception e) { throw logger.logExceptionAsError( new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } if (responseCode == 400) { throw logger.logExceptionAsError( new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established.", null)); } if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable(String endpoint) { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("%s?%s", endpoint, payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (Exception e) { throw logger.logExceptionAsError( new CredentialUnavailableException( "ManagedIdentityCredential authentication unavailable. " + "Connection to IMDS endpoint cannot be established, " + e.getMessage() + ".", e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } private CompletableFuture<IAuthenticationResult> getFailedCompletableFuture(Exception e) { CompletableFuture<IAuthenticationResult> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(e); return completableFuture; } private void initializeHttpPipelineAdapter() { HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); } else if (options.getProxyOptions() == null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); } } } /** * Get the configured tenant id. * * @return the tenant id. */ public String getTenantId() { return tenantId; } /** * Get the configured client id. * * @return the client id. */ public String getClientId() { return clientId; } private boolean isADFSTenant() { return this.tenantId.equals(ADFS_TENANT); } private byte[] getCertificateBytes() throws IOException { if (certificatePath != null) { return Files.readAllBytes(Paths.get(certificatePath)); } else if (certificate != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = certificate.read(buffer, 0, buffer.length); while (read != -1) { outputStream.write(buffer, 0, read); read = certificate.read(buffer, 0, buffer.length); } return outputStream.toByteArray(); } else { return new byte[0]; } } private InputStream getCertificateInputStream() throws IOException { if (certificatePath != null) { return new FileInputStream(certificatePath); } else if (certificate != null) { return certificate; } else { return null; } } }
keep consistency with other action behavior.
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { return new JobManifestTasks() .setEntityRecognitionTasks(actions.getRecognizeEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask.setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); return entitiesTask; }).collect(Collectors.toList())) .setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask.setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) ); return piiTask; }).collect(Collectors.toList())) .setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesActions() == null ? null : StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask.setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) ); return keyPhrasesTask; }).collect(Collectors.toList())) .setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask.setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return entityLinkingTask; }).collect(Collectors.toList())) .setSentimentAnalysisTasks(actions.getAnalyzeSentimentActions() == null ? null : StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask.setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return sentimentAnalysisTask; }).collect(Collectors.toList())); }
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { return new JobManifestTasks() .setEntityRecognitionTasks(actions.getRecognizeEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask.setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); return entitiesTask; }).collect(Collectors.toList())) .setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask.setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) ); return piiTask; }).collect(Collectors.toList())) .setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesActions() == null ? null : StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask.setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) ); return keyPhrasesTask; }).collect(Collectors.toList())) .setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask.setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return entityLinkingTask; }).collect(Collectors.toList())) .setSentimentAnalysisTasks(actions.getAnalyzeSentimentActions() == null ? null : StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask.setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return sentimentAnalysisTask; }).collect(Collectors.toList())); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String REGEX_ACTION_ERROR_TARGET = " + "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)"; private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String REGEX_ACTION_ERROR_TARGET = " + "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)"; private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
consider adding the addition of string index type default to utf16 for entity linking in the changelog
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { return new JobManifestTasks() .setEntityRecognitionTasks(actions.getRecognizeEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask.setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); return entitiesTask; }).collect(Collectors.toList())) .setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask.setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) ); return piiTask; }).collect(Collectors.toList())) .setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesActions() == null ? null : StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask.setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) ); return keyPhrasesTask; }).collect(Collectors.toList())) .setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask.setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return entityLinkingTask; }).collect(Collectors.toList())) .setSentimentAnalysisTasks(actions.getAnalyzeSentimentActions() == null ? null : StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask.setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return sentimentAnalysisTask; }).collect(Collectors.toList())); }
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { return new JobManifestTasks() .setEntityRecognitionTasks(actions.getRecognizeEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask.setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); return entitiesTask; }).collect(Collectors.toList())) .setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask.setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) ); return piiTask; }).collect(Collectors.toList())) .setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesActions() == null ? null : StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask.setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) ); return keyPhrasesTask; }).collect(Collectors.toList())) .setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask.setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return entityLinkingTask; }).collect(Collectors.toList())) .setSentimentAnalysisTasks(actions.getAnalyzeSentimentActions() == null ? null : StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask.setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return sentimentAnalysisTask; }).collect(Collectors.toList())); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String REGEX_ACTION_ERROR_TARGET = " + "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)"; private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String REGEX_ACTION_ERROR_TARGET = " + "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)"; private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
same for sentiment
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { return new JobManifestTasks() .setEntityRecognitionTasks(actions.getRecognizeEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask.setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); return entitiesTask; }).collect(Collectors.toList())) .setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask.setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) ); return piiTask; }).collect(Collectors.toList())) .setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesActions() == null ? null : StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask.setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) ); return keyPhrasesTask; }).collect(Collectors.toList())) .setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask.setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return entityLinkingTask; }).collect(Collectors.toList())) .setSentimentAnalysisTasks(actions.getAnalyzeSentimentActions() == null ? null : StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask.setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return sentimentAnalysisTask; }).collect(Collectors.toList())); }
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) { return new JobManifestTasks() .setEntityRecognitionTasks(actions.getRecognizeEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntitiesTask entitiesTask = new EntitiesTask(); entitiesTask.setParameters( new EntitiesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT)); return entitiesTask; }).collect(Collectors.toList())) .setEntityRecognitionPiiTasks(actions.getRecognizePiiEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizePiiEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final PiiTask piiTask = new PiiTask(); piiTask.setParameters( new PiiTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setDomain(PiiTaskParametersDomain.fromString( action.getDomainFilter() == null ? null : action.getDomainFilter().toString())) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) .setPiiCategories(toCategoriesFilter(action.getCategoriesFilter())) ); return piiTask; }).collect(Collectors.toList())) .setKeyPhraseExtractionTasks(actions.getExtractKeyPhrasesActions() == null ? null : StreamSupport.stream(actions.getExtractKeyPhrasesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final KeyPhrasesTask keyPhrasesTask = new KeyPhrasesTask(); keyPhrasesTask.setParameters( new KeyPhrasesTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) ); return keyPhrasesTask; }).collect(Collectors.toList())) .setEntityLinkingTasks(actions.getRecognizeLinkedEntitiesActions() == null ? null : StreamSupport.stream(actions.getRecognizeLinkedEntitiesActions().spliterator(), false).map( action -> { if (action == null) { return null; } final EntityLinkingTask entityLinkingTask = new EntityLinkingTask(); entityLinkingTask.setParameters( new EntityLinkingTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return entityLinkingTask; }).collect(Collectors.toList())) .setSentimentAnalysisTasks(actions.getAnalyzeSentimentActions() == null ? null : StreamSupport.stream(actions.getAnalyzeSentimentActions().spliterator(), false).map( action -> { if (action == null) { return null; } final SentimentAnalysisTask sentimentAnalysisTask = new SentimentAnalysisTask(); sentimentAnalysisTask.setParameters( new SentimentAnalysisTaskParameters() .setModelVersion(action.getModelVersion()) .setLoggingOptOut(action.isServiceLogsDisabled()) .setStringIndexType(StringIndexType.UTF16CODE_UNIT) ); return sentimentAnalysisTask; }).collect(Collectors.toList())); }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String REGEX_ACTION_ERROR_TARGET = " + "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)"; private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
class AnalyzeActionsAsyncClient { private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks"; private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks"; private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks"; private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks"; private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks"; private static final String REGEX_ACTION_ERROR_TARGET = " + "entityRecognitionPiiTasks|entityRecognitionTasks|entityLinkingTasks|sentimentAnalysisTasks)/(\\d+)"; private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class); private final TextAnalyticsClientImpl service; private static final Pattern PATTERN; static { PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE); } AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) { this.service = service; } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail textAnalyticsOperationResult = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper .setOperationId(textAnalyticsOperationResult, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return textAnalyticsOperationResult; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable( Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options, Context context) { try { inputDocumentsValidation(documents); options = getNotNullAnalyzeActionsOptions(options); final Context finalContext = getNotNullContext(context) .addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE); final AnalyzeBatchInput analyzeBatchInput = new AnalyzeBatchInput() .setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents))) .setTasks(getJobManifestTasks(actions)); analyzeBatchInput.setDisplayName(actions.getDisplayName()); final boolean finalIncludeStatistics = options.isIncludeStatistics(); return new PollerFlux<>( DEFAULT_POLL_INTERVAL, activationOperation( service.analyzeWithResponseAsync(analyzeBatchInput, finalContext) .map(analyzeResponse -> { final AnalyzeActionsOperationDetail operationDetail = new AnalyzeActionsOperationDetail(); AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail, parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation())); return operationDetail; })), pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId, finalIncludeStatistics, null, null, finalContext)), (activationResponse, pollingContext) -> Mono.error(new RuntimeException("Cancellation is not supported.")), fetchingOperationIterable( operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage( operationId, null, null, finalIncludeStatistics, finalContext)))) ); } catch (RuntimeException ex) { return PollerFlux.error(ex); } } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>> activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) { return pollingContext -> { try { return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>> pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) { return pollingContext -> { try { final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse = pollingContext.getLatestResponse(); final String operationId = operationResultPollResponse.getValue().getOperationId(); return pollingFunction.apply(operationId) .flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>> fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>> fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) { return pollingContext -> { try { final String operationId = pollingContext.getLatestResponse().getValue().getOperationId(); return fetchingFunction.apply(operationId); } catch (RuntimeException ex) { return monoError(logger, ex); } }; } AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip, boolean showStats, Context context) { return new AnalyzeActionsResultPagedFlux( () -> (continuationToken, pageSize) -> getPage(continuationToken, operationId, top, skip, showStats, context).flux()); } Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top, Integer skip, boolean showStats, Context context) { if (continuationToken != null) { final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken); final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null); final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null); final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false); return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } else { return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context) .map(this::toAnalyzeActionsResultPagedResponse) .onErrorMap(Utility::mapToHttpResponseExceptionIfExists); } } private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) { final AnalyzeJobState analyzeJobState = response.getValue(); return new PagedResponseBase<Void, AnalyzeActionsResult>( response.getRequest(), response.getStatusCode(), response.getHeaders(), Arrays.asList(toAnalyzeActionsResult(analyzeJobState)), analyzeJobState.getNextLink(), null); } private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) { TasksStateTasks tasksStateTasks = analyzeJobState.getTasks(); final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems = tasksStateTasks.getEntityRecognitionPiiTasks(); final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems = tasksStateTasks.getEntityRecognitionTasks(); final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks = tasksStateTasks.getKeyPhraseExtractionTasks(); final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems = tasksStateTasks.getEntityLinkingTasks(); final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems = tasksStateTasks.getSentimentAnalysisTasks(); List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>(); List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>(); List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>(); List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>(); List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) { for (int i = 0; i < entityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i); final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult(); final EntitiesResult results = taskItem.getResults(); if (results != null) { RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeEntitiesResultCollectionResponse(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(piiTasksItems)) { for (int i = 0; i < piiTasksItems.size(); i++) { final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i); final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult(); final PiiResult results = taskItem.getResults(); if (results != null) { RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizePiiEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizePiiEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) { for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) { final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i); final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult(); final KeyPhraseResult results = taskItem.getResults(); if (results != null) { ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult, toExtractKeyPhrasesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); extractKeyPhrasesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) { for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) { final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i); final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); final EntityLinkingResult results = taskItem.getResults(); if (results != null) { RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult, toRecognizeLinkedEntitiesResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); recognizeLinkedEntitiesActionResults.add(actionResult); } } if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) { for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) { final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i); final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult(); final SentimentResponse results = taskItem.getResults(); if (results != null) { AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult, toAnalyzeSentimentResultCollection(results)); } TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult, taskItem.getLastUpdateDateTime()); analyzeSentimentActionResults.add(actionResult); } } final List<TextAnalyticsError> errors = analyzeJobState.getErrors(); if (!CoreUtils.isNullOrEmpty(errors)) { for (TextAnalyticsError error : errors) { final String[] targetPair = parseActionErrorTarget(error.getTarget()); final String taskName = targetPair[0]; final Integer taskIndex = Integer.valueOf(targetPair[1]); final TextAnalyticsActionResult actionResult; if (ENTITY_RECOGNITION_TASKS.equals(taskName)) { actionResult = recognizeEntitiesActionResults.get(taskIndex); } else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) { actionResult = recognizePiiEntitiesActionResults.get(taskIndex); } else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) { actionResult = extractKeyPhrasesActionResults.get(taskIndex); } else if (ENTITY_LINKING_TASKS.equals(taskName)) { actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex); } else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) { actionResult = analyzeSentimentActionResults.get(taskIndex); } else { throw logger.logExceptionAsError(new RuntimeException( "Invalid task name in target reference, " + taskName)); } TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true); TextAnalyticsActionResultPropertiesHelper.setError(actionResult, new com.azure.ai.textanalytics.models.TextAnalyticsError( TextAnalyticsErrorCode.fromString( error.getCode() == null ? null : error.getCode().toString()), error.getMessage(), null)); } } final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult, IterableStream.of(recognizePiiEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult, IterableStream.of(extractKeyPhrasesActionResults)); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult, IterableStream.of(recognizeLinkedEntitiesActionResults)); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult, IterableStream.of(analyzeSentimentActionResults)); return analyzeActionsResult; } private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse( Response<AnalyzeJobState> analyzeJobStateResponse, PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) { LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) { switch (analyzeJobStateResponse.getValue().getStatus()) { case NOT_STARTED: case RUNNING: status = LongRunningOperationStatus.IN_PROGRESS; break; case SUCCEEDED: status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; break; case CANCELLED: status = LongRunningOperationStatus.USER_CANCELLED; break; default: status = LongRunningOperationStatus.fromString( analyzeJobStateResponse.getValue().getStatus().toString(), true); break; } } AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getDisplayName()); AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getCreatedDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getExpirationDateTime()); AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(), analyzeJobStateResponse.getValue().getLastUpdateDateTime()); final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks(); AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(), tasksResult.getFailed()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(), tasksResult.getInProgress()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded( operationResultPollResponse.getValue(), tasksResult.getCompleted()); AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(), tasksResult.getTotal()); return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue())); } private Context getNotNullContext(Context context) { return context == null ? Context.NONE : context; } private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) { return options == null ? new AnalyzeActionsOptions() : options; } private String[] parseActionErrorTarget(String targetReference) { if (CoreUtils.isNullOrEmpty(targetReference)) { throw logger.logExceptionAsError(new RuntimeException( "Expected an error with a target field referencing an action but did not get one")); } final Matcher matcher = PATTERN.matcher(targetReference); String[] taskNameIdPair = new String[2]; while (matcher.find()) { taskNameIdPair[0] = matcher.group(1); taskNameIdPair[1] = matcher.group(2); } return taskNameIdPair; } }
does Java usually sets the default in the client library? In .NET, if the user didn't set a value for a parameter, we just don't pass it to the service, and let the service decide what the default is
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
return disableServiceLogs == null ? true : disableServiceLogs;
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of {@code disableServiceLogs}. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of {@code disableServiceLogs}. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of service logs disable status. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of service logs disable status. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
and why do you set it for 2 tasks and not the others?
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
return disableServiceLogs == null ? true : disableServiceLogs;
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of {@code disableServiceLogs}. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of {@code disableServiceLogs}. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of service logs disable status. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of service logs disable status. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
If it is an object `Boolean`, it is nullable. A primitive boolean can't be null. The default value for a `Boolean` is `null`, the default value for a primitive `boolean` is `false`. So since we already GAed with `boolean`, we can't change it to `Boolean`. And the default value of `disableServiceLogs` is `true` in healthcare and pii tasks. So only these two need to set the default value to true
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
return disableServiceLogs == null ? true : disableServiceLogs;
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of {@code disableServiceLogs}. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of {@code disableServiceLogs}. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of service logs disable status. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of service logs disable status. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
Usually, we don't set the default value for an optional REST request parameter. If the type is `Boolean`, then we are the same behavior as .NET but unfortunately, a primitive `boolean` is GAed.
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
return disableServiceLogs == null ? true : disableServiceLogs;
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of {@code disableServiceLogs}. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of {@code disableServiceLogs}. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of service logs disable status. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of service logs disable status. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
I see. Do you know why Java went with `boolean`?
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
return disableServiceLogs == null ? true : disableServiceLogs;
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of {@code disableServiceLogs}. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of {@code disableServiceLogs}. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of service logs disable status. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of service logs disable status. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
I believed it is the uncaught attention that I missed. It is expected to have default to false at some point, but it is not the case anymore.
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
return disableServiceLogs == null ? true : disableServiceLogs;
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of {@code disableServiceLogs}. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of {@code disableServiceLogs}. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of service logs disable status. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of service logs disable status. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
No worries. I missed it because I didn't know about nullable in Java. But now we all know better and fixes are being made. Thanks Shawn!
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
return disableServiceLogs == null ? true : disableServiceLogs;
public boolean isServiceLogsDisabled() { return disableServiceLogs == null ? true : disableServiceLogs; }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of {@code disableServiceLogs}. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of {@code disableServiceLogs}. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
class AnalyzeHealthcareEntitiesOptions extends TextAnalyticsRequestOptions { private Boolean disableServiceLogs; /** * Sets the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". * If a model-version is not specified, the API will default to the latest, non-preview version. * * @param modelVersion The model version. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setModelVersion(String modelVersion) { super.setModelVersion(modelVersion); return this; } /** * Sets the value of {@code includeStatistics}. * * @param includeStatistics If a boolean value was specified in the request this field will contain * information about the document payload. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setIncludeStatistics(boolean includeStatistics) { super.setIncludeStatistics(includeStatistics); return this; } /** * Gets the value of service logs disable status. The default value of this property is 'true'. This means, * Text Analytics service won't log your input text. Setting this property to 'false', enables logging your input * text for 48 hours, solely to allow for troubleshooting issues. * * @return true if logging input text service are disabled. */ @Override /** * Sets the value of service logs disable status. * * @param disableServiceLogs The default value of this property is 'true'. This means, Text Analytics service * does not log your input text. Setting this property to 'false', enables the service to log your text input for * 48 hours, solely to allow for troubleshooting issues. * * @return The {@link AnalyzeHealthcareEntitiesOptions} object itself. */ @Override public AnalyzeHealthcareEntitiesOptions setServiceLogsDisabled(boolean disableServiceLogs) { this.disableServiceLogs = disableServiceLogs; return this; } }
Do you need to wrap in Mono.just()? I think `client.issueRelayConfiguration(body)` returns Mono directly
public Mono<CommunicationRelayConfiguration> getRelayConfiguration(CommunicationUserIdentifier communicationUser) { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return Mono.just(client.issueRelayConfiguration(body)); }
return Mono.just(client.issueRelayConfiguration(body));
public Mono<CommunicationRelayConfiguration> getRelayConfiguration(CommunicationUserIdentifier communicationUser) { return this.getRelayConfigurationWithResponse(communicationUser).flatMap(FluxUtil::toMono); }
class CommunicationRelayAsyncClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); CommunicationRelayAsyncClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser) { try { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfigurationWithResponseAsync(body) .onErrorMap(CommunicationErrorResponseException.class, e -> translateException(e)) .flatMap( (Response<CommunicationRelayConfiguration> response) -> { return Mono.just( new SimpleResponse<CommunicationRelayConfiguration>( response, response.getValue())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private CommunicationErrorResponseException translateException(CommunicationErrorResponseException exception) { CommunicationErrorResponse error = null; if (exception.getValue() != null) { error = exception.getValue(); } return new CommunicationErrorResponseException(exception.getMessage(), exception.getResponse(), error); } }
class CommunicationRelayAsyncClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); CommunicationRelayAsyncClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser) { return withContext(context -> getRelayConfigurationWithResponse(communicationUser, context)); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The created Communication Relay Configuration. */ Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { context = context == null ? Context.NONE : context; try { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfigurationWithResponseAsync(body, context) .onErrorMap(CommunicationErrorResponseException.class, e -> e); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Lines 63-68 is usually to convert the response value to another type and putting it into Response<>. I don't see that needed here. I think you can just remove these lines here.
public Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser) { try { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfigurationWithResponseAsync(body) .onErrorMap(CommunicationErrorResponseException.class, e -> translateException(e)) .flatMap( (Response<CommunicationRelayConfiguration> response) -> { return Mono.just( new SimpleResponse<CommunicationRelayConfiguration>( response, response.getValue())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
response.getValue()));
new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfigurationWithResponseAsync(body, context) .onErrorMap(CommunicationErrorResponseException.class, e -> e); } catch (RuntimeException ex) { return monoError(logger, ex); }
class CommunicationRelayAsyncClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); CommunicationRelayAsyncClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CommunicationRelayConfiguration> getRelayConfiguration(CommunicationUserIdentifier communicationUser) { CommunicationRelayConfigurationRequest body = private CommunicationErrorResponseException translateException(CommunicationErrorResponseException exception) { CommunicationErrorResponse error = null; if (exception.getValue() != null) { error = exception.getValue(); } return new CommunicationErrorResponseException(exception.getMessage(), exception.getResponse(), error); } }
class CommunicationRelayAsyncClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); CommunicationRelayAsyncClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CommunicationRelayConfiguration> getRelayConfiguration(CommunicationUserIdentifier communicationUser) { return this.getRelayConfigurationWithResponse(communicationUser).flatMap(FluxUtil::toMono); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser) { return withContext(context -> getRelayConfigurationWithResponse(communicationUser, context)); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The created Communication Relay Configuration. */ Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { context = context == null ? Context.NONE : context; try { CommunicationRelayConfigurationRequest body = } }
I think you can just return the response right away right? Why do you need lines 66-68?
public Response<CommunicationRelayConfiguration> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { context = context == null ? Context.NONE : context; CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); Response<CommunicationRelayConfiguration> response = client.issueRelayConfigurationWithResponseAsync(body, context).block(); if (response == null || response.getValue() == null) { throw logger.logExceptionAsError(new IllegalStateException("Service failed to return a response or expected value.")); } return new SimpleResponse<CommunicationRelayConfiguration>( response, response.getValue()); }
return new SimpleResponse<CommunicationRelayConfiguration>(
public Response<CommunicationRelayConfiguration> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { Response<CommunicationRelayConfiguration> response = client.getRelayConfigurationWithResponse(communicationUser, context).block(); return response; }
class CommunicationRelayClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayClient.class); CommunicationRelayClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRelayConfiguration getRelayConfiguration(CommunicationUserIdentifier communicationUser) { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfiguration(body); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The obtained Communication Relay Configuration */ }
class CommunicationRelayClient { private final CommunicationRelayAsyncClient client; private final ClientLogger logger = new ClientLogger(CommunicationRelayClient.class); CommunicationRelayClient(CommunicationRelayAsyncClient communicationNetworkingClient) { client = communicationNetworkingClient; } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRelayConfiguration getRelayConfiguration(CommunicationUserIdentifier communicationUser) { return client.getRelayConfiguration(communicationUser).block(); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) }
Are these live tests? If so, where are the recorded files for these tests? They need to be checked in as well
public void createRelayClientUsingManagedIdentity(HttpClient httpClient) { try { CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); client = setupClient(builder, "createRelayClientUsingManagedIdentitySync"); assertNotNull(client); String connectionString = System.getenv("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING"); CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder().connectionString(connectionString).buildClient(); CommunicationUserIdentifier user = communicationIdentityClient.createUser(); CommunicationRelayConfiguration config = client.getRelayConfiguration(user); List<CommunicationIceServer> iceServers = config.getIceServers(); assertNotNull(config); assertNotNull(config.getExpiresOn()); System.out.println("Expires on:" + config.getExpiresOn()); for (CommunicationIceServer iceS : iceServers) { assertNotNull(iceS.getUrls()); System.out.println("URLS: " + iceS.getUrls()); assertNotNull(iceS.getUsername()); System.out.println("Username: " + iceS.getUsername()); assertNotNull(iceS.getCredential()); System.out.println("credential: " + iceS.getCredential()); } } catch (Exception e) { System.out.println("Exception: " + e); } }
public void createRelayClientUsingManagedIdentity(HttpClient httpClient) { try { setupTest(httpClient); CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); client = setupClient(builder, "createRelayClientUsingManagedIdentitySync"); assertNotNull(client); CommunicationRelayConfiguration config = client.getRelayConfiguration(user); List<CommunicationIceServer> iceServers = config.getIceServers(); assertNotNull(config); assertNotNull(config.getExpiresOn()); for (CommunicationIceServer iceS : iceServers) { assertNotNull(iceS.getUrls()); assertNotNull(iceS.getUsername()); assertNotNull(iceS.getCredential()); } } catch (Exception e) { System.out.println("Exception: " + e); } }
class CommunicationRelayTests extends CommunicationRelayClientTestBase { private CommunicationRelayClient client; @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRelayClientUsingConnectionString(HttpClient httpClient) { CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); client = setupClient(builder, "createIdentityClientUsingConnectionStringSync"); assertNotNull(client); String connectionString = System.getenv("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING"); CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationUserIdentifier user = communicationIdentityClient.createUser(); CommunicationRelayConfiguration config; try { config = client.getRelayConfiguration(user); List<CommunicationIceServer> iceServers = config.getIceServers(); assertNotNull(config); assertNotNull(config.getExpiresOn()); for (CommunicationIceServer iceS : iceServers) { assertNotNull(iceS.getUrls()); System.out.println("Urls: " + iceS.getUrls()); assertNotNull(iceS.getUsername()); System.out.println("Username: " + iceS.getUsername()); assertNotNull(iceS.getCredential()); System.out.println("Credential: " + iceS.getCredential()); } } catch (Exception e) { e.printStackTrace(); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRelayConfigWithResponse(HttpClient httpClient) { CommunicationRelayClientBuilder builder = createClientBuilder(httpClient); client = setupClient(builder, "getRelayConfigWithResponse"); CommunicationIdentityClientBuilder identityBuilder = createIdentityClientBuilder(httpClient); CommunicationIdentityClient communicationIdentityClient = setupIdentityClient(identityBuilder, "getRelayConfigWithResponse"); CommunicationUserIdentifier user = communicationIdentityClient.createUser(); Response<CommunicationRelayConfiguration> response; try { response = client.getRelayConfigurationWithResponse(user, Context.NONE); List<CommunicationIceServer> iceServers = response.getValue().getIceServers(); assertNotNull(response.getValue()); assertEquals(200, response.getStatusCode(), "Expect status code to be 200"); assertNotNull(response.getValue().getExpiresOn()); System.out.println("Expires on:" + response.getValue().getExpiresOn()); for (CommunicationIceServer iceS : iceServers) { assertNotNull(iceS.getUrls()); System.out.println("URLS" + iceS.getUrls()); assertNotNull(iceS.getUsername()); System.out.println("Username" + iceS.getUsername()); assertNotNull(iceS.getCredential()); System.out.println("credential" + iceS.getCredential()); } } catch (Exception e) { e.printStackTrace(); } } private CommunicationRelayClient setupClient(CommunicationRelayClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } private CommunicationIdentityClient setupIdentityClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicyIdentity(builder, testName).buildClient(); } }
class CommunicationRelayTests extends CommunicationRelayClientTestBase { private CommunicationRelayClient client; private CommunicationUserIdentifier user; @Override protected void afterTest() { super.afterTest(); } private void setupTest(HttpClient httpClient) { CommunicationIdentityClient communicationIdentityClient = createIdentityClientBuilder(httpClient).buildClient(); user = communicationIdentityClient.createUser(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRelayClientUsingConnectionString(HttpClient httpClient) { try { setupTest(httpClient); CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); client = setupClient(builder, "createIdentityClientUsingConnectionStringSync"); assertNotNull(client); CommunicationRelayConfiguration config = client.getRelayConfiguration(user); List<CommunicationIceServer> iceServers = config.getIceServers(); assertNotNull(config); assertNotNull(config.getExpiresOn()); for (CommunicationIceServer iceS : iceServers) { assertNotNull(iceS.getUrls()); assertNotNull(iceS.getUsername()); assertNotNull(iceS.getCredential()); } } catch (Exception e) { e.printStackTrace(); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRelayConfigWithResponse(HttpClient httpClient) { try { setupTest(httpClient); CommunicationRelayClientBuilder builder = createClientBuilder(httpClient); client = setupClient(builder, "getRelayConfigWithResponse"); Response<CommunicationRelayConfiguration> response; response = client.getRelayConfigurationWithResponse(user, Context.NONE); List<CommunicationIceServer> iceServers = response.getValue().getIceServers(); assertNotNull(response.getValue()); assertEquals(200, response.getStatusCode(), "Expect status code to be 200"); assertNotNull(response.getValue().getExpiresOn()); for (CommunicationIceServer iceS : iceServers) { assertNotNull(iceS.getUrls()); assertNotNull(iceS.getUsername()); assertNotNull(iceS.getCredential()); } } catch (Exception e) { e.printStackTrace(); } } private CommunicationRelayClient setupClient(CommunicationRelayClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildClient(); } }
In what scenarios do we see response or response.getValue() being null? We should provide a more useful error message here for user to troubleshoot when this happens.
public Response<CommunicationRelayConfiguration> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { context = context == null ? Context.NONE : context; CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); Response<CommunicationRelayConfiguration> response = client.issueRelayConfigurationWithResponseAsync(body, context).block(); if (response == null || response.getValue() == null) { throw logger.logExceptionAsError(new IllegalStateException("Service failed to return a response or expected value.")); } return new SimpleResponse<CommunicationRelayConfiguration>( response, response.getValue()); }
if (response == null || response.getValue() == null) {
public Response<CommunicationRelayConfiguration> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { Response<CommunicationRelayConfiguration> response = client.getRelayConfigurationWithResponse(communicationUser, context).block(); return response; }
class CommunicationRelayClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayClient.class); CommunicationRelayClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRelayConfiguration getRelayConfiguration(CommunicationUserIdentifier communicationUser) { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfiguration(body); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The obtained Communication Relay Configuration */ }
class CommunicationRelayClient { private final CommunicationRelayAsyncClient client; private final ClientLogger logger = new ClientLogger(CommunicationRelayClient.class); CommunicationRelayClient(CommunicationRelayAsyncClient communicationNetworkingClient) { client = communicationNetworkingClient; } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRelayConfiguration getRelayConfiguration(CommunicationUserIdentifier communicationUser) { return client.getRelayConfiguration(communicationUser).block(); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) }
These builder methods should allow setting `null` value to unset previously set values. The validation should happen in `build*Client()` methods
public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; }
this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null.");
public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; }
class CommunicationRelayClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_IDENTITY_PROPERTIES = "azure-communication-networktravesal.properties"; private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_IDENTITY_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationRelayClientBuilder */ /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); return this; } /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code clientOptions} is {@code null}. */ public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder configuration(Configuration configuration) { this.configuration = Objects.requireNonNull(configuration, "'configuration' cannot be null."); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * @param retryPolicy User's retry policy applied to each request. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If the specified {@code retryPolicy} is null. */ public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null"); return this; } /** * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayAsyncClient instance */ public CommunicationRelayAsyncClient buildAsyncClient() { return new CommunicationRelayAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayClient instance */ public CommunicationRelayClient buildClient() { return new CommunicationRelayClient(createServiceImpl()); } private CommunicationNetworkingClientImpl createServiceImpl() { Objects.requireNonNull(endpoint); HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationNetworkingClientImplBuilder clientBuilder = new CommunicationNetworkingClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.azureKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.azureKeyCredential != null) { return new HmacAuthenticationPolicy(this.azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); applyRequiredPolicies(policies, authorizationPolicy); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies, HttpPipelinePolicy authorizationPolicy) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; String applicationId = null; if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { applicationId = buildClientOptions.getApplicationId(); } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { applicationId = buildLogOptions.getApplicationId(); } policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); policies.add(new CookiePolicy()); policies.add(authorizationPolicy); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
class CommunicationRelayClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES = "azure-communication-networktraversal.properties"; private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private String connectionString; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationRelayClientBuilder */ /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = keyCredential; return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder connectionString(String connectionString) { CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(customPolicy); return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * @param retryPolicy User's retry policy applied to each request. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayAsyncClient instance */ public CommunicationRelayAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return new CommunicationRelayAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayClient instance */ public CommunicationRelayClient buildClient() { return new CommunicationRelayClient(buildAsyncClient()); } private CommunicationNetworkingClientImpl createServiceImpl() { HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationNetworkingClientImplBuilder clientBuilder = new CommunicationNetworkingClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.azureKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.azureKeyCredential != null) { return new HmacAuthenticationPolicy(this.azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); applyRequiredPolicies(policies, authorizationPolicy); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies, HttpPipelinePolicy authorizationPolicy) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; String applicationId = null; if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { applicationId = buildClientOptions.getApplicationId(); } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { applicationId = buildLogOptions.getApplicationId(); } policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); policies.add(new CookiePolicy()); policies.add(authorizationPolicy); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
Add javadoc.
public static void main(String[] args) { String connectionString = System.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING"); CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationUserIdentifier user = communicationIdentityClient.createUser(); System.out.println("User id: " + user.getId()); CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(user); System.out.println("Expires on:" + config.getExpiresOn()); List<CommunicationIceServer> iceServers = config.getIceServers(); for (CommunicationIceServer iceS : iceServers) { System.out.println("URLS: " + iceS.getUrls()); System.out.println("Username: " + iceS.getUsername()); System.out.println("credential: " + iceS.getCredential()); } }
public static void main(String[] args) { String connectionString = System.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING"); CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationUserIdentifier user = communicationIdentityClient.createUser(); System.out.println("User id: " + user.getId()); CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(user); System.out.println("Expires on:" + config.getExpiresOn()); List<CommunicationIceServer> iceServers = config.getIceServers(); for (CommunicationIceServer iceS : iceServers) { System.out.println("URLS: " + iceS.getUrls()); System.out.println("Username: " + iceS.getUsername()); System.out.println("credential: " + iceS.getCredential()); } }
class CreateAndIssueRelayCredentialsExample { }
class CreateAndIssueRelayCredentialsExample { }
Yes, the one that is calling is of return type CommunicationRelayConfiguration in CommunicationTraversalImpl.java so Mono.just is needed. Also, I tested to in case this calling a different function.
public Mono<CommunicationRelayConfiguration> getRelayConfiguration(CommunicationUserIdentifier communicationUser) { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return Mono.just(client.issueRelayConfiguration(body)); }
return Mono.just(client.issueRelayConfiguration(body));
public Mono<CommunicationRelayConfiguration> getRelayConfiguration(CommunicationUserIdentifier communicationUser) { return this.getRelayConfigurationWithResponse(communicationUser).flatMap(FluxUtil::toMono); }
class CommunicationRelayAsyncClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); CommunicationRelayAsyncClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser) { try { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfigurationWithResponseAsync(body) .onErrorMap(CommunicationErrorResponseException.class, e -> translateException(e)) .flatMap( (Response<CommunicationRelayConfiguration> response) -> { return Mono.just( new SimpleResponse<CommunicationRelayConfiguration>( response, response.getValue())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private CommunicationErrorResponseException translateException(CommunicationErrorResponseException exception) { CommunicationErrorResponse error = null; if (exception.getValue() != null) { error = exception.getValue(); } return new CommunicationErrorResponseException(exception.getMessage(), exception.getResponse(), error); } }
class CommunicationRelayAsyncClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); CommunicationRelayAsyncClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser) { return withContext(context -> getRelayConfigurationWithResponse(communicationUser, context)); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The created Communication Relay Configuration. */ Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { context = context == null ? Context.NONE : context; try { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfigurationWithResponseAsync(body, context) .onErrorMap(CommunicationErrorResponseException.class, e -> e); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Yeah, here I can just do that. I'll update
public Response<CommunicationRelayConfiguration> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { context = context == null ? Context.NONE : context; CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); Response<CommunicationRelayConfiguration> response = client.issueRelayConfigurationWithResponseAsync(body, context).block(); if (response == null || response.getValue() == null) { throw logger.logExceptionAsError(new IllegalStateException("Service failed to return a response or expected value.")); } return new SimpleResponse<CommunicationRelayConfiguration>( response, response.getValue()); }
return new SimpleResponse<CommunicationRelayConfiguration>(
public Response<CommunicationRelayConfiguration> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { Response<CommunicationRelayConfiguration> response = client.getRelayConfigurationWithResponse(communicationUser, context).block(); return response; }
class CommunicationRelayClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayClient.class); CommunicationRelayClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRelayConfiguration getRelayConfiguration(CommunicationUserIdentifier communicationUser) { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfiguration(body); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The obtained Communication Relay Configuration */ }
class CommunicationRelayClient { private final CommunicationRelayAsyncClient client; private final ClientLogger logger = new ClientLogger(CommunicationRelayClient.class); CommunicationRelayClient(CommunicationRelayAsyncClient communicationNetworkingClient) { client = communicationNetworkingClient; } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) public CommunicationRelayConfiguration getRelayConfiguration(CommunicationUserIdentifier communicationUser) { return client.getRelayConfiguration(communicationUser).block(); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The obtained Communication Relay Configuration */ @ServiceMethod(returns = ReturnType.SINGLE) }
For which values should we do that? I see identity has it the same way as I did. But chat has a mix of both, so I'm not sure what's the criteria to decide which ones can be null.
public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; }
this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null.");
public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; }
class CommunicationRelayClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_IDENTITY_PROPERTIES = "azure-communication-networktravesal.properties"; private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_IDENTITY_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationRelayClientBuilder */ /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); return this; } /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code clientOptions} is {@code null}. */ public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder configuration(Configuration configuration) { this.configuration = Objects.requireNonNull(configuration, "'configuration' cannot be null."); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * @param retryPolicy User's retry policy applied to each request. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If the specified {@code retryPolicy} is null. */ public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null"); return this; } /** * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayAsyncClient instance */ public CommunicationRelayAsyncClient buildAsyncClient() { return new CommunicationRelayAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayClient instance */ public CommunicationRelayClient buildClient() { return new CommunicationRelayClient(createServiceImpl()); } private CommunicationNetworkingClientImpl createServiceImpl() { Objects.requireNonNull(endpoint); HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationNetworkingClientImplBuilder clientBuilder = new CommunicationNetworkingClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.azureKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.azureKeyCredential != null) { return new HmacAuthenticationPolicy(this.azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); applyRequiredPolicies(policies, authorizationPolicy); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies, HttpPipelinePolicy authorizationPolicy) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; String applicationId = null; if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { applicationId = buildClientOptions.getApplicationId(); } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { applicationId = buildLogOptions.getApplicationId(); } policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); policies.add(new CookiePolicy()); policies.add(authorizationPolicy); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
class CommunicationRelayClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES = "azure-communication-networktraversal.properties"; private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private String connectionString; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationRelayClientBuilder */ /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = keyCredential; return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder connectionString(String connectionString) { CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(customPolicy); return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * @param retryPolicy User's retry policy applied to each request. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayAsyncClient instance */ public CommunicationRelayAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return new CommunicationRelayAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayClient instance */ public CommunicationRelayClient buildClient() { return new CommunicationRelayClient(buildAsyncClient()); } private CommunicationNetworkingClientImpl createServiceImpl() { HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationNetworkingClientImplBuilder clientBuilder = new CommunicationNetworkingClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.azureKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.azureKeyCredential != null) { return new HmacAuthenticationPolicy(this.azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); applyRequiredPolicies(policies, authorizationPolicy); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies, HttpPipelinePolicy authorizationPolicy) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; String applicationId = null; if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { applicationId = buildClientOptions.getApplicationId(); } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { applicationId = buildLogOptions.getApplicationId(); } policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); policies.add(new CookiePolicy()); policies.add(authorizationPolicy); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
Seems we don't have java doc for other samples classes, I'll leave it as it is. But I can add them if necessary.
public static void main(String[] args) { String connectionString = System.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING"); CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationUserIdentifier user = communicationIdentityClient.createUser(); System.out.println("User id: " + user.getId()); CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(user); System.out.println("Expires on:" + config.getExpiresOn()); List<CommunicationIceServer> iceServers = config.getIceServers(); for (CommunicationIceServer iceS : iceServers) { System.out.println("URLS: " + iceS.getUrls()); System.out.println("Username: " + iceS.getUsername()); System.out.println("credential: " + iceS.getCredential()); } }
public static void main(String[] args) { String connectionString = System.getenv("COMMUNICATION_SAMPLES_CONNECTION_STRING"); CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationRelayClient communicationRelayClient = new CommunicationRelayClientBuilder() .connectionString(connectionString) .buildClient(); CommunicationUserIdentifier user = communicationIdentityClient.createUser(); System.out.println("User id: " + user.getId()); CommunicationRelayConfiguration config = communicationRelayClient.getRelayConfiguration(user); System.out.println("Expires on:" + config.getExpiresOn()); List<CommunicationIceServer> iceServers = config.getIceServers(); for (CommunicationIceServer iceS : iceServers) { System.out.println("URLS: " + iceS.getUrls()); System.out.println("Username: " + iceS.getUsername()); System.out.println("credential: " + iceS.getCredential()); } }
class CreateAndIssueRelayCredentialsExample { }
class CreateAndIssueRelayCredentialsExample { }
In chat for some they're doing it as you say and makes a lot of sense in those cases which are values that can be null. They just check, and don't use it if it's null. In this case, if I add the checks later I will need to throw there, which in the end will be the same having the check on one place or the other. If we would need to reset, we should assign to something else the value and not be able to set to null.
public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; }
this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null.");
public CommunicationRelayClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; }
class CommunicationRelayClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_IDENTITY_PROPERTIES = "azure-communication-networktravesal.properties"; private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_IDENTITY_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder endpoint(String endpoint) { this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationRelayClientBuilder */ /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); return this; } /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If {@code clientOptions} is {@code null}. */ public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder configuration(Configuration configuration) { this.configuration = Objects.requireNonNull(configuration, "'configuration' cannot be null."); return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * @param retryPolicy User's retry policy applied to each request. * @return The updated {@link CommunicationRelayClientBuilder} object. * @throws NullPointerException If the specified {@code retryPolicy} is null. */ public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null"); return this; } /** * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayAsyncClient instance */ public CommunicationRelayAsyncClient buildAsyncClient() { return new CommunicationRelayAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayClient instance */ public CommunicationRelayClient buildClient() { return new CommunicationRelayClient(createServiceImpl()); } private CommunicationNetworkingClientImpl createServiceImpl() { Objects.requireNonNull(endpoint); HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationNetworkingClientImplBuilder clientBuilder = new CommunicationNetworkingClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.azureKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.azureKeyCredential != null) { return new HmacAuthenticationPolicy(this.azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); applyRequiredPolicies(policies, authorizationPolicy); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies, HttpPipelinePolicy authorizationPolicy) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; String applicationId = null; if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { applicationId = buildClientOptions.getApplicationId(); } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { applicationId = buildLogOptions.getApplicationId(); } policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); policies.add(new CookiePolicy()); policies.add(authorizationPolicy); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
class CommunicationRelayClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES = "azure-communication-networktraversal.properties"; private final ClientLogger logger = new ClientLogger(CommunicationRelayClientBuilder.class); private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; private ClientOptions clientOptions; private String connectionString; private final Map<String, String> properties = CoreUtils.getProperties(COMMUNICATION_NETWORK_TRAVERSAL_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<>(); /** * Set endpoint of the service * * @param endpoint url of the service * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * Set endpoint of the service * * @param pipeline HttpPipeline to use, if a pipeline is not * supplied, the credential and httpClient fields must be set * @return CommunicationRelayClientBuilder */ /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; return this; } /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = keyCredential; return this; } /** * Set endpoint and credential to use * * @param connectionString connection string for setting endpoint and initalizing CommunicationClientCredential * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder connectionString(String connectionString) { CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); this .endpoint(endpoint) .credential(new AzureKeyCredential(accessKey)); return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline * field. * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Apply additional HttpPipelinePolicy * * @param customPolicy HttpPipelinePolicy object to be applied after * AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy * @return CommunicationRelayClientBuilder */ public CommunicationRelayClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(customPolicy); return this; } /** * Sets the client options for all the requests made through the client. * * @param clientOptions {@link ClientOptions}. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Sets the configuration object used to retrieve environment configuration values during building of the client. * * @param configuration Configuration store used to retrieve environment configurations. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link HttpLogOptions} for service requests. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * @param retryPolicy User's retry policy applied to each request. * @return The updated {@link CommunicationRelayClientBuilder} object. */ public CommunicationRelayClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Sets the {@link CommunicationRelayServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version of the client library will have the result of potentially moving to a newer service version. * <p> * Targeting a specific service version may also mean that the service will return an error for newer APIs. * * @param version {@link CommunicationRelayServiceVersion} of the service to be used when making requests. * @return the updated CommunicationRelayClientBuilder object */ public CommunicationRelayClientBuilder serviceVersion(CommunicationRelayServiceVersion version) { return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayAsyncClient instance */ public CommunicationRelayAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); return new CommunicationRelayAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. * Additional HttpPolicies specified by additionalPolicies will be applied after them * * @return CommunicationRelayClient instance */ public CommunicationRelayClient buildClient() { return new CommunicationRelayClient(buildAsyncClient()); } private CommunicationNetworkingClientImpl createServiceImpl() { HttpPipeline builderPipeline = this.pipeline; if (this.pipeline == null) { builderPipeline = createHttpPipeline(httpClient, createHttpPipelineAuthPolicy(), customPolicies); } CommunicationNetworkingClientImplBuilder clientBuilder = new CommunicationNetworkingClientImplBuilder(); clientBuilder.endpoint(endpoint) .pipeline(builderPipeline); return clientBuilder.buildClient(); } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (this.tokenCredential != null && this.azureKeyCredential != null) { throw logger.logExceptionAsError( new IllegalArgumentException("Both 'credential' and 'accessKey' are set. Just one may be used.")); } if (this.tokenCredential != null) { return new BearerTokenAuthenticationPolicy( this.tokenCredential, "https: } else if (this.azureKeyCredential != null) { return new HmacAuthenticationPolicy(this.azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpPipeline createHttpPipeline(HttpClient httpClient, HttpPipelinePolicy authorizationPolicy, List<HttpPipelinePolicy> customPolicies) { List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>(); applyRequiredPolicies(policies, authorizationPolicy); if (customPolicies != null && customPolicies.size() > 0) { policies.addAll(customPolicies); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(clientOptions) .build(); } private void applyRequiredPolicies(List<HttpPipelinePolicy> policies, HttpPipelinePolicy authorizationPolicy) { String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions; HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions; String applicationId = null; if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) { applicationId = buildClientOptions.getApplicationId(); } else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) { applicationId = buildLogOptions.getApplicationId(); } policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policies.add(new RequestIdPolicy()); policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); policies.add(new CookiePolicy()); policies.add(authorizationPolicy); policies.add(new HttpLoggingPolicy(httpLogOptions)); } }
Yeah, I think it should have worked since they are the same type, but the compiler complains. Seems I have to keep it this way. I guess that's why in identity is done the same way.
public Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser) { try { CommunicationRelayConfigurationRequest body = new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfigurationWithResponseAsync(body) .onErrorMap(CommunicationErrorResponseException.class, e -> translateException(e)) .flatMap( (Response<CommunicationRelayConfiguration> response) -> { return Mono.just( new SimpleResponse<CommunicationRelayConfiguration>( response, response.getValue())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }
response.getValue()));
new CommunicationRelayConfigurationRequest(); body.setId(communicationUser.getId()); return client.issueRelayConfigurationWithResponseAsync(body, context) .onErrorMap(CommunicationErrorResponseException.class, e -> e); } catch (RuntimeException ex) { return monoError(logger, ex); }
class CommunicationRelayAsyncClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); CommunicationRelayAsyncClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CommunicationRelayConfiguration> getRelayConfiguration(CommunicationUserIdentifier communicationUser) { CommunicationRelayConfigurationRequest body = private CommunicationErrorResponseException translateException(CommunicationErrorResponseException exception) { CommunicationErrorResponse error = null; if (exception.getValue() != null) { error = exception.getValue(); } return new CommunicationErrorResponseException(exception.getMessage(), exception.getResponse(), error); } }
class CommunicationRelayAsyncClient { private final CommunicationNetworkTraversalsImpl client; private final ClientLogger logger = new ClientLogger(CommunicationRelayAsyncClient.class); CommunicationRelayAsyncClient(CommunicationNetworkingClientImpl communicationNetworkingClient) { client = communicationNetworkingClient.getCommunicationNetworkTraversals(); } /** * Creates a new CommunicationRelayConfiguration. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<CommunicationRelayConfiguration> getRelayConfiguration(CommunicationUserIdentifier communicationUser) { return this.getRelayConfigurationWithResponse(communicationUser).flatMap(FluxUtil::toMono); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @return The created Communication Relay Configuration. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser) { return withContext(context -> getRelayConfigurationWithResponse(communicationUser, context)); } /** * Creates a new CommunicationRelayConfiguration with response. * * @param communicationUser The CommunicationUserIdentifier for whom to issue a token * @param context A {@link Context} representing the request context. * @return The created Communication Relay Configuration. */ Mono<Response<CommunicationRelayConfiguration>> getRelayConfigurationWithResponse(CommunicationUserIdentifier communicationUser, Context context) { context = context == null ? Context.NONE : context; try { CommunicationRelayConfigurationRequest body = } }
Not really, I'll delete :)
public void createRelayClientUsingConnectionString(HttpClient httpClient) { CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); asyncClient = setupAsyncClient(builder, "createIdentityClientUsingConnectionStringSync"); assertNotNull(asyncClient); String connectionString = System.getenv("COMMUNICATION_LIVETEST_DYNAMIC_CONNECTION_STRING"); CommunicationIdentityAsyncClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .connectionString(connectionString) .buildAsyncClient(); Mono<CommunicationUserIdentifier> response = communicationIdentityClient.createUser(); CommunicationUserIdentifier user = response.block(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); }).verifyComplete(); if (user != null) { Mono<CommunicationRelayConfiguration> relayResponse = asyncClient.getRelayConfiguration(user); StepVerifier.create(relayResponse) .assertNext(relayConfig -> { assertNotNull(relayConfig.getIceServers()); for (CommunicationIceServer iceS : relayConfig.getIceServers()) { assertNotNull(iceS.getUrls()); System.out.println("Urls:" + iceS.getUrls()); assertNotNull(iceS.getUsername()); System.out.println("Username: " + iceS.getUsername()); assertNotNull(iceS.getCredential()); System.out.println("Credential: " + iceS.getCredential()); } }).verifyComplete(); } }
System.out.println("Urls:" + iceS.getUrls());
public void createRelayClientUsingConnectionString(HttpClient httpClient) { setupTest(httpClient); CommunicationRelayClientBuilder builder = createClientBuilderUsingConnectionString(httpClient); asyncClient = setupAsyncClient(builder, "createIdentityClientUsingConnectionStringSync"); assertNotNull(asyncClient); assertNotNull(user.getId()); if (user != null) { Mono<CommunicationRelayConfiguration> relayResponse = asyncClient.getRelayConfiguration(user); StepVerifier.create(relayResponse) .assertNext(relayConfig -> { assertNotNull(relayConfig.getIceServers()); for (CommunicationIceServer iceS : relayConfig.getIceServers()) { assertNotNull(iceS.getUrls()); assertNotNull(iceS.getUsername()); assertNotNull(iceS.getCredential()); } }).verifyComplete(); } }
class CommunicationRelayAsyncTests extends CommunicationRelayClientTestBase { private CommunicationRelayAsyncClient asyncClient; @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRelayClientUsingManagedIdentity(HttpClient httpClient) { CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); asyncClient = setupAsyncClient(builder, "createRelayClientUsingManagedIdentitySync"); assertNotNull(asyncClient); CommunicationIdentityClientBuilder identityBuilder = createIdentityClientBuilder(httpClient); CommunicationIdentityAsyncClient communicationIdentityClient = setupIdentityAsyncClient(identityBuilder, "createRelayClientUsingManagedIdentity"); Mono<CommunicationUserIdentifier> response = communicationIdentityClient.createUser(); CommunicationUserIdentifier user = response.block(); StepVerifier.create(response) .assertNext(item -> { assertNotNull(item.getId()); }).verifyComplete(); if (user != null) { Mono<CommunicationRelayConfiguration> relayResponse = asyncClient.getRelayConfiguration(user); StepVerifier.create(relayResponse) .assertNext(relayConfig -> { assertNotNull(relayConfig.getIceServers()); for (CommunicationIceServer iceS : relayConfig.getIceServers()) { System.out.println("Urls:" + iceS.getUrls()); assertNotNull(iceS.getUsername()); System.out.println("Username: " + iceS.getUsername()); assertNotNull(iceS.getCredential()); System.out.println("Credential: " + iceS.getCredential()); } }).verifyComplete(); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRelayConfigWithResponse(HttpClient httpClient) { CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); asyncClient = setupAsyncClient(builder, "createRelayClientUsingManagedIdentitySync"); assertNotNull(asyncClient); CommunicationIdentityClientBuilder identityBuilder = createIdentityClientBuilder(httpClient); CommunicationIdentityAsyncClient communicationIdentityClient = setupIdentityAsyncClient(identityBuilder, "createRelayClientUsingManagedIdentity"); Mono<CommunicationUserIdentifier> responseUser = communicationIdentityClient.createUser(); CommunicationUserIdentifier user = responseUser.block(); StepVerifier.create(responseUser) .assertNext(item -> { assertNotNull(item.getId()); }).verifyComplete(); if (user != null) { Mono<Response<CommunicationRelayConfiguration>> relayConfig = asyncClient.getRelayConfigurationWithResponse(user); StepVerifier.create(relayConfig) .assertNext(response -> { assertEquals(200, response.getStatusCode(), "Expect status code to be 200"); assertNotNull(response.getValue().getIceServers()); for (CommunicationIceServer iceS : response.getValue().getIceServers()) { assertNotNull(iceS.getUrls()); System.out.println("Urls: " + iceS.getUrls()); assertNotNull(iceS.getUsername()); System.out.println("Username: " + iceS.getUsername()); assertNotNull(iceS.getCredential()); System.out.println("Credential: " + iceS.getCredential()); } }).verifyComplete(); } } private CommunicationRelayAsyncClient setupAsyncClient(CommunicationRelayClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } private CommunicationIdentityAsyncClient setupIdentityAsyncClient(CommunicationIdentityClientBuilder builder, String testName) { return addLoggingPolicyIdentity(builder, testName).buildAsyncClient(); } }
class CommunicationRelayAsyncTests extends CommunicationRelayClientTestBase { private CommunicationRelayAsyncClient asyncClient; private CommunicationUserIdentifier user; private void setupTest(HttpClient httpClient) { CommunicationIdentityClient communicationIdentityClient = createIdentityClientBuilder(httpClient).buildClient(); user = communicationIdentityClient.createUser(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRelayClientUsingManagedIdentity(HttpClient httpClient) { setupTest(httpClient); CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); asyncClient = setupAsyncClient(builder, "createRelayClientUsingManagedIdentitySync"); assertNotNull(asyncClient); assertNotNull(user.getId()); if (user != null) { Mono<CommunicationRelayConfiguration> relayResponse = asyncClient.getRelayConfiguration(user); StepVerifier.create(relayResponse) .assertNext(relayConfig -> { assertNotNull(relayConfig.getIceServers()); for (CommunicationIceServer iceS : relayConfig.getIceServers()) { assertNotNull(iceS.getUsername()); assertNotNull(iceS.getCredential()); } }).verifyComplete(); } } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRelayConfigWithResponse(HttpClient httpClient) { setupTest(httpClient); CommunicationRelayClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient); asyncClient = setupAsyncClient(builder, "createRelayClientUsingManagedIdentitySync"); assertNotNull(asyncClient); assertNotNull(user.getId()); if (user != null) { Mono<Response<CommunicationRelayConfiguration>> relayConfig = asyncClient.getRelayConfigurationWithResponse(user); StepVerifier.create(relayConfig) .assertNext(response -> { assertEquals(200, response.getStatusCode(), "Expect status code to be 200"); assertNotNull(response.getValue().getIceServers()); for (CommunicationIceServer iceS : response.getValue().getIceServers()) { assertNotNull(iceS.getUrls()); assertNotNull(iceS.getUsername()); assertNotNull(iceS.getCredential()); } }).verifyComplete(); } } private CommunicationRelayAsyncClient setupAsyncClient(CommunicationRelayClientBuilder builder, String testName) { return addLoggingPolicy(builder, testName).buildAsyncClient(); } }