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
Is this a client side or server side param? If server, no need to null check recordingId
public Mono<CallRecordingStateResult> getRecordingState(String recordingId) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return this.serverCallInternal.recordingStateAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Objects.requireNonNull(recordingId, "'recordingId' cannot be null.");
public Mono<CallRecordingStateResult> getRecordingState(String recordingId) { try { return serverCallInternal.recordingStateAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .flatMap(result -> Mono.just(new CallRecordingStateResult(result.getRecordingState()))); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ServerCallAsync { private final String serverCallId; private final ServerCallsImpl serverCallInternal; private final ClientLogger logger = new ClientLogger(ServerCallAsync.class); ServerCallAsync(String serverCallId, ServerCallsImpl serverCallInternal) { this.serverCallId = serverCallId; this.serverCallInternal = serverCallInternal; } /** * Get the server call id property * * @return the id value. */ public String getServerCallId() { return serverCallId; } /** * Add a participant to the call. * * @param participant Invited participant. * @param callBackUri callBackUri to get notifications. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext operationContext. * @return response for a successful addParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> addParticipant(CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext) { try { Objects.requireNonNull(participant, "'participant' cannot be null."); InviteParticipantsRequest request = AddParticipantConverter.convert(participant, alternateCallerId, operationContext, callBackUri); return this.serverCallInternal.inviteParticipantsAsync(serverCallId, request) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Add a participant to the call. * * @param participant Invited participant. * @param callBackUri callBackUri to get notifications. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext operationContext. * @return response for a successful addParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addParticipantWithResponse(CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext) { return addParticipantWithResponse(participant, callBackUri, alternateCallerId, operationContext, Context.NONE); } Mono<Response<Void>> addParticipantWithResponse(CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext, Context context) { try { Objects.requireNonNull(participant, "'participant' cannot be null."); InviteParticipantsRequest request = AddParticipantConverter.convert(participant, alternateCallerId, operationContext, callBackUri); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .inviteParticipantsWithResponseAsync(serverCallId, request, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful removeParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> removeParticipant(String participantId) { try { Objects.requireNonNull(participantId, "'participantId' cannot be null."); return this.serverCallInternal.removeParticipantAsync(serverCallId, participantId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful removeParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeParticipantWithResponse(String participantId) { return removeParticipantWithResponse(participantId, Context.NONE); } Mono<Response<Void>> removeParticipantWithResponse(String participantId, Context context) { try { Objects.requireNonNull(participantId, "'participantId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .removeParticipantWithResponseAsync(serverCallId, participantId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Start recording * * @param recordingStateCallbackUri The uri to send state change callbacks. * @throws InvalidParameterException is recordingStateCallbackUri is absolute uri. * @return response for a successful startRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<StartCallRecordingResult> startRecording(String recordingStateCallbackUri) { try { Objects.requireNonNull(recordingStateCallbackUri, "'recordingStateCallbackUri' cannot be null."); if (!Boolean.TRUE.equals(new URI(recordingStateCallbackUri).isAbsolute())) { throw logger.logExceptionAsError(new InvalidParameterException("'recordingStateCallbackUri' cannot be non absolute Uri")); } StartCallRecordingRequest request = new StartCallRecordingRequest(); request.setRecordingStateCallbackUri(recordingStateCallbackUri); return this.serverCallInternal.startRecordingAsync(serverCallId, request) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } catch (URISyntaxException ex) { return monoError(logger, new RuntimeException(ex.getMessage())); } } /** * Start recording * * @param recordingStateCallbackUri The uri to send state change callbacks. * @throws InvalidParameterException is recordingStateCallbackUri is absolute uri. * @return response for a successful startRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<StartCallRecordingResult>> startRecordingWithResponse(String recordingStateCallbackUri) { return startRecordingWithResponse(recordingStateCallbackUri, Context.NONE); } Mono<Response<StartCallRecordingResult>> startRecordingWithResponse(String recordingStateCallbackUri, Context context) { try { Objects.requireNonNull(recordingStateCallbackUri, "'recordingStateCallbackUri' cannot be null."); if (!Boolean.TRUE.equals(new URI(recordingStateCallbackUri).isAbsolute())) { throw logger.logExceptionAsError(new InvalidParameterException("'recordingStateCallbackUri' cannot be non absolute Uri")); } StartCallRecordingRequest request = new StartCallRecordingRequest(); request.setRecordingStateCallbackUri(recordingStateCallbackUri); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .startRecordingWithResponseAsync(serverCallId, request, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } catch (URISyntaxException ex) { return monoError(logger, new RuntimeException(ex.getMessage())); } } /** * Stop recording * * @param recordingId The recording id to stop. * @return response for a successful stopRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> stopRecording(String recordingId) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return this.serverCallInternal.stopRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Stop recording * * @param recordingId The recording id to stop. * @return response for a successful stopRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> stopRecordingWithResponse(String recordingId) { return stopRecordingWithResponse(recordingId, Context.NONE); } Mono<Response<Void>> stopRecordingWithResponse(String recordingId, Context context) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .stopRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Pause recording * * @param recordingId The recording id to stop. * @return response for a successful pauseRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> pauseRecording(String recordingId) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return this.serverCallInternal.pauseRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Pause recording * * @param recordingId The recording id to stop. * @return response for a successful pauseRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> pauseRecordingWithResponse(String recordingId) { return pauseRecordingWithResponse(recordingId, Context.NONE); } Mono<Response<Void>> pauseRecordingWithResponse(String recordingId, Context context) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .pauseRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resume recording * * @param recordingId The recording id to stop. * @return response for a successful resumeRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> resumeRecording(String recordingId) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return this.serverCallInternal.resumeRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resume recording * * @param recordingId The recording id to stop. * @return response for a successful resumeRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> resumeRecordingWithResponse(String recordingId) { return resumeRecordingWithResponse(recordingId, Context.NONE); } Mono<Response<Void>> resumeRecordingWithResponse(String recordingId, Context context) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .resumeRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get recording state * * @param recordingId The recording id to stop. * @return response for a successful getRecordingState request. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Get recording state * * @param recordingId The recording id to stop. * @return response for a successful getRecordingState request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CallRecordingStateResult>> getRecordingStateWithResponse(String recordingId) { return getRecordingStateWithResponse(recordingId, Context.NONE); } Mono<Response<CallRecordingStateResult>> getRecordingStateWithResponse(String recordingId, Context context) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .recordingStateWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param audioFileId Tne id for the media in the AudioFileUri, using which we cache the media resource. * @param callbackUri The callback Uri to receive PlayAudio status notifications. * @param operationContext The operation context. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PlayAudioResult> playAudio(String audioFileUri, String audioFileId, String callbackUri, String operationContext) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest playAudioRequest = new PlayAudioRequest(); playAudioRequest.setAudioFileUri(audioFileUri); playAudioRequest.setLoop(false); playAudioRequest.setAudioFileId(audioFileId); playAudioRequest.setOperationContext(operationContext); playAudioRequest.setCallbackUri(callbackUri); return playAudio(playAudioRequest); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PlayAudioResult> playAudio(String audioFileUri, PlayAudioOptions playAudioOptions) { PlayAudioRequest playAudioRequest = PlayAudioConverter.convert(audioFileUri, playAudioOptions); return playAudio(playAudioRequest); } Mono<PlayAudioResult> playAudio(PlayAudioRequest playAudioRequest) { try { Objects.requireNonNull(playAudioRequest.getAudioFileUri(), "'audioFileUri' cannot be null."); return this.serverCallInternal.playAudioAsync(serverCallId, playAudioRequest) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param audioFileId Tne id for the media in the AudioFileUri, using which we cache the media resource. * @param callbackUri The callback Uri to receive PlayAudio status notifications. * @param operationContext The operation context. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PlayAudioResult>> playAudioWithResponse(String audioFileUri, String audioFileId, String callbackUri, String operationContext) { PlayAudioRequest playAudioRequest = new PlayAudioRequest(); playAudioRequest.setAudioFileUri(audioFileUri); playAudioRequest.setLoop(false); playAudioRequest.setAudioFileId(audioFileId); playAudioRequest.setOperationContext(operationContext); playAudioRequest.setCallbackUri(callbackUri); return playAudioWithResponse(playAudioRequest, Context.NONE); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PlayAudioResult>> playAudioWithResponse(String audioFileUri, PlayAudioOptions playAudioOptions) { PlayAudioRequest playAudioRequest = PlayAudioConverter.convert(audioFileUri, playAudioOptions); return playAudioWithResponse(playAudioRequest, Context.NONE); } Mono<Response<PlayAudioResult>> playAudioWithResponse(PlayAudioRequest playAudioRequest, Context context) { try { Objects.requireNonNull(playAudioRequest.getAudioFileUri(), "'audioFileUri' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .playAudioWithResponseAsync(serverCallId, playAudioRequest, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class ServerCallAsync { private final String serverCallId; private final ServerCallsImpl serverCallInternal; private final ClientLogger logger = new ClientLogger(ServerCallAsync.class); ServerCallAsync(String serverCallId, ServerCallsImpl serverCallInternal) { this.serverCallId = serverCallId; this.serverCallInternal = serverCallInternal; } /** * Get the server call id property * * @return the id value. */ public String getServerCallId() { return serverCallId; } /** * Add a participant to the call. * * @param participant Invited participant. * @param callBackUri callBackUri to get notifications. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return response for a successful add participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> addParticipant( CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext) { try { Objects.requireNonNull(participant, "'participant' cannot be null."); InviteParticipantsRequest request = InviteParticipantRequestConverter.convert(participant, alternateCallerId, operationContext, callBackUri); return serverCallInternal.inviteParticipantsAsync(serverCallId, request) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Add a participant to the call. * * @param participant Invited participant. * @param callBackUri callBackUri to get notifications. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return response for a successful add participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addParticipantWithResponse( CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext) { return addParticipantWithResponse(participant, callBackUri, alternateCallerId, operationContext, null); } Mono<Response<Void>> addParticipantWithResponse( CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext, Context context) { try { Objects.requireNonNull(participant, "'participant' cannot be null."); InviteParticipantsRequest request = InviteParticipantRequestConverter.convert(participant, alternateCallerId, operationContext, callBackUri); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .inviteParticipantsWithResponseAsync(serverCallId, request, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful remove participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> removeParticipant(String participantId) { try { return serverCallInternal.removeParticipantAsync(serverCallId, participantId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful remove participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeParticipantWithResponse(String participantId) { return removeParticipantWithResponse(participantId, null); } Mono<Response<Void>> removeParticipantWithResponse(String participantId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .removeParticipantWithResponseAsync(serverCallId, participantId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Start recording * * @param recordingStateCallbackUri The uri to send state change callbacks. * @throws InvalidParameterException is recordingStateCallbackUri is absolute uri. * @return response for a successful start recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<StartCallRecordingResult> startRecording(String recordingStateCallbackUri) { try { Objects.requireNonNull(recordingStateCallbackUri, "'recordingStateCallbackUri' cannot be null."); if (!Boolean.TRUE.equals(new URI(recordingStateCallbackUri).isAbsolute())) { throw logger.logExceptionAsError(new InvalidParameterException("'recordingStateCallbackUri' has to be an absolute Uri")); } StartCallRecordingRequest request = new StartCallRecordingRequest(); request.setRecordingStateCallbackUri(recordingStateCallbackUri); return serverCallInternal.startRecordingAsync(serverCallId, request) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .flatMap(result -> Mono.just(new StartCallRecordingResult(result.getRecordingId()))); } catch (RuntimeException ex) { return monoError(logger, ex); } catch (URISyntaxException ex) { return monoError(logger, new RuntimeException(ex.getMessage())); } } /** * Start recording * * @param recordingStateCallbackUri The uri to send state change callbacks. * @throws InvalidParameterException is recordingStateCallbackUri is absolute uri. * @return response for a successful start recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<StartCallRecordingResult>> startRecordingWithResponse(String recordingStateCallbackUri) { return startRecordingWithResponse(recordingStateCallbackUri, null); } Mono<Response<StartCallRecordingResult>> startRecordingWithResponse( String recordingStateCallbackUri, Context context) { try { Objects.requireNonNull(recordingStateCallbackUri, "'recordingStateCallbackUri' cannot be null."); if (!Boolean.TRUE.equals(new URI(recordingStateCallbackUri).isAbsolute())) { throw logger.logExceptionAsError(new InvalidParameterException("'recordingStateCallbackUri' has to be an absolute Uri")); } StartCallRecordingRequest request = new StartCallRecordingRequest(); request.setRecordingStateCallbackUri(recordingStateCallbackUri); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .startRecordingWithResponseAsync(serverCallId, request, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .map(response -> new SimpleResponse<>(response, new StartCallRecordingResult(response.getValue().getRecordingId()))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } catch (URISyntaxException ex) { return monoError(logger, new RuntimeException(ex.getMessage())); } } /** * Stop recording * * @param recordingId The recording id to stop. * @return response for a successful stop recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> stopRecording(String recordingId) { try { return serverCallInternal.stopRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Stop recording * * @param recordingId The recording id to stop. * @return response for a successful stop recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> stopRecordingWithResponse(String recordingId) { return stopRecordingWithResponse(recordingId, null); } Mono<Response<Void>> stopRecordingWithResponse(String recordingId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .stopRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Pause recording * * @param recordingId The recording id to stop. * @return response for a successful pause recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> pauseRecording(String recordingId) { try { return serverCallInternal.pauseRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Pause recording * * @param recordingId The recording id to stop. * @return response for a successful pause recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> pauseRecordingWithResponse(String recordingId) { return pauseRecordingWithResponse(recordingId, null); } Mono<Response<Void>> pauseRecordingWithResponse(String recordingId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .pauseRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resume recording * * @param recordingId The recording id to stop. * @return response for a successful resume recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> resumeRecording(String recordingId) { try { return serverCallInternal.resumeRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resume recording * * @param recordingId The recording id to stop. * @return response for a successful resume recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> resumeRecordingWithResponse(String recordingId) { return resumeRecordingWithResponse(recordingId, null); } Mono<Response<Void>> resumeRecordingWithResponse(String recordingId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .resumeRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get recording state * * @param recordingId The recording id to stop. * @return response for a successful get recording state request. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Get recording state * * @param recordingId The recording id to stop. * @return response for a successful get recording state request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CallRecordingStateResult>> getRecordingStateWithResponse(String recordingId) { return getRecordingStateWithResponse(recordingId, null); } Mono<Response<CallRecordingStateResult>> getRecordingStateWithResponse(String recordingId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .recordingStateWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .map(response -> new SimpleResponse<>(response, new CallRecordingStateResult(response.getValue().getRecordingState()))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param audioFileId Tne id for the media in the AudioFileUri, using which we cache the media resource. * @param callbackUri The callback Uri to receive PlayAudio status notifications. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PlayAudioResult> playAudio( String audioFileUri, String audioFileId, String callbackUri, String operationContext) { return playAudioInternal(audioFileUri, audioFileId, callbackUri, operationContext); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PlayAudioResult> playAudio(String audioFileUri, PlayAudioOptions playAudioOptions) { return playAudioInternal(audioFileUri, playAudioOptions); } Mono<PlayAudioResult> playAudioInternal( String audioFileUri, String audioFileId, String callbackUri, String operationContext) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest playAudioRequest = new PlayAudioRequest() .setAudioFileUri(audioFileUri) .setLoop(false) .setAudioFileId(audioFileId) .setOperationContext(operationContext) .setCallbackUri(callbackUri); return playAudioInternal(playAudioRequest); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<PlayAudioResult> playAudioInternal(String audioFileUri, PlayAudioOptions playAudioOptions) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest request = new PlayAudioRequest().setAudioFileUri(audioFileUri); if (playAudioOptions != null) { request .setLoop(false) .setOperationContext(playAudioOptions.getOperationContext()) .setAudioFileId(playAudioOptions.getAudioFileId()) .setCallbackUri(playAudioOptions.getCallbackUri()); } return playAudioInternal(request); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<PlayAudioResult> playAudioInternal(PlayAudioRequest playAudioRequest) { try { return serverCallInternal.playAudioAsync(serverCallId, playAudioRequest) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .flatMap(result -> Mono.just(PlayAudioResultConverter.convert(result))); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param audioFileId Tne id for the media in the AudioFileUri, using which we cache the media resource. * @param callbackUri The callback Uri to receive PlayAudio status notifications. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PlayAudioResult>> playAudioWithResponse( String audioFileUri, String audioFileId, String callbackUri, String operationContext) { return playAudioWithResponseInternal(audioFileUri, audioFileId, callbackUri, operationContext, null); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PlayAudioResult>> playAudioWithResponse( String audioFileUri, PlayAudioOptions playAudioOptions) { return playAudioWithResponseInternal(audioFileUri, playAudioOptions, null); } Mono<Response<PlayAudioResult>> playAudioWithResponseInternal( String audioFileUri, String audioFileId, String callbackUri, String operationContext, Context context) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest playAudioRequest = new PlayAudioRequest() .setAudioFileUri(audioFileUri) .setLoop(false) .setAudioFileId(audioFileId) .setOperationContext(operationContext) .setCallbackUri(callbackUri); return playAudioWithResponse(playAudioRequest, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<PlayAudioResult>> playAudioWithResponseInternal( String audioFileUri, PlayAudioOptions playAudioOptions, Context context) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest request = new PlayAudioRequest().setAudioFileUri(audioFileUri); if (playAudioOptions != null) { request .setLoop(false) .setOperationContext(playAudioOptions.getOperationContext()) .setAudioFileId(playAudioOptions.getAudioFileId()) .setCallbackUri(playAudioOptions.getCallbackUri()); } return playAudioWithResponse(request, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<PlayAudioResult>> playAudioWithResponse(PlayAudioRequest playAudioRequest, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .playAudioWithResponseAsync(serverCallId, playAudioRequest, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .map(response -> new SimpleResponse<>(response, PlayAudioResultConverter.convert(response.getValue()))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
'this' removed
public String getCallConnectionId() { return this.callConnectionAsync.getCallConnectionId(); }
return this.callConnectionAsync.getCallConnectionId();
public String getCallConnectionId() { return callConnectionAsync.getCallConnectionId(); }
class CallConnection { private final CallConnectionAsync callConnectionAsync; private final ClientLogger logger = new ClientLogger(CallConnection.class); CallConnection(CallConnectionAsync callConnectionAsync) { this.callConnectionAsync = callConnectionAsync; } /** * Get the call connection id property * * @return the id value. */ /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param loop The flag indicating whether audio file needs to be played in loop or not. * @param audioFileId An id for the media in the AudioFileUri, using which we cache the media. * @param callbackUri call back uri to receive notifications. * @param operationContext The value to identify context of the operation. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public PlayAudioResult playAudio(String audioFileUri, boolean loop, String audioFileId, String callbackUri, String operationContext) { PlayAudioRequest playAudioRequest = new PlayAudioRequest(); playAudioRequest.setAudioFileUri(audioFileUri); playAudioRequest.setLoop(loop); playAudioRequest.setAudioFileId(audioFileId); playAudioRequest.setOperationContext(operationContext); playAudioRequest.setCallbackUri(callbackUri); return callConnectionAsync.playAudio(playAudioRequest).block(); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param loop The flag indicating whether audio file needs to be played in loop or not. * @param audioFileId An id for the media in the AudioFileUri, using which we cache the media. * @param callbackUri call back uri to receive notifications. * @param operationContext The value to identify context of the operation. * @param context A {@link Context} representing the request context. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<PlayAudioResult> playAudioWithResponse(String audioFileUri, boolean loop, String audioFileId, String callbackUri, String operationContext, Context context) { PlayAudioRequest playAudioRequest = new PlayAudioRequest(); playAudioRequest.setAudioFileUri(audioFileUri); playAudioRequest.setLoop(loop); playAudioRequest.setAudioFileId(audioFileId); playAudioRequest.setOperationContext(operationContext); playAudioRequest.setCallbackUri(callbackUri); return callConnectionAsync.playAudioWithResponse(playAudioRequest, context).block(); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public PlayAudioResult playAudio(String audioFileUri, PlayAudioOptions playAudioOptions) { PlayAudioRequest playAudioRequest = PlayAudioConverter.convert(audioFileUri, playAudioOptions); return callConnectionAsync.playAudio(playAudioRequest).block(); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @param context A {@link Context} representing the request context. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<PlayAudioResult> playAudioWithResponse(String audioFileUri, PlayAudioOptions playAudioOptions, Context context) { PlayAudioRequest playAudioRequest = PlayAudioConverter.convert(audioFileUri, playAudioOptions); return callConnectionAsync.playAudioWithResponse(playAudioRequest, context).block(); } /** * Disconnect the current caller in a Group-call or end a p2p-call. * * @return response for a successful Hangup request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Void hangup() { return callConnectionAsync.hangup().block(); } /** * Disconnect the current caller in a Group-call or end a p2p-call. * * @param context A {@link Context} representing the request context. * @return response for a successful HangupCall request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> hangupWithResponse(Context context) { return callConnectionAsync.hangupWithResponse(context).block(); } /** * Cancel all media operations in the call. * * @param operationContext operationContext. * @return response for a successful CancelMediaOperations request. */ @ServiceMethod(returns = ReturnType.SINGLE) public CancelAllMediaOperationsResult cancelAllMediaOperations(String operationContext) { return callConnectionAsync.cancelAllMediaOperations(operationContext).block(); } /** * Cancel all media operations in the call. * * @param operationContext operationContext. * @param context A {@link Context} representing the request context. * @return response for a successful CancelMediaOperations request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CancelAllMediaOperationsResult> cancelAllMediaOperationsWithResponse(String operationContext, Context context) { return callConnectionAsync.cancelAllMediaOperationsWithResponse(operationContext, context).block(); } /** * Add a participant to the call. * * @param participant Invited participant. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext operationContext. * @return response for a successful addParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Void addParticipant(CommunicationIdentifier participant, String alternateCallerId, String operationContext) { return callConnectionAsync.addParticipant(participant, alternateCallerId, operationContext).block(); } /** * Add a participant to the call. * * @param participant Invited participant. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext operationContext. * @param context A {@link Context} representing the request context. * @return response for a successful addParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> addParticipantWithResponse(CommunicationIdentifier participant, String alternateCallerId, String operationContext, Context context) { return callConnectionAsync .addParticipantWithResponse(participant, alternateCallerId, operationContext, context).block(); } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful removeParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Void removeParticipant(String participantId) { return callConnectionAsync.removeParticipant(participantId).block(); } /** * Remove a participant from the call. * * @param participantId Participant id. * @param context A {@link Context} representing the request context. * @return response for a successful removeParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> removeParticipantWithResponse(String participantId, Context context) { return callConnectionAsync.removeParticipantWithResponse(participantId, context).block(); } }
class CallConnection { private final CallConnectionAsync callConnectionAsync; private final ClientLogger logger = new ClientLogger(CallConnection.class); CallConnection(CallConnectionAsync callConnectionAsync) { this.callConnectionAsync = callConnectionAsync; } /** * Get the call connection id property * * @return the id value. */ /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param loop The flag indicating whether audio file needs to be played in loop or not. * @param audioFileId An id for the media in the AudioFileUri, using which we cache the media. * @param callbackUri call back uri to receive notifications. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public PlayAudioResult playAudio( String audioFileUri, boolean loop, String audioFileId, String callbackUri, String operationContext) { return callConnectionAsync .playAudioInternal(audioFileUri, loop, audioFileId, callbackUri, operationContext).block(); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public PlayAudioResult playAudio(String audioFileUri, PlayAudioOptions playAudioOptions) { return callConnectionAsync.playAudioInternal(audioFileUri, playAudioOptions).block(); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param loop The flag indicating whether audio file needs to be played in loop or not. * @param audioFileId An id for the media in the AudioFileUri, using which we cache the media. * @param callbackUri call back uri to receive notifications. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @param context A {@link Context} representing the request context. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<PlayAudioResult> playAudioWithResponse( String audioFileUri, boolean loop, String audioFileId, String callbackUri, String operationContext, Context context) { return callConnectionAsync .playAudioWithResponseInternal( audioFileUri, loop, audioFileId, callbackUri, operationContext, context) .block(); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @param context A {@link Context} representing the request context. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<PlayAudioResult> playAudioWithResponse( String audioFileUri, PlayAudioOptions playAudioOptions, Context context) { return callConnectionAsync .playAudioWithResponseInternal(audioFileUri, playAudioOptions, context) .block(); } /** * Disconnect the current caller in a group-call or end a p2p-call. * * @return response for a successful hangup request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Void hangup() { return callConnectionAsync.hangup().block(); } /** * Disconnect the current caller in a group-call or end a p2p-call. * * @param context A {@link Context} representing the request context. * @return response for a successful hangup request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> hangupWithResponse(Context context) { return callConnectionAsync.hangupWithResponse(context).block(); } /** * Cancel all media operations in the call. * * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return response for a successful cancel all media operations request. */ @ServiceMethod(returns = ReturnType.SINGLE) public CancelAllMediaOperationsResult cancelAllMediaOperations(String operationContext) { return callConnectionAsync.cancelAllMediaOperations(operationContext).block(); } /** * Cancel all media operations in the call. * * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @param context A {@link Context} representing the request context. * @return response for a successful cancel all media operations request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<CancelAllMediaOperationsResult> cancelAllMediaOperationsWithResponse( String operationContext, Context context) { return callConnectionAsync.cancelAllMediaOperationsWithResponse(operationContext, context).block(); } /** * Add a participant to the call. * * @param participant Invited participant. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return response for a successful add participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Void addParticipant( CommunicationIdentifier participant, String alternateCallerId, String operationContext) { return callConnectionAsync.addParticipant(participant, alternateCallerId, operationContext).block(); } /** * Add a participant to the call. * * @param participant Invited participant. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @param context A {@link Context} representing the request context. * @return response for a successful add participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> addParticipantWithResponse( CommunicationIdentifier participant, String alternateCallerId, String operationContext, Context context) { return callConnectionAsync .addParticipantWithResponse(participant, alternateCallerId, operationContext, context).block(); } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful remove participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Void removeParticipant(String participantId) { return callConnectionAsync.removeParticipant(participantId).block(); } /** * Remove a participant from the call. * * @param participantId Participant id. * @param context A {@link Context} representing the request context. * @return response for a successful remove participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Void> removeParticipantWithResponse(String participantId, Context context) { return callConnectionAsync.removeParticipantWithResponse(participantId, context).block(); } }
This is passed from client side, so checking null
public Mono<CallRecordingStateResult> getRecordingState(String recordingId) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return this.serverCallInternal.recordingStateAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Objects.requireNonNull(recordingId, "'recordingId' cannot be null.");
public Mono<CallRecordingStateResult> getRecordingState(String recordingId) { try { return serverCallInternal.recordingStateAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .flatMap(result -> Mono.just(new CallRecordingStateResult(result.getRecordingState()))); } catch (RuntimeException ex) { return monoError(logger, ex); } }
class ServerCallAsync { private final String serverCallId; private final ServerCallsImpl serverCallInternal; private final ClientLogger logger = new ClientLogger(ServerCallAsync.class); ServerCallAsync(String serverCallId, ServerCallsImpl serverCallInternal) { this.serverCallId = serverCallId; this.serverCallInternal = serverCallInternal; } /** * Get the server call id property * * @return the id value. */ public String getServerCallId() { return serverCallId; } /** * Add a participant to the call. * * @param participant Invited participant. * @param callBackUri callBackUri to get notifications. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext operationContext. * @return response for a successful addParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> addParticipant(CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext) { try { Objects.requireNonNull(participant, "'participant' cannot be null."); InviteParticipantsRequest request = AddParticipantConverter.convert(participant, alternateCallerId, operationContext, callBackUri); return this.serverCallInternal.inviteParticipantsAsync(serverCallId, request) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Add a participant to the call. * * @param participant Invited participant. * @param callBackUri callBackUri to get notifications. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext operationContext. * @return response for a successful addParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addParticipantWithResponse(CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext) { return addParticipantWithResponse(participant, callBackUri, alternateCallerId, operationContext, Context.NONE); } Mono<Response<Void>> addParticipantWithResponse(CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext, Context context) { try { Objects.requireNonNull(participant, "'participant' cannot be null."); InviteParticipantsRequest request = AddParticipantConverter.convert(participant, alternateCallerId, operationContext, callBackUri); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .inviteParticipantsWithResponseAsync(serverCallId, request, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful removeParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> removeParticipant(String participantId) { try { Objects.requireNonNull(participantId, "'participantId' cannot be null."); return this.serverCallInternal.removeParticipantAsync(serverCallId, participantId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful removeParticipant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeParticipantWithResponse(String participantId) { return removeParticipantWithResponse(participantId, Context.NONE); } Mono<Response<Void>> removeParticipantWithResponse(String participantId, Context context) { try { Objects.requireNonNull(participantId, "'participantId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .removeParticipantWithResponseAsync(serverCallId, participantId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Start recording * * @param recordingStateCallbackUri The uri to send state change callbacks. * @throws InvalidParameterException is recordingStateCallbackUri is absolute uri. * @return response for a successful startRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<StartCallRecordingResult> startRecording(String recordingStateCallbackUri) { try { Objects.requireNonNull(recordingStateCallbackUri, "'recordingStateCallbackUri' cannot be null."); if (!Boolean.TRUE.equals(new URI(recordingStateCallbackUri).isAbsolute())) { throw logger.logExceptionAsError(new InvalidParameterException("'recordingStateCallbackUri' cannot be non absolute Uri")); } StartCallRecordingRequest request = new StartCallRecordingRequest(); request.setRecordingStateCallbackUri(recordingStateCallbackUri); return this.serverCallInternal.startRecordingAsync(serverCallId, request) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } catch (URISyntaxException ex) { return monoError(logger, new RuntimeException(ex.getMessage())); } } /** * Start recording * * @param recordingStateCallbackUri The uri to send state change callbacks. * @throws InvalidParameterException is recordingStateCallbackUri is absolute uri. * @return response for a successful startRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<StartCallRecordingResult>> startRecordingWithResponse(String recordingStateCallbackUri) { return startRecordingWithResponse(recordingStateCallbackUri, Context.NONE); } Mono<Response<StartCallRecordingResult>> startRecordingWithResponse(String recordingStateCallbackUri, Context context) { try { Objects.requireNonNull(recordingStateCallbackUri, "'recordingStateCallbackUri' cannot be null."); if (!Boolean.TRUE.equals(new URI(recordingStateCallbackUri).isAbsolute())) { throw logger.logExceptionAsError(new InvalidParameterException("'recordingStateCallbackUri' cannot be non absolute Uri")); } StartCallRecordingRequest request = new StartCallRecordingRequest(); request.setRecordingStateCallbackUri(recordingStateCallbackUri); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .startRecordingWithResponseAsync(serverCallId, request, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } catch (URISyntaxException ex) { return monoError(logger, new RuntimeException(ex.getMessage())); } } /** * Stop recording * * @param recordingId The recording id to stop. * @return response for a successful stopRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> stopRecording(String recordingId) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return this.serverCallInternal.stopRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Stop recording * * @param recordingId The recording id to stop. * @return response for a successful stopRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> stopRecordingWithResponse(String recordingId) { return stopRecordingWithResponse(recordingId, Context.NONE); } Mono<Response<Void>> stopRecordingWithResponse(String recordingId, Context context) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .stopRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Pause recording * * @param recordingId The recording id to stop. * @return response for a successful pauseRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> pauseRecording(String recordingId) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return this.serverCallInternal.pauseRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Pause recording * * @param recordingId The recording id to stop. * @return response for a successful pauseRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> pauseRecordingWithResponse(String recordingId) { return pauseRecordingWithResponse(recordingId, Context.NONE); } Mono<Response<Void>> pauseRecordingWithResponse(String recordingId, Context context) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .pauseRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resume recording * * @param recordingId The recording id to stop. * @return response for a successful resumeRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> resumeRecording(String recordingId) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return this.serverCallInternal.resumeRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resume recording * * @param recordingId The recording id to stop. * @return response for a successful resumeRecording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> resumeRecordingWithResponse(String recordingId) { return resumeRecordingWithResponse(recordingId, Context.NONE); } Mono<Response<Void>> resumeRecordingWithResponse(String recordingId, Context context) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .resumeRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get recording state * * @param recordingId The recording id to stop. * @return response for a successful getRecordingState request. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Get recording state * * @param recordingId The recording id to stop. * @return response for a successful getRecordingState request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CallRecordingStateResult>> getRecordingStateWithResponse(String recordingId) { return getRecordingStateWithResponse(recordingId, Context.NONE); } Mono<Response<CallRecordingStateResult>> getRecordingStateWithResponse(String recordingId, Context context) { try { Objects.requireNonNull(recordingId, "'recordingId' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .recordingStateWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param audioFileId Tne id for the media in the AudioFileUri, using which we cache the media resource. * @param callbackUri The callback Uri to receive PlayAudio status notifications. * @param operationContext The operation context. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PlayAudioResult> playAudio(String audioFileUri, String audioFileId, String callbackUri, String operationContext) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest playAudioRequest = new PlayAudioRequest(); playAudioRequest.setAudioFileUri(audioFileUri); playAudioRequest.setLoop(false); playAudioRequest.setAudioFileId(audioFileId); playAudioRequest.setOperationContext(operationContext); playAudioRequest.setCallbackUri(callbackUri); return playAudio(playAudioRequest); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PlayAudioResult> playAudio(String audioFileUri, PlayAudioOptions playAudioOptions) { PlayAudioRequest playAudioRequest = PlayAudioConverter.convert(audioFileUri, playAudioOptions); return playAudio(playAudioRequest); } Mono<PlayAudioResult> playAudio(PlayAudioRequest playAudioRequest) { try { Objects.requireNonNull(playAudioRequest.getAudioFileUri(), "'audioFileUri' cannot be null."); return this.serverCallInternal.playAudioAsync(serverCallId, playAudioRequest) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param audioFileId Tne id for the media in the AudioFileUri, using which we cache the media resource. * @param callbackUri The callback Uri to receive PlayAudio status notifications. * @param operationContext The operation context. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PlayAudioResult>> playAudioWithResponse(String audioFileUri, String audioFileId, String callbackUri, String operationContext) { PlayAudioRequest playAudioRequest = new PlayAudioRequest(); playAudioRequest.setAudioFileUri(audioFileUri); playAudioRequest.setLoop(false); playAudioRequest.setAudioFileId(audioFileId); playAudioRequest.setOperationContext(operationContext); playAudioRequest.setCallbackUri(callbackUri); return playAudioWithResponse(playAudioRequest, Context.NONE); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PlayAudioResult>> playAudioWithResponse(String audioFileUri, PlayAudioOptions playAudioOptions) { PlayAudioRequest playAudioRequest = PlayAudioConverter.convert(audioFileUri, playAudioOptions); return playAudioWithResponse(playAudioRequest, Context.NONE); } Mono<Response<PlayAudioResult>> playAudioWithResponse(PlayAudioRequest playAudioRequest, Context context) { try { Objects.requireNonNull(playAudioRequest.getAudioFileUri(), "'audioFileUri' cannot be null."); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return this.serverCallInternal .playAudioWithResponseAsync(serverCallId, playAudioRequest, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
class ServerCallAsync { private final String serverCallId; private final ServerCallsImpl serverCallInternal; private final ClientLogger logger = new ClientLogger(ServerCallAsync.class); ServerCallAsync(String serverCallId, ServerCallsImpl serverCallInternal) { this.serverCallId = serverCallId; this.serverCallInternal = serverCallInternal; } /** * Get the server call id property * * @return the id value. */ public String getServerCallId() { return serverCallId; } /** * Add a participant to the call. * * @param participant Invited participant. * @param callBackUri callBackUri to get notifications. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return response for a successful add participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> addParticipant( CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext) { try { Objects.requireNonNull(participant, "'participant' cannot be null."); InviteParticipantsRequest request = InviteParticipantRequestConverter.convert(participant, alternateCallerId, operationContext, callBackUri); return serverCallInternal.inviteParticipantsAsync(serverCallId, request) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Add a participant to the call. * * @param participant Invited participant. * @param callBackUri callBackUri to get notifications. * @param alternateCallerId The phone number to use when adding a phone number participant. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return response for a successful add participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> addParticipantWithResponse( CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext) { return addParticipantWithResponse(participant, callBackUri, alternateCallerId, operationContext, null); } Mono<Response<Void>> addParticipantWithResponse( CommunicationIdentifier participant, String callBackUri, String alternateCallerId, String operationContext, Context context) { try { Objects.requireNonNull(participant, "'participant' cannot be null."); InviteParticipantsRequest request = InviteParticipantRequestConverter.convert(participant, alternateCallerId, operationContext, callBackUri); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .inviteParticipantsWithResponseAsync(serverCallId, request, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful remove participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> removeParticipant(String participantId) { try { return serverCallInternal.removeParticipantAsync(serverCallId, participantId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Remove a participant from the call. * * @param participantId Participant id. * @return response for a successful remove participant request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> removeParticipantWithResponse(String participantId) { return removeParticipantWithResponse(participantId, null); } Mono<Response<Void>> removeParticipantWithResponse(String participantId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .removeParticipantWithResponseAsync(serverCallId, participantId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Start recording * * @param recordingStateCallbackUri The uri to send state change callbacks. * @throws InvalidParameterException is recordingStateCallbackUri is absolute uri. * @return response for a successful start recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<StartCallRecordingResult> startRecording(String recordingStateCallbackUri) { try { Objects.requireNonNull(recordingStateCallbackUri, "'recordingStateCallbackUri' cannot be null."); if (!Boolean.TRUE.equals(new URI(recordingStateCallbackUri).isAbsolute())) { throw logger.logExceptionAsError(new InvalidParameterException("'recordingStateCallbackUri' has to be an absolute Uri")); } StartCallRecordingRequest request = new StartCallRecordingRequest(); request.setRecordingStateCallbackUri(recordingStateCallbackUri); return serverCallInternal.startRecordingAsync(serverCallId, request) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .flatMap(result -> Mono.just(new StartCallRecordingResult(result.getRecordingId()))); } catch (RuntimeException ex) { return monoError(logger, ex); } catch (URISyntaxException ex) { return monoError(logger, new RuntimeException(ex.getMessage())); } } /** * Start recording * * @param recordingStateCallbackUri The uri to send state change callbacks. * @throws InvalidParameterException is recordingStateCallbackUri is absolute uri. * @return response for a successful start recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<StartCallRecordingResult>> startRecordingWithResponse(String recordingStateCallbackUri) { return startRecordingWithResponse(recordingStateCallbackUri, null); } Mono<Response<StartCallRecordingResult>> startRecordingWithResponse( String recordingStateCallbackUri, Context context) { try { Objects.requireNonNull(recordingStateCallbackUri, "'recordingStateCallbackUri' cannot be null."); if (!Boolean.TRUE.equals(new URI(recordingStateCallbackUri).isAbsolute())) { throw logger.logExceptionAsError(new InvalidParameterException("'recordingStateCallbackUri' has to be an absolute Uri")); } StartCallRecordingRequest request = new StartCallRecordingRequest(); request.setRecordingStateCallbackUri(recordingStateCallbackUri); return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .startRecordingWithResponseAsync(serverCallId, request, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .map(response -> new SimpleResponse<>(response, new StartCallRecordingResult(response.getValue().getRecordingId()))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } catch (URISyntaxException ex) { return monoError(logger, new RuntimeException(ex.getMessage())); } } /** * Stop recording * * @param recordingId The recording id to stop. * @return response for a successful stop recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> stopRecording(String recordingId) { try { return serverCallInternal.stopRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Stop recording * * @param recordingId The recording id to stop. * @return response for a successful stop recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> stopRecordingWithResponse(String recordingId) { return stopRecordingWithResponse(recordingId, null); } Mono<Response<Void>> stopRecordingWithResponse(String recordingId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .stopRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Pause recording * * @param recordingId The recording id to stop. * @return response for a successful pause recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> pauseRecording(String recordingId) { try { return serverCallInternal.pauseRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Pause recording * * @param recordingId The recording id to stop. * @return response for a successful pause recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> pauseRecordingWithResponse(String recordingId) { return pauseRecordingWithResponse(recordingId, null); } Mono<Response<Void>> pauseRecordingWithResponse(String recordingId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .pauseRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resume recording * * @param recordingId The recording id to stop. * @return response for a successful resume recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> resumeRecording(String recordingId) { try { return serverCallInternal.resumeRecordingAsync(serverCallId, recordingId) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resume recording * * @param recordingId The recording id to stop. * @return response for a successful resume recording request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> resumeRecordingWithResponse(String recordingId) { return resumeRecordingWithResponse(recordingId, null); } Mono<Response<Void>> resumeRecordingWithResponse(String recordingId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .resumeRecordingWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Get recording state * * @param recordingId The recording id to stop. * @return response for a successful get recording state request. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Get recording state * * @param recordingId The recording id to stop. * @return response for a successful get recording state request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<CallRecordingStateResult>> getRecordingStateWithResponse(String recordingId) { return getRecordingStateWithResponse(recordingId, null); } Mono<Response<CallRecordingStateResult>> getRecordingStateWithResponse(String recordingId, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .recordingStateWithResponseAsync(serverCallId, recordingId, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .map(response -> new SimpleResponse<>(response, new CallRecordingStateResult(response.getValue().getRecordingState()))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param audioFileId Tne id for the media in the AudioFileUri, using which we cache the media resource. * @param callbackUri The callback Uri to receive PlayAudio status notifications. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PlayAudioResult> playAudio( String audioFileUri, String audioFileId, String callbackUri, String operationContext) { return playAudioInternal(audioFileUri, audioFileId, callbackUri, operationContext); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PlayAudioResult> playAudio(String audioFileUri, PlayAudioOptions playAudioOptions) { return playAudioInternal(audioFileUri, playAudioOptions); } Mono<PlayAudioResult> playAudioInternal( String audioFileUri, String audioFileId, String callbackUri, String operationContext) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest playAudioRequest = new PlayAudioRequest() .setAudioFileUri(audioFileUri) .setLoop(false) .setAudioFileId(audioFileId) .setOperationContext(operationContext) .setCallbackUri(callbackUri); return playAudioInternal(playAudioRequest); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<PlayAudioResult> playAudioInternal(String audioFileUri, PlayAudioOptions playAudioOptions) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest request = new PlayAudioRequest().setAudioFileUri(audioFileUri); if (playAudioOptions != null) { request .setLoop(false) .setOperationContext(playAudioOptions.getOperationContext()) .setAudioFileId(playAudioOptions.getAudioFileId()) .setCallbackUri(playAudioOptions.getCallbackUri()); } return playAudioInternal(request); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<PlayAudioResult> playAudioInternal(PlayAudioRequest playAudioRequest) { try { return serverCallInternal.playAudioAsync(serverCallId, playAudioRequest) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .flatMap(result -> Mono.just(PlayAudioResultConverter.convert(result))); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param audioFileId Tne id for the media in the AudioFileUri, using which we cache the media resource. * @param callbackUri The callback Uri to receive PlayAudio status notifications. * @param operationContext The value to identify context of the operation. This is used to co-relate other * communications related to this operation * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PlayAudioResult>> playAudioWithResponse( String audioFileUri, String audioFileId, String callbackUri, String operationContext) { return playAudioWithResponseInternal(audioFileUri, audioFileId, callbackUri, operationContext, null); } /** * Play audio in a call. * * @param audioFileUri The media resource uri of the play audio request. Currently only Wave file (.wav) format * audio prompts are supported. More specifically, the audio content in the wave file must * be mono (single-channel), 16-bit samples with a 16,000 (16KHz) sampling rate. * @param playAudioOptions Options for play audio. * @return the response payload for play audio operation. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PlayAudioResult>> playAudioWithResponse( String audioFileUri, PlayAudioOptions playAudioOptions) { return playAudioWithResponseInternal(audioFileUri, playAudioOptions, null); } Mono<Response<PlayAudioResult>> playAudioWithResponseInternal( String audioFileUri, String audioFileId, String callbackUri, String operationContext, Context context) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest playAudioRequest = new PlayAudioRequest() .setAudioFileUri(audioFileUri) .setLoop(false) .setAudioFileId(audioFileId) .setOperationContext(operationContext) .setCallbackUri(callbackUri); return playAudioWithResponse(playAudioRequest, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<PlayAudioResult>> playAudioWithResponseInternal( String audioFileUri, PlayAudioOptions playAudioOptions, Context context) { try { Objects.requireNonNull(audioFileUri, "'audioFileUri' cannot be null."); PlayAudioRequest request = new PlayAudioRequest().setAudioFileUri(audioFileUri); if (playAudioOptions != null) { request .setLoop(false) .setOperationContext(playAudioOptions.getOperationContext()) .setAudioFileId(playAudioOptions.getAudioFileId()) .setCallbackUri(playAudioOptions.getCallbackUri()); } return playAudioWithResponse(request, context); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<PlayAudioResult>> playAudioWithResponse(PlayAudioRequest playAudioRequest, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return serverCallInternal .playAudioWithResponseAsync(serverCallId, playAudioRequest, contextValue) .onErrorMap(CommunicationErrorException.class, CallingServerErrorConverter::translateException) .map(response -> new SimpleResponse<>(response, PlayAudioResultConverter.convert(response.getValue()))); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } }
Please move auth policy to after retry policy. We made a mistake in other SDKs wrt this.
private HttpPipeline createHttpPipeline(HttpClient httpClient) { if (pipeline != null) { return pipeline; } List<HttpPipelinePolicy> policyList = new ArrayList<>(); 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(); } policyList.add(createHttpPipelineAuthPolicy()); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policyList.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policyList.add(new RequestIdPolicy()); policyList.add((retryPolicy == null) ? new RetryPolicy() : retryPolicy); policyList.add(new CookiePolicy()); if (!customPolicies.isEmpty()) { policyList.addAll(customPolicies); } policyList.add(new HttpLoggingPolicy(getHttpLogOptions())); return new HttpPipelineBuilder().policies(policyList.toArray(new HttpPipelinePolicy[0])).httpClient(httpClient) .build(); }
policyList.add(createHttpPipelineAuthPolicy());
private HttpPipeline createHttpPipeline(HttpClient httpClient) { if (pipeline != null) { return pipeline; } List<HttpPipelinePolicy> policyList = new ArrayList<>(); 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(); } String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policyList.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policyList.add(new RequestIdPolicy()); policyList.add((retryPolicy == null) ? new RetryPolicy() : retryPolicy); policyList.add(createHttpPipelineAuthPolicy()); policyList.add(new CookiePolicy()); if (!customPolicies.isEmpty()) { policyList.addAll(customPolicies); } policyList.add(new HttpLoggingPolicy(getHttpLogOptions())); return new HttpPipelineBuilder().policies(policyList.toArray(new HttpPipelinePolicy[0])).httpClient(httpClient) .build(); }
class CallingServerClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String APP_CONFIG_PROPERTIES = "azure-communication-callingserver.properties"; private final ClientLogger logger = new ClientLogger(CallingServerClientBuilder.class); private String connectionString; private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private Configuration configuration; private final Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<>(); private ClientOptions clientOptions; private RetryPolicy retryPolicy; /** * Set endpoint of the service * * @param endpoint url of the service * @return CallingServerClientBuilder */ public CallingServerClientBuilder 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 CallingServerClientBuilder */ public CallingServerClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP * requests. * @return The updated {@link CallingServerClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CallingServerClientBuilder 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 CallingServerClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ public CallingServerClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Set connectionString to use * * @param connectionString connection string to set * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); this.connectionString = connectionString; return this; } /** * Sets the retry policy to use (using the RetryPolicy type). * * @param retryPolicy object to be applied * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' 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 {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder 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 {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link CallingServerClientBuilder} 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 CallingServerClientBuilder} of the service to be used when * making requests. * @return the updated CallingServerClientBuilder object */ public CallingServerClientBuilder serviceVersion(CallingServerClientBuilder version) { return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline field. * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder 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 The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, * UserAgentPolicy, RetryPolicy, and CookiePolicy. Additional HttpPolicies * specified by additionalPolicies will be applied after them * * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerAsyncClient buildAsyncClient() { return new CallingServerAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. Additional HttpPolicies specified by * additionalPolicies will be applied after them * * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClient buildClient() { return new CallingServerClient(buildAsyncClient()); } private AzureCommunicationCallingServerServiceImpl createServiceImpl() { boolean isConnectionStringSet = connectionString != null && !connectionString.trim().isEmpty(); boolean isEndpointSet = endpoint != null && !endpoint.trim().isEmpty(); boolean isAzureKeyCredentialSet = azureKeyCredential != null; boolean isTokenCredentialSet = tokenCredential != null; if (isConnectionStringSet && isEndpointSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'endpoint' are set. Just one may be used.")); } if (isConnectionStringSet && isAzureKeyCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'keyCredential' are set. Just one may be used.")); } if (isConnectionStringSet && isTokenCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'tokenCredential' are set. Just one may be used.")); } if (isAzureKeyCredentialSet && isTokenCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'tokenCredential' and 'keyCredential' are set. Just one may be used.")); } if (isConnectionStringSet) { CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); endpoint(endpoint).credential(new AzureKeyCredential(accessKey)); } Objects.requireNonNull(endpoint); if (pipeline == null) { Objects.requireNonNull(httpClient); } HttpPipeline builderPipeline = pipeline; if (pipeline == null) { builderPipeline = createHttpPipeline(httpClient); } AzureCommunicationCallingServerServiceImplBuilder clientBuilder = new AzureCommunicationCallingServerServiceImplBuilder(); clientBuilder.endpoint(endpoint).pipeline(builderPipeline); return clientBuilder.buildClient(); } /** * Allows the user to set a variety of client-related options, such as * user-agent string, headers, etc. * * @param clientOptions object to be applied * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (tokenCredential != null && azureKeyCredential != null) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'credential' and 'keyCredential' are set. Just one may be used.")); } if (tokenCredential != null) { return new BearerTokenAuthenticationPolicy(tokenCredential, "https: } else if (azureKeyCredential != null) { return new HmacAuthenticationPolicy(azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpLogOptions getHttpLogOptions() { if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } return httpLogOptions; } }
class CallingServerClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String APP_CONFIG_PROPERTIES = "azure-communication-callingserver.properties"; private final ClientLogger logger = new ClientLogger(CallingServerClientBuilder.class); private String connectionString; private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private Configuration configuration; private final Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<>(); private ClientOptions clientOptions; private RetryPolicy retryPolicy; /** * Set endpoint of the service * * @param endpoint url of the service * @return CallingServerClientBuilder */ public CallingServerClientBuilder 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 CallingServerClientBuilder */ public CallingServerClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP * requests. * @return The updated {@link CallingServerClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CallingServerClientBuilder 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 CallingServerClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ public CallingServerClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Set connectionString to use * * @param connectionString connection string to set * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); this.connectionString = connectionString; return this; } /** * Sets the retry policy to use (using the RetryPolicy type). * * @param retryPolicy object to be applied * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' 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 {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder 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 {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link CallingServerClientBuilder} 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 CallingServerClientBuilder} of the service to be used when * making requests. * @return the updated CallingServerClientBuilder object */ public CallingServerClientBuilder serviceVersion(CallingServerClientBuilder version) { return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline field. * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder 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 The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, * UserAgentPolicy, RetryPolicy, and CookiePolicy. Additional HttpPolicies * specified by additionalPolicies will be applied after them * * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerAsyncClient buildAsyncClient() { return new CallingServerAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. Additional HttpPolicies specified by * additionalPolicies will be applied after them * * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClient buildClient() { return new CallingServerClient(buildAsyncClient()); } private AzureCommunicationCallingServerServiceImpl createServiceImpl() { boolean isConnectionStringSet = connectionString != null && !connectionString.trim().isEmpty(); boolean isEndpointSet = endpoint != null && !endpoint.trim().isEmpty(); boolean isAzureKeyCredentialSet = azureKeyCredential != null; boolean isTokenCredentialSet = tokenCredential != null; if (isConnectionStringSet && isEndpointSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'endpoint' are set. Just one may be used.")); } if (isConnectionStringSet && isAzureKeyCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'keyCredential' are set. Just one may be used.")); } if (isConnectionStringSet && isTokenCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'tokenCredential' are set. Just one may be used.")); } if (isAzureKeyCredentialSet && isTokenCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'tokenCredential' and 'keyCredential' are set. Just one may be used.")); } if (isConnectionStringSet) { CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); endpoint(endpoint).credential(new AzureKeyCredential(accessKey)); } Objects.requireNonNull(endpoint); if (pipeline == null) { Objects.requireNonNull(httpClient); } HttpPipeline builderPipeline = pipeline; if (pipeline == null) { builderPipeline = createHttpPipeline(httpClient); } AzureCommunicationCallingServerServiceImplBuilder clientBuilder = new AzureCommunicationCallingServerServiceImplBuilder(); clientBuilder.endpoint(endpoint).pipeline(builderPipeline); return clientBuilder.buildClient(); } /** * Allows the user to set a variety of client-related options, such as * user-agent string, headers, etc. * * @param clientOptions object to be applied * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (tokenCredential != null && azureKeyCredential != null) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'credential' and 'keyCredential' are set. Just one may be used.")); } if (tokenCredential != null) { return new BearerTokenAuthenticationPolicy(tokenCredential, "https: } else if (azureKeyCredential != null) { return new HmacAuthenticationPolicy(azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpLogOptions getHttpLogOptions() { if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } return httpLogOptions; } }
Auth policy is moved after retry policy
private HttpPipeline createHttpPipeline(HttpClient httpClient) { if (pipeline != null) { return pipeline; } List<HttpPipelinePolicy> policyList = new ArrayList<>(); 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(); } policyList.add(createHttpPipelineAuthPolicy()); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policyList.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policyList.add(new RequestIdPolicy()); policyList.add((retryPolicy == null) ? new RetryPolicy() : retryPolicy); policyList.add(new CookiePolicy()); if (!customPolicies.isEmpty()) { policyList.addAll(customPolicies); } policyList.add(new HttpLoggingPolicy(getHttpLogOptions())); return new HttpPipelineBuilder().policies(policyList.toArray(new HttpPipelinePolicy[0])).httpClient(httpClient) .build(); }
policyList.add(createHttpPipelineAuthPolicy());
private HttpPipeline createHttpPipeline(HttpClient httpClient) { if (pipeline != null) { return pipeline; } List<HttpPipelinePolicy> policyList = new ArrayList<>(); 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(); } String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policyList.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration)); policyList.add(new RequestIdPolicy()); policyList.add((retryPolicy == null) ? new RetryPolicy() : retryPolicy); policyList.add(createHttpPipelineAuthPolicy()); policyList.add(new CookiePolicy()); if (!customPolicies.isEmpty()) { policyList.addAll(customPolicies); } policyList.add(new HttpLoggingPolicy(getHttpLogOptions())); return new HttpPipelineBuilder().policies(policyList.toArray(new HttpPipelinePolicy[0])).httpClient(httpClient) .build(); }
class CallingServerClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String APP_CONFIG_PROPERTIES = "azure-communication-callingserver.properties"; private final ClientLogger logger = new ClientLogger(CallingServerClientBuilder.class); private String connectionString; private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private Configuration configuration; private final Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<>(); private ClientOptions clientOptions; private RetryPolicy retryPolicy; /** * Set endpoint of the service * * @param endpoint url of the service * @return CallingServerClientBuilder */ public CallingServerClientBuilder 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 CallingServerClientBuilder */ public CallingServerClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP * requests. * @return The updated {@link CallingServerClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CallingServerClientBuilder 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 CallingServerClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ public CallingServerClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Set connectionString to use * * @param connectionString connection string to set * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); this.connectionString = connectionString; return this; } /** * Sets the retry policy to use (using the RetryPolicy type). * * @param retryPolicy object to be applied * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' 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 {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder 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 {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link CallingServerClientBuilder} 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 CallingServerClientBuilder} of the service to be used when * making requests. * @return the updated CallingServerClientBuilder object */ public CallingServerClientBuilder serviceVersion(CallingServerClientBuilder version) { return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline field. * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder 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 The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, * UserAgentPolicy, RetryPolicy, and CookiePolicy. Additional HttpPolicies * specified by additionalPolicies will be applied after them * * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerAsyncClient buildAsyncClient() { return new CallingServerAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. Additional HttpPolicies specified by * additionalPolicies will be applied after them * * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClient buildClient() { return new CallingServerClient(buildAsyncClient()); } private AzureCommunicationCallingServerServiceImpl createServiceImpl() { boolean isConnectionStringSet = connectionString != null && !connectionString.trim().isEmpty(); boolean isEndpointSet = endpoint != null && !endpoint.trim().isEmpty(); boolean isAzureKeyCredentialSet = azureKeyCredential != null; boolean isTokenCredentialSet = tokenCredential != null; if (isConnectionStringSet && isEndpointSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'endpoint' are set. Just one may be used.")); } if (isConnectionStringSet && isAzureKeyCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'keyCredential' are set. Just one may be used.")); } if (isConnectionStringSet && isTokenCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'tokenCredential' are set. Just one may be used.")); } if (isAzureKeyCredentialSet && isTokenCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'tokenCredential' and 'keyCredential' are set. Just one may be used.")); } if (isConnectionStringSet) { CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); endpoint(endpoint).credential(new AzureKeyCredential(accessKey)); } Objects.requireNonNull(endpoint); if (pipeline == null) { Objects.requireNonNull(httpClient); } HttpPipeline builderPipeline = pipeline; if (pipeline == null) { builderPipeline = createHttpPipeline(httpClient); } AzureCommunicationCallingServerServiceImplBuilder clientBuilder = new AzureCommunicationCallingServerServiceImplBuilder(); clientBuilder.endpoint(endpoint).pipeline(builderPipeline); return clientBuilder.buildClient(); } /** * Allows the user to set a variety of client-related options, such as * user-agent string, headers, etc. * * @param clientOptions object to be applied * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (tokenCredential != null && azureKeyCredential != null) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'credential' and 'keyCredential' are set. Just one may be used.")); } if (tokenCredential != null) { return new BearerTokenAuthenticationPolicy(tokenCredential, "https: } else if (azureKeyCredential != null) { return new HmacAuthenticationPolicy(azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpLogOptions getHttpLogOptions() { if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } return httpLogOptions; } }
class CallingServerClientBuilder { private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final String APP_CONFIG_PROPERTIES = "azure-communication-callingserver.properties"; private final ClientLogger logger = new ClientLogger(CallingServerClientBuilder.class); private String connectionString; private String endpoint; private AzureKeyCredential azureKeyCredential; private TokenCredential tokenCredential; private HttpClient httpClient; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private HttpPipeline pipeline; private Configuration configuration; private final Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES); private final List<HttpPipelinePolicy> customPolicies = new ArrayList<>(); private ClientOptions clientOptions; private RetryPolicy retryPolicy; /** * Set endpoint of the service * * @param endpoint url of the service * @return CallingServerClientBuilder */ public CallingServerClientBuilder 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 CallingServerClientBuilder */ public CallingServerClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = Objects.requireNonNull(pipeline, "'pipeline' cannot be null."); return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param tokenCredential {@link TokenCredential} used to authenticate HTTP * requests. * @return The updated {@link CallingServerClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ public CallingServerClientBuilder 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 CallingServerClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ public CallingServerClientBuilder credential(AzureKeyCredential keyCredential) { this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; } /** * Set connectionString to use * * @param connectionString connection string to set * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); this.connectionString = connectionString; return this; } /** * Sets the retry policy to use (using the RetryPolicy type). * * @param retryPolicy object to be applied * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' 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 {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder 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 {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Sets the {@link CallingServerClientBuilder} 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 CallingServerClientBuilder} of the service to be used when * making requests. * @return the updated CallingServerClientBuilder object */ public CallingServerClientBuilder serviceVersion(CallingServerClientBuilder version) { return this; } /** * Set httpClient to use * * @param httpClient httpClient to use, overridden by the pipeline field. * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder 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 The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; } /** * Create asynchronous client applying HMACAuthenticationPolicy, * UserAgentPolicy, RetryPolicy, and CookiePolicy. Additional HttpPolicies * specified by additionalPolicies will be applied after them * * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerAsyncClient buildAsyncClient() { return new CallingServerAsyncClient(createServiceImpl()); } /** * Create synchronous client applying HmacAuthenticationPolicy, UserAgentPolicy, * RetryPolicy, and CookiePolicy. Additional HttpPolicies specified by * additionalPolicies will be applied after them * * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClient buildClient() { return new CallingServerClient(buildAsyncClient()); } private AzureCommunicationCallingServerServiceImpl createServiceImpl() { boolean isConnectionStringSet = connectionString != null && !connectionString.trim().isEmpty(); boolean isEndpointSet = endpoint != null && !endpoint.trim().isEmpty(); boolean isAzureKeyCredentialSet = azureKeyCredential != null; boolean isTokenCredentialSet = tokenCredential != null; if (isConnectionStringSet && isEndpointSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'endpoint' are set. Just one may be used.")); } if (isConnectionStringSet && isAzureKeyCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'keyCredential' are set. Just one may be used.")); } if (isConnectionStringSet && isTokenCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'connectionString' and 'tokenCredential' are set. Just one may be used.")); } if (isAzureKeyCredentialSet && isTokenCredentialSet) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'tokenCredential' and 'keyCredential' are set. Just one may be used.")); } if (isConnectionStringSet) { CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString); String endpoint = connectionStringObject.getEndpoint(); String accessKey = connectionStringObject.getAccessKey(); endpoint(endpoint).credential(new AzureKeyCredential(accessKey)); } Objects.requireNonNull(endpoint); if (pipeline == null) { Objects.requireNonNull(httpClient); } HttpPipeline builderPipeline = pipeline; if (pipeline == null) { builderPipeline = createHttpPipeline(httpClient); } AzureCommunicationCallingServerServiceImplBuilder clientBuilder = new AzureCommunicationCallingServerServiceImplBuilder(); clientBuilder.endpoint(endpoint).pipeline(builderPipeline); return clientBuilder.buildClient(); } /** * Allows the user to set a variety of client-related options, such as * user-agent string, headers, etc. * * @param clientOptions object to be applied * @return The updated {@link CallingServerClientBuilder} object. */ public CallingServerClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } private HttpPipelinePolicy createHttpPipelineAuthPolicy() { if (tokenCredential != null && azureKeyCredential != null) { throw logger.logExceptionAsError(new IllegalArgumentException( "Both 'credential' and 'keyCredential' are set. Just one may be used.")); } if (tokenCredential != null) { return new BearerTokenAuthenticationPolicy(tokenCredential, "https: } else if (azureKeyCredential != null) { return new HmacAuthenticationPolicy(azureKeyCredential); } else { throw logger.logExceptionAsError( new IllegalArgumentException("Missing credential information while building a client.")); } } private HttpLogOptions getHttpLogOptions() { if (httpLogOptions == null) { httpLogOptions = new HttpLogOptions(); } return httpLogOptions; } }
We should throw NPE for both params if they're null.
public AmqpErrorContext(String namespace, Map<String, Object> errorInfo) { if (CoreUtils.isNullOrEmpty(namespace)) { throw new IllegalArgumentException("'namespace' cannot be null or empty"); } this.namespace = namespace; this.errorInfo = Objects.requireNonNull(errorInfo, "'errorInfo' cannot be null."); }
this.errorInfo = Objects.requireNonNull(errorInfo, "'errorInfo' cannot be null.");
public AmqpErrorContext(String namespace, Map<String, Object> errorInfo) { if (CoreUtils.isNullOrEmpty(namespace)) { throw new IllegalArgumentException("'namespace' cannot be null or empty"); } this.namespace = namespace; this.errorInfo = Objects.requireNonNull(errorInfo, "'errorInfo' cannot be null."); }
class AmqpErrorContext implements Serializable { static final String MESSAGE_PARAMETER_DELIMITER = ", "; private static final long serialVersionUID = -2819764407122954922L; private final String namespace; private final Map<String, Object> errorInfo; /** * Creates a new instance with the provided {@code namespace}. * * @param namespace The service namespace of the error. * * @throws IllegalArgumentException when {@code namespace} is {@code null} or empty. */ public AmqpErrorContext(String namespace) { if (CoreUtils.isNullOrEmpty(namespace)) { throw new IllegalArgumentException("'namespace' cannot be null or empty"); } this.namespace = namespace; this.errorInfo = null; } /** * Creates a new instance with the provided {@code namespace}. * * @param namespace The service namespace of the error. * @param errorInfo Additional information associated with the error. * * @throws IllegalArgumentException when {@code namespace} is {@code null} or empty. */ /** * Gets the namespace for this error. * * @return The namespace for this error. */ public String getNamespace() { return namespace; } /** * Gets the map carrying information about the error condition. * * @return Map carrying additional information about the error. */ public Map<String, Object> getErrorInfo() { return errorInfo != null ? Collections.unmodifiableMap(errorInfo) : Collections.emptyMap(); } /** * Creates a string representation of this ErrorContext. * * @return A string representation of this ErrorContext. */ @Override public String toString() { final String formatString = "NAMESPACE: %s. ERROR CONTEXT: %s"; if (errorInfo == null) { return String.format(Locale.ROOT, formatString, getNamespace(), "N/A"); } final StringBuilder builder = new StringBuilder(); errorInfo.forEach((key, value) -> builder.append(String.format("[%s: %s], ", key, value))); return String.format(Locale.ROOT, formatString, getNamespace(), builder.toString()); } }
class AmqpErrorContext implements Serializable { static final String MESSAGE_PARAMETER_DELIMITER = ", "; private static final long serialVersionUID = -2819764407122954922L; private final String namespace; private final Map<String, Object> errorInfo; /** * Creates a new instance with the provided {@code namespace}. * * @param namespace The service namespace of the error. * * @throws IllegalArgumentException when {@code namespace} is {@code null} or empty. */ public AmqpErrorContext(String namespace) { if (CoreUtils.isNullOrEmpty(namespace)) { throw new IllegalArgumentException("'namespace' cannot be null or empty"); } this.namespace = namespace; this.errorInfo = null; } /** * Creates a new instance with the provided {@code namespace}. * * @param namespace The service namespace of the error. * @param errorInfo Additional information associated with the error. * * @throws IllegalArgumentException when {@code namespace} is {@code null} or empty. */ /** * Gets the namespace for this error. * * @return The namespace for this error. */ public String getNamespace() { return namespace; } /** * Gets the map carrying information about the error condition. * * @return Map carrying additional information about the error. */ public Map<String, Object> getErrorInfo() { return errorInfo != null ? Collections.unmodifiableMap(errorInfo) : Collections.emptyMap(); } /** * Creates a string representation of this ErrorContext. * * @return A string representation of this ErrorContext. */ @Override public String toString() { final String formatString = "NAMESPACE: %s. ERROR CONTEXT: %s"; if (errorInfo == null) { return String.format(Locale.ROOT, formatString, getNamespace(), "N/A"); } final StringBuilder builder = new StringBuilder(); errorInfo.forEach((key, value) -> builder.append(String.format("[%s: %s], ", key, value))); return String.format(Locale.ROOT, formatString, getNamespace(), builder.toString()); } }
Would it be worthwhile to cache this string?
public String toString() { final String formatString = "NAMESPACE: %s. ERROR CONTEXT: %s"; if (errorInfo == null) { return String.format(Locale.ROOT, formatString, getNamespace(), "N/A"); } final StringBuilder builder = new StringBuilder(); errorInfo.forEach((key, value) -> builder.append(String.format("[%s: %s], ", key, value))); return String.format(Locale.ROOT, formatString, getNamespace(), builder.toString()); }
final String formatString = "NAMESPACE: %s. ERROR CONTEXT: %s";
public String toString() { final String formatString = "NAMESPACE: %s. ERROR CONTEXT: %s"; if (errorInfo == null) { return String.format(Locale.ROOT, formatString, getNamespace(), "N/A"); } final StringBuilder builder = new StringBuilder(); errorInfo.forEach((key, value) -> builder.append(String.format("[%s: %s], ", key, value))); return String.format(Locale.ROOT, formatString, getNamespace(), builder.toString()); }
class AmqpErrorContext implements Serializable { static final String MESSAGE_PARAMETER_DELIMITER = ", "; private static final long serialVersionUID = -2819764407122954922L; private final String namespace; private final Map<String, Object> errorInfo; /** * Creates a new instance with the provided {@code namespace}. * * @param namespace The service namespace of the error. * * @throws IllegalArgumentException when {@code namespace} is {@code null} or empty. */ public AmqpErrorContext(String namespace) { if (CoreUtils.isNullOrEmpty(namespace)) { throw new IllegalArgumentException("'namespace' cannot be null or empty"); } this.namespace = namespace; this.errorInfo = null; } /** * Creates a new instance with the provided {@code namespace}. * * @param namespace The service namespace of the error. * @param errorInfo Additional information associated with the error. * * @throws IllegalArgumentException when {@code namespace} is {@code null} or empty. */ public AmqpErrorContext(String namespace, Map<String, Object> errorInfo) { if (CoreUtils.isNullOrEmpty(namespace)) { throw new IllegalArgumentException("'namespace' cannot be null or empty"); } this.namespace = namespace; this.errorInfo = Objects.requireNonNull(errorInfo, "'errorInfo' cannot be null."); } /** * Gets the namespace for this error. * * @return The namespace for this error. */ public String getNamespace() { return namespace; } /** * Gets the map carrying information about the error condition. * * @return Map carrying additional information about the error. */ public Map<String, Object> getErrorInfo() { return errorInfo != null ? Collections.unmodifiableMap(errorInfo) : Collections.emptyMap(); } /** * Creates a string representation of this ErrorContext. * * @return A string representation of this ErrorContext. */ @Override }
class AmqpErrorContext implements Serializable { static final String MESSAGE_PARAMETER_DELIMITER = ", "; private static final long serialVersionUID = -2819764407122954922L; private final String namespace; private final Map<String, Object> errorInfo; /** * Creates a new instance with the provided {@code namespace}. * * @param namespace The service namespace of the error. * * @throws IllegalArgumentException when {@code namespace} is {@code null} or empty. */ public AmqpErrorContext(String namespace) { if (CoreUtils.isNullOrEmpty(namespace)) { throw new IllegalArgumentException("'namespace' cannot be null or empty"); } this.namespace = namespace; this.errorInfo = null; } /** * Creates a new instance with the provided {@code namespace}. * * @param namespace The service namespace of the error. * @param errorInfo Additional information associated with the error. * * @throws IllegalArgumentException when {@code namespace} is {@code null} or empty. */ public AmqpErrorContext(String namespace, Map<String, Object> errorInfo) { if (CoreUtils.isNullOrEmpty(namespace)) { throw new IllegalArgumentException("'namespace' cannot be null or empty"); } this.namespace = namespace; this.errorInfo = Objects.requireNonNull(errorInfo, "'errorInfo' cannot be null."); } /** * Gets the namespace for this error. * * @return The namespace for this error. */ public String getNamespace() { return namespace; } /** * Gets the map carrying information about the error condition. * * @return Map carrying additional information about the error. */ public Map<String, Object> getErrorInfo() { return errorInfo != null ? Collections.unmodifiableMap(errorInfo) : Collections.emptyMap(); } /** * Creates a string representation of this ErrorContext. * * @return A string representation of this ErrorContext. */ @Override }
And we can call `groupInformationFromGraph.setGroupIds(...)` and `groupInformationFromGraph.setGroupNames(...)` here instead of set in each test.
public void setup() { groupInformationFromGraph = new GroupInformation(); allowedGroupIds = groupInformationFromGraph.getGroupsId(); allowedGroupNames = groupInformationFromGraph.getGroupsName(); this.autoCloseable = MockitoAnnotations.openMocks(this); properties.setUserGroup(userGroup); properties.setGraphMembershipUri("https: Mockito.lenient().when(accessToken.getTokenValue()).thenReturn("fake-access-token"); userService = new AADOAuth2UserService(properties, graphClient); }
allowedGroupIds = groupInformationFromGraph.getGroupsId();
public void setup() { this.autoCloseable = MockitoAnnotations.openMocks(this); GroupInformation groupInformationFromGraph = new GroupInformation(); Set<String> groupNamesFromGraph = new HashSet<>(); Set<String> groupIdsFromGraph = new HashSet<>(); groupNamesFromGraph.add("group1"); groupNamesFromGraph.add("group2"); groupIdsFromGraph.add(GROUP_ID_1); groupIdsFromGraph.add(GROUP_ID_2); groupInformationFromGraph.setGroupsIds(groupIdsFromGraph); groupInformationFromGraph.setGroupsNames(groupNamesFromGraph); properties.setUserGroup(userGroup); properties.setGraphMembershipUri("https: Mockito.lenient().when(accessToken.getTokenValue()) .thenReturn("fake-access-token"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); }
class AADAccessTokenGroupRolesExtractionTest { @Mock private OAuth2AccessToken accessToken; @Mock private GraphClient graphClient; private AADAuthenticationProperties properties = new AADAuthenticationProperties(); private AADAuthenticationProperties.UserGroupProperties userGroup = new AADAuthenticationProperties.UserGroupProperties(); private AADOAuth2UserService userService; private AutoCloseable autoCloseable; private GroupInformation groupInformationFromGraph; private Set<String> allowedGroupNames; private Set<String> allowedGroupIds; @BeforeEach @AfterEach public void close() throws Exception { this.autoCloseable.close(); } @Test public void testGroupsName() { allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); userGroup.setAllowedGroupNames(customizeGroupName); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).hasSize(1); } @Test public void testGroupsId() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupId = new ArrayList<>(); customizeGroupId.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); userGroup.setAllowedGroupIds(allowedGroupIds); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(1); } @Test public void testGroupsNameAndGroupsId() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupNames.add("group1"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(2); } @Test public void testWithEnableFullList() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); userGroup.setEnableFullList(true); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); } @Test public void testWithoutEnableFullList() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); List<String> customizeGroupNames = new ArrayList<>(); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); customizeGroupNames.add("group1"); userGroup.setEnableFullList(false); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupNames); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(2); } @Test public void testAllGroupIds() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("all"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); userGroup.setEnableFullList(true); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); } }
class AADAccessTokenGroupRolesExtractionTest { private static final String GROUP_ID_1 = "d07c0bd6-4aab-45ac-b87c-23e8d00194ab"; private static final String GROUP_ID_2 = "6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"; private final AADAuthenticationProperties properties = new AADAuthenticationProperties(); private final AADAuthenticationProperties.UserGroupProperties userGroup = new AADAuthenticationProperties.UserGroupProperties(); private AutoCloseable autoCloseable; @Mock private OAuth2AccessToken accessToken; @Mock private GraphClient graphClient; @BeforeAll @AfterEach public void reset() { userGroup.setAllowedGroupNames(Collections.emptyList()); userGroup.setAllowedGroupIds(Collections.emptySet()); userGroup.setEnableFullList(false); } @AfterAll public void close() throws Exception { this.autoCloseable.close(); } @Test public void testAllowedGroupsNames() { List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(1); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); } @Test public void testAllowedGroupsIds() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); userGroup.setAllowedGroupIds(allowedGroupIds); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testAllowedGroupsNamesAndAllowedGroupsIds() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(2); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testWithEnableFullList() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); userGroup.setEnableFullList(true); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_2); } @Test public void testWithoutEnableFullList() { List<String> allowedGroupNames = new ArrayList<>(); Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); allowedGroupNames.add("group1"); userGroup.setEnableFullList(false); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(2); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testAllowedGroupIdsAllWithoutEnableFullList() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add("all"); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); userGroup.setEnableFullList(false); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_2); } @Test public void testIllegalGroupIdParam() { WebApplicationContextRunnerUtils .getContextRunnerWithRequiredProperties() .withPropertyValues( "azure.activedirectory.user-group.allowed-group-ids = all," + GROUP_ID_1 ) .run(context -> assertThrows(IllegalStateException.class, () -> context.getBean(AADAuthenticationProperties.class))); } }
Instead of creating the rule and then updating it, we should use the overload that takes CreateRuleOptions. https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-servicebus/7.2.3/com/azure/messaging/servicebus/administration/ServiceBusAdministrationClient.html#createRule-java.lang.String-java.lang.String-java.lang.String-com.azure.messaging.servicebus.administration.models.CreateRuleOptions-
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME);
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
>preferHeader [](http://example.com/codeflow?start=42&length=12) What happens if you end the preferHeader with a ','? If it is a no-op, you can directly do something like sb.append(include-statistics=true,) and not have to do if check for length and the second append.
Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery, Context context) { AtomicInteger id = new AtomicInteger(); List<BatchQueryRequest> requests = logsBatchQuery.getQueries() .stream() .map(query -> { QueryBody body = new QueryBody(query.getQuery()) .setWorkspaces(getAllWorkspaces(query)); StringBuilder sb = new StringBuilder(); if (query.isIncludeRendering()) { sb.append("include-render=true"); } if (query.isIncludeStatistics()) { if (sb.length() > 0) { sb.append(","); } sb.append("include-statistics=true"); } if (query.getServerTimeout() != null) { if (sb.length() > 0) { sb.append(","); } sb.append("wait="); sb.append(query.getServerTimeout().getSeconds()); } String preferHeader = sb.toString().isEmpty() ? null : sb.toString(); Map<String, String> headers = new HashMap<>(); headers.put("Prefer", preferHeader); return new BatchQueryRequest(String.valueOf(id.incrementAndGet()), body, query.getWorkspaceId()) .setHeaders(headers) .setPath("/query") .setMethod("POST"); }) .collect(Collectors.toList()); BatchRequest batchRequest = new BatchRequest(requests); return innerClient.getQueries().batchWithResponseAsync(batchRequest, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryBatchResult); }
headers.put("Prefer", preferHeader);
new AtomicInteger(); List<BatchQueryRequest> requests = logsBatchQuery.getQueries() .stream() .map(query -> { QueryBody body = new QueryBody(query.getQuery()) .setWorkspaces(getAllWorkspaces(query)); String preferHeader = buildPreferHeaderString(query); Map<String, String> headers = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(preferHeader)) { headers.put("Prefer", preferHeader); } return new BatchQueryRequest(String.valueOf(id.incrementAndGet()), body, query.getWorkspaceId()) .setHeaders(headers) .setPath("/query") .setMethod("POST"); }
class LogsQueryAsyncClient { private final AzureLogAnalyticsImpl innerClient; /** * Constructor that has the inner generated client to make the service call. * @param innerClient The inner generated client. */ LogsQueryAsyncClient(AzureLogAnalyticsImpl innerClient) { this.innerClient = innerClient; } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param workspaceId The workspaceId where the query should be executed. * @param query The Kusto query to fetch the logs. * @param timeSpan The time period for which the logs should be looked up. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsQueryResult> queryLogs(String workspaceId, String query, QueryTimeSpan timeSpan) { return queryLogsWithResponse(new LogsQueryOptions(workspaceId, query, timeSpan)) .map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param options The query options. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options) { return withContext(context -> queryLogsWithResponse(options, context)); } /** * Returns all the Azure Monitor logs matching the given batch of queries in the specified workspaceId. * @param workspaceId The workspaceId where the batch of queries should be executed. * @param queries A batch of Kusto queries. * @param timeSpan The time period for which the logs should be looked up. * @return A collection of query results corresponding to the input batch of queries. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsBatchQueryResultCollection> queryLogsBatch(String workspaceId, List<String> queries, QueryTimeSpan timeSpan) { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); queries.forEach(query -> logsBatchQuery.addQuery(workspaceId, query, timeSpan)); return queryLogsBatchWithResponse(logsBatchQuery).map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given batch of queries. * @param logsBatchQuery {@link LogsBatchQuery} containing a batch of queries. * @return A collection of query results corresponding to the input batch of queries.@return */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery) { return queryLogsBatchWithResponse(logsBatchQuery, Context.NONE); } Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery, Context context) { AtomicInteger id = ) .collect(Collectors.toList()); BatchRequest batchRequest = new BatchRequest(requests); return innerClient.getQueries().batchWithResponseAsync(batchRequest, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryBatchResult); } private Response<LogsBatchQueryResultCollection> convertToLogQueryBatchResult(Response<BatchResponse> response) { List<LogsBatchQueryResult> batchResults = new ArrayList<>(); LogsBatchQueryResultCollection logsBatchQueryResultCollection = new LogsBatchQueryResultCollection(batchResults); BatchResponse batchResponse = response.getValue(); for (BatchQueryResponse singleQueryResponse : batchResponse.getResponses()) { LogsBatchQueryResult logsBatchQueryResult = new LogsBatchQueryResult(singleQueryResponse.getId(), singleQueryResponse.getStatus(), getLogsQueryResult(singleQueryResponse.getBody())); batchResults.add(logsBatchQueryResult); } batchResults.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getId()))); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsBatchQueryResultCollection); } private LogsQueryError mapLogsQueryError(ErrorInfo errors) { if (errors != null) { List<LogsQueryErrorDetail> errorDetails = Collections.emptyList(); if (errors.getDetails() != null) { errorDetails = errors.getDetails() .stream() .map(errorDetail -> new LogsQueryErrorDetail(errorDetail.getCode(), errorDetail.getMessage(), errorDetail.getTarget(), errorDetail.getValue(), errorDetail.getResources(), errorDetail.getAdditionalProperties())) .collect(Collectors.toList()); } ErrorInfo innerError = errors.getInnererror(); ErrorInfo currentError = errors.getInnererror(); while (currentError != null) { innerError = currentError.getInnererror(); currentError = currentError.getInnererror(); } String code = errors.getCode(); if (errors.getCode() != null && innerError != null && errors.getCode().equals(innerError.getCode())) { code = innerError.getCode(); } return new LogsQueryError(errors.getMessage(), code, errorDetails); } return null; } Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options, Context context) { StringBuilder sb = new StringBuilder(); if (options.isIncludeRendering()) { sb.append("include-render=true"); } if (options.isIncludeStatistics()) { if (sb.length() > 0) { sb.append(","); } sb.append("include-statistics=true"); } if (options.getServerTimeout() != null) { if (sb.length() > 0) { sb.append(","); } sb.append("wait="); sb.append(options.getServerTimeout().getSeconds()); } String preferHeader = sb.toString().isEmpty() ? null : sb.toString(); QueryBody queryBody = new QueryBody(options.getQuery()); if (options.getTimeSpan() != null) { queryBody.setTimespan(options.getTimeSpan().toString()); } queryBody.setWorkspaces(getAllWorkspaces(options)); return innerClient .getQueries() .executeWithResponseAsync(options.getWorkspaceId(), queryBody, preferHeader, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryResult); } private Response<LogsQueryResult> convertToLogQueryResult(Response<QueryResults> response) { QueryResults queryResults = response.getValue(); LogsQueryResult logsQueryResult = getLogsQueryResult(queryResults); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsQueryResult); } private LogsQueryResult getLogsQueryResult(QueryResults queryResults) { List<LogsTable> tables = null; if (queryResults.getTables() != null) { tables = new ArrayList<>(); for (Table table : queryResults.getTables()) { List<LogsTableCell> tableCells = new ArrayList<>(); List<LogsTableRow> tableRows = new ArrayList<>(); List<LogsTableColumn> tableColumns = new ArrayList<>(); LogsTable logsTable = new LogsTable(tableCells, tableRows, tableColumns); tables.add(logsTable); List<List<String>> rows = table.getRows(); for (int i = 0; i < rows.size(); i++) { List<String> row = rows.get(i); LogsTableRow tableRow = new LogsTableRow(i, new ArrayList<>()); tableRows.add(tableRow); for (int j = 0; j < row.size(); j++) { LogsTableCell cell = new LogsTableCell(table.getColumns().get(j).getName(), table.getColumns().get(j).getType(), j, i, row.get(j)); tableCells.add(cell); tableRow.getTableRow().add(cell); } } } } LogsQueryStatistics statistics = null; if (queryResults.getStatistics() != null) { statistics = new LogsQueryStatistics(queryResults.getStatistics()); } LogsQueryResult logsQueryResult = new LogsQueryResult(tables, statistics, mapLogsQueryError(queryResults.getError())); return logsQueryResult; } private List<String> getAllWorkspaces(LogsQueryOptions body) { List<String> allWorkspaces = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(body.getWorkspaceNames())) { allWorkspaces.addAll(body.getWorkspaceNames()); } if (!CoreUtils.isNullOrEmpty(body.getAzureResourceIds())) { allWorkspaces.addAll(body.getAzureResourceIds()); } if (!CoreUtils.isNullOrEmpty(body.getQualifiedWorkspaceNames())) { allWorkspaces.addAll(body.getQualifiedWorkspaceNames()); } if (!CoreUtils.isNullOrEmpty(body.getWorkspaceIds())) { allWorkspaces.addAll(body.getWorkspaceIds()); } return allWorkspaces; } }
class LogsQueryAsyncClient { private final AzureLogAnalyticsImpl innerClient; /** * Constructor that has the inner generated client to make the service call. * @param innerClient The inner generated client. */ LogsQueryAsyncClient(AzureLogAnalyticsImpl innerClient) { this.innerClient = innerClient; } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param workspaceId The workspaceId where the query should be executed. * @param query The Kusto query to fetch the logs. * @param timeSpan The time period for which the logs should be looked up. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsQueryResult> queryLogs(String workspaceId, String query, QueryTimeSpan timeSpan) { return queryLogsWithResponse(new LogsQueryOptions(workspaceId, query, timeSpan)) .map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param options The query options. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options) { return withContext(context -> queryLogsWithResponse(options, context)); } /** * Returns all the Azure Monitor logs matching the given batch of queries in the specified workspaceId. * @param workspaceId The workspaceId where the batch of queries should be executed. * @param queries A batch of Kusto queries. * @param timeSpan The time period for which the logs should be looked up. * @return A collection of query results corresponding to the input batch of queries. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsBatchQueryResultCollection> queryLogsBatch(String workspaceId, List<String> queries, QueryTimeSpan timeSpan) { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); queries.forEach(query -> logsBatchQuery.addQuery(workspaceId, query, timeSpan)); return queryLogsBatchWithResponse(logsBatchQuery).map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given batch of queries. * @param logsBatchQuery {@link LogsBatchQuery} containing a batch of queries. * @return A collection of query results corresponding to the input batch of queries.@return */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery) { return queryLogsBatchWithResponse(logsBatchQuery, Context.NONE); } Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery, Context context) { AtomicInteger id = ) .collect(Collectors.toList()); BatchRequest batchRequest = new BatchRequest(requests); return innerClient.getQueries().batchWithResponseAsync(batchRequest, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryBatchResult); } private String buildPreferHeaderString(LogsQueryOptions query) { StringBuilder sb = new StringBuilder(); if (query.isIncludeRendering()) { sb.append("include-render=true"); } if (query.isIncludeStatistics()) { if (sb.length() > 0) { sb.append(","); } sb.append("include-statistics=true"); } if (query.getServerTimeout() != null) { if (sb.length() > 0) { sb.append(","); } sb.append("wait="); sb.append(query.getServerTimeout().getSeconds()); } return sb.toString().isEmpty() ? null : sb.toString(); } private Response<LogsBatchQueryResultCollection> convertToLogQueryBatchResult(Response<BatchResponse> response) { List<LogsBatchQueryResult> batchResults = new ArrayList<>(); LogsBatchQueryResultCollection logsBatchQueryResultCollection = new LogsBatchQueryResultCollection(batchResults); BatchResponse batchResponse = response.getValue(); for (BatchQueryResponse singleQueryResponse : batchResponse.getResponses()) { LogsBatchQueryResult logsBatchQueryResult = new LogsBatchQueryResult(singleQueryResponse.getId(), singleQueryResponse.getStatus(), getLogsQueryResult(singleQueryResponse.getBody())); batchResults.add(logsBatchQueryResult); } batchResults.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getId()))); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsBatchQueryResultCollection); } private LogsQueryError mapLogsQueryError(ErrorInfo errors) { if (errors != null) { List<LogsQueryErrorDetail> errorDetails = Collections.emptyList(); if (errors.getDetails() != null) { errorDetails = errors.getDetails() .stream() .map(errorDetail -> new LogsQueryErrorDetail(errorDetail.getCode(), errorDetail.getMessage(), errorDetail.getTarget(), errorDetail.getValue(), errorDetail.getResources(), errorDetail.getAdditionalProperties())) .collect(Collectors.toList()); } ErrorInfo innerError = errors.getInnererror(); ErrorInfo currentError = errors.getInnererror(); while (currentError != null) { innerError = currentError.getInnererror(); currentError = currentError.getInnererror(); } String code = errors.getCode(); if (errors.getCode() != null && innerError != null && errors.getCode().equals(innerError.getCode())) { code = innerError.getCode(); } return new LogsQueryError(errors.getMessage(), code, errorDetails); } return null; } Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options, Context context) { String preferHeader = buildPreferHeaderString(options); QueryBody queryBody = new QueryBody(options.getQuery()); if (options.getTimeSpan() != null) { queryBody.setTimespan(options.getTimeSpan().toString()); } queryBody.setWorkspaces(getAllWorkspaces(options)); return innerClient .getQueries() .executeWithResponseAsync(options.getWorkspaceId(), queryBody, preferHeader, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryResult); } private Response<LogsQueryResult> convertToLogQueryResult(Response<QueryResults> response) { QueryResults queryResults = response.getValue(); LogsQueryResult logsQueryResult = getLogsQueryResult(queryResults); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsQueryResult); } private LogsQueryResult getLogsQueryResult(QueryResults queryResults) { List<LogsTable> tables = null; if (queryResults.getTables() != null) { tables = new ArrayList<>(); for (Table table : queryResults.getTables()) { List<LogsTableCell> tableCells = new ArrayList<>(); List<LogsTableRow> tableRows = new ArrayList<>(); List<LogsTableColumn> tableColumns = new ArrayList<>(); LogsTable logsTable = new LogsTable(tableCells, tableRows, tableColumns); tables.add(logsTable); List<List<String>> rows = table.getRows(); for (int i = 0; i < rows.size(); i++) { List<String> row = rows.get(i); LogsTableRow tableRow = new LogsTableRow(i, new ArrayList<>()); tableRows.add(tableRow); for (int j = 0; j < row.size(); j++) { LogsTableCell cell = new LogsTableCell(table.getColumns().get(j).getName(), table.getColumns().get(j).getType(), j, i, row.get(j)); tableCells.add(cell); tableRow.getTableRow().add(cell); } } } } LogsQueryStatistics statistics = null; if (queryResults.getStatistics() != null) { statistics = new LogsQueryStatistics(queryResults.getStatistics()); } LogsQueryResult logsQueryResult = new LogsQueryResult(tables, statistics, mapLogsQueryError(queryResults.getError())); return logsQueryResult; } private List<String> getAllWorkspaces(LogsQueryOptions body) { List<String> allWorkspaces = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(body.getWorkspaceNames())) { allWorkspaces.addAll(body.getWorkspaceNames()); } if (!CoreUtils.isNullOrEmpty(body.getAzureResourceIds())) { allWorkspaces.addAll(body.getAzureResourceIds()); } if (!CoreUtils.isNullOrEmpty(body.getQualifiedWorkspaceNames())) { allWorkspaces.addAll(body.getQualifiedWorkspaceNames()); } if (!CoreUtils.isNullOrEmpty(body.getWorkspaceIds())) { allWorkspaces.addAll(body.getWorkspaceIds()); } return allWorkspaces; } }
I think it shouldn't matter if the preferHeader ends with `,` but it's better to keep it well-formatted as defined in the RFC for prefer headers.
Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery, Context context) { AtomicInteger id = new AtomicInteger(); List<BatchQueryRequest> requests = logsBatchQuery.getQueries() .stream() .map(query -> { QueryBody body = new QueryBody(query.getQuery()) .setWorkspaces(getAllWorkspaces(query)); StringBuilder sb = new StringBuilder(); if (query.isIncludeRendering()) { sb.append("include-render=true"); } if (query.isIncludeStatistics()) { if (sb.length() > 0) { sb.append(","); } sb.append("include-statistics=true"); } if (query.getServerTimeout() != null) { if (sb.length() > 0) { sb.append(","); } sb.append("wait="); sb.append(query.getServerTimeout().getSeconds()); } String preferHeader = sb.toString().isEmpty() ? null : sb.toString(); Map<String, String> headers = new HashMap<>(); headers.put("Prefer", preferHeader); return new BatchQueryRequest(String.valueOf(id.incrementAndGet()), body, query.getWorkspaceId()) .setHeaders(headers) .setPath("/query") .setMethod("POST"); }) .collect(Collectors.toList()); BatchRequest batchRequest = new BatchRequest(requests); return innerClient.getQueries().batchWithResponseAsync(batchRequest, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryBatchResult); }
headers.put("Prefer", preferHeader);
new AtomicInteger(); List<BatchQueryRequest> requests = logsBatchQuery.getQueries() .stream() .map(query -> { QueryBody body = new QueryBody(query.getQuery()) .setWorkspaces(getAllWorkspaces(query)); String preferHeader = buildPreferHeaderString(query); Map<String, String> headers = new HashMap<>(); if (!CoreUtils.isNullOrEmpty(preferHeader)) { headers.put("Prefer", preferHeader); } return new BatchQueryRequest(String.valueOf(id.incrementAndGet()), body, query.getWorkspaceId()) .setHeaders(headers) .setPath("/query") .setMethod("POST"); }
class LogsQueryAsyncClient { private final AzureLogAnalyticsImpl innerClient; /** * Constructor that has the inner generated client to make the service call. * @param innerClient The inner generated client. */ LogsQueryAsyncClient(AzureLogAnalyticsImpl innerClient) { this.innerClient = innerClient; } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param workspaceId The workspaceId where the query should be executed. * @param query The Kusto query to fetch the logs. * @param timeSpan The time period for which the logs should be looked up. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsQueryResult> queryLogs(String workspaceId, String query, QueryTimeSpan timeSpan) { return queryLogsWithResponse(new LogsQueryOptions(workspaceId, query, timeSpan)) .map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param options The query options. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options) { return withContext(context -> queryLogsWithResponse(options, context)); } /** * Returns all the Azure Monitor logs matching the given batch of queries in the specified workspaceId. * @param workspaceId The workspaceId where the batch of queries should be executed. * @param queries A batch of Kusto queries. * @param timeSpan The time period for which the logs should be looked up. * @return A collection of query results corresponding to the input batch of queries. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsBatchQueryResultCollection> queryLogsBatch(String workspaceId, List<String> queries, QueryTimeSpan timeSpan) { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); queries.forEach(query -> logsBatchQuery.addQuery(workspaceId, query, timeSpan)); return queryLogsBatchWithResponse(logsBatchQuery).map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given batch of queries. * @param logsBatchQuery {@link LogsBatchQuery} containing a batch of queries. * @return A collection of query results corresponding to the input batch of queries.@return */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery) { return queryLogsBatchWithResponse(logsBatchQuery, Context.NONE); } Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery, Context context) { AtomicInteger id = ) .collect(Collectors.toList()); BatchRequest batchRequest = new BatchRequest(requests); return innerClient.getQueries().batchWithResponseAsync(batchRequest, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryBatchResult); } private Response<LogsBatchQueryResultCollection> convertToLogQueryBatchResult(Response<BatchResponse> response) { List<LogsBatchQueryResult> batchResults = new ArrayList<>(); LogsBatchQueryResultCollection logsBatchQueryResultCollection = new LogsBatchQueryResultCollection(batchResults); BatchResponse batchResponse = response.getValue(); for (BatchQueryResponse singleQueryResponse : batchResponse.getResponses()) { LogsBatchQueryResult logsBatchQueryResult = new LogsBatchQueryResult(singleQueryResponse.getId(), singleQueryResponse.getStatus(), getLogsQueryResult(singleQueryResponse.getBody())); batchResults.add(logsBatchQueryResult); } batchResults.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getId()))); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsBatchQueryResultCollection); } private LogsQueryError mapLogsQueryError(ErrorInfo errors) { if (errors != null) { List<LogsQueryErrorDetail> errorDetails = Collections.emptyList(); if (errors.getDetails() != null) { errorDetails = errors.getDetails() .stream() .map(errorDetail -> new LogsQueryErrorDetail(errorDetail.getCode(), errorDetail.getMessage(), errorDetail.getTarget(), errorDetail.getValue(), errorDetail.getResources(), errorDetail.getAdditionalProperties())) .collect(Collectors.toList()); } ErrorInfo innerError = errors.getInnererror(); ErrorInfo currentError = errors.getInnererror(); while (currentError != null) { innerError = currentError.getInnererror(); currentError = currentError.getInnererror(); } String code = errors.getCode(); if (errors.getCode() != null && innerError != null && errors.getCode().equals(innerError.getCode())) { code = innerError.getCode(); } return new LogsQueryError(errors.getMessage(), code, errorDetails); } return null; } Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options, Context context) { StringBuilder sb = new StringBuilder(); if (options.isIncludeRendering()) { sb.append("include-render=true"); } if (options.isIncludeStatistics()) { if (sb.length() > 0) { sb.append(","); } sb.append("include-statistics=true"); } if (options.getServerTimeout() != null) { if (sb.length() > 0) { sb.append(","); } sb.append("wait="); sb.append(options.getServerTimeout().getSeconds()); } String preferHeader = sb.toString().isEmpty() ? null : sb.toString(); QueryBody queryBody = new QueryBody(options.getQuery()); if (options.getTimeSpan() != null) { queryBody.setTimespan(options.getTimeSpan().toString()); } queryBody.setWorkspaces(getAllWorkspaces(options)); return innerClient .getQueries() .executeWithResponseAsync(options.getWorkspaceId(), queryBody, preferHeader, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryResult); } private Response<LogsQueryResult> convertToLogQueryResult(Response<QueryResults> response) { QueryResults queryResults = response.getValue(); LogsQueryResult logsQueryResult = getLogsQueryResult(queryResults); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsQueryResult); } private LogsQueryResult getLogsQueryResult(QueryResults queryResults) { List<LogsTable> tables = null; if (queryResults.getTables() != null) { tables = new ArrayList<>(); for (Table table : queryResults.getTables()) { List<LogsTableCell> tableCells = new ArrayList<>(); List<LogsTableRow> tableRows = new ArrayList<>(); List<LogsTableColumn> tableColumns = new ArrayList<>(); LogsTable logsTable = new LogsTable(tableCells, tableRows, tableColumns); tables.add(logsTable); List<List<String>> rows = table.getRows(); for (int i = 0; i < rows.size(); i++) { List<String> row = rows.get(i); LogsTableRow tableRow = new LogsTableRow(i, new ArrayList<>()); tableRows.add(tableRow); for (int j = 0; j < row.size(); j++) { LogsTableCell cell = new LogsTableCell(table.getColumns().get(j).getName(), table.getColumns().get(j).getType(), j, i, row.get(j)); tableCells.add(cell); tableRow.getTableRow().add(cell); } } } } LogsQueryStatistics statistics = null; if (queryResults.getStatistics() != null) { statistics = new LogsQueryStatistics(queryResults.getStatistics()); } LogsQueryResult logsQueryResult = new LogsQueryResult(tables, statistics, mapLogsQueryError(queryResults.getError())); return logsQueryResult; } private List<String> getAllWorkspaces(LogsQueryOptions body) { List<String> allWorkspaces = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(body.getWorkspaceNames())) { allWorkspaces.addAll(body.getWorkspaceNames()); } if (!CoreUtils.isNullOrEmpty(body.getAzureResourceIds())) { allWorkspaces.addAll(body.getAzureResourceIds()); } if (!CoreUtils.isNullOrEmpty(body.getQualifiedWorkspaceNames())) { allWorkspaces.addAll(body.getQualifiedWorkspaceNames()); } if (!CoreUtils.isNullOrEmpty(body.getWorkspaceIds())) { allWorkspaces.addAll(body.getWorkspaceIds()); } return allWorkspaces; } }
class LogsQueryAsyncClient { private final AzureLogAnalyticsImpl innerClient; /** * Constructor that has the inner generated client to make the service call. * @param innerClient The inner generated client. */ LogsQueryAsyncClient(AzureLogAnalyticsImpl innerClient) { this.innerClient = innerClient; } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param workspaceId The workspaceId where the query should be executed. * @param query The Kusto query to fetch the logs. * @param timeSpan The time period for which the logs should be looked up. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsQueryResult> queryLogs(String workspaceId, String query, QueryTimeSpan timeSpan) { return queryLogsWithResponse(new LogsQueryOptions(workspaceId, query, timeSpan)) .map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param options The query options. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options) { return withContext(context -> queryLogsWithResponse(options, context)); } /** * Returns all the Azure Monitor logs matching the given batch of queries in the specified workspaceId. * @param workspaceId The workspaceId where the batch of queries should be executed. * @param queries A batch of Kusto queries. * @param timeSpan The time period for which the logs should be looked up. * @return A collection of query results corresponding to the input batch of queries. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsBatchQueryResultCollection> queryLogsBatch(String workspaceId, List<String> queries, QueryTimeSpan timeSpan) { LogsBatchQuery logsBatchQuery = new LogsBatchQuery(); queries.forEach(query -> logsBatchQuery.addQuery(workspaceId, query, timeSpan)); return queryLogsBatchWithResponse(logsBatchQuery).map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given batch of queries. * @param logsBatchQuery {@link LogsBatchQuery} containing a batch of queries. * @return A collection of query results corresponding to the input batch of queries.@return */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery) { return queryLogsBatchWithResponse(logsBatchQuery, Context.NONE); } Mono<Response<LogsBatchQueryResultCollection>> queryLogsBatchWithResponse(LogsBatchQuery logsBatchQuery, Context context) { AtomicInteger id = ) .collect(Collectors.toList()); BatchRequest batchRequest = new BatchRequest(requests); return innerClient.getQueries().batchWithResponseAsync(batchRequest, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryBatchResult); } private String buildPreferHeaderString(LogsQueryOptions query) { StringBuilder sb = new StringBuilder(); if (query.isIncludeRendering()) { sb.append("include-render=true"); } if (query.isIncludeStatistics()) { if (sb.length() > 0) { sb.append(","); } sb.append("include-statistics=true"); } if (query.getServerTimeout() != null) { if (sb.length() > 0) { sb.append(","); } sb.append("wait="); sb.append(query.getServerTimeout().getSeconds()); } return sb.toString().isEmpty() ? null : sb.toString(); } private Response<LogsBatchQueryResultCollection> convertToLogQueryBatchResult(Response<BatchResponse> response) { List<LogsBatchQueryResult> batchResults = new ArrayList<>(); LogsBatchQueryResultCollection logsBatchQueryResultCollection = new LogsBatchQueryResultCollection(batchResults); BatchResponse batchResponse = response.getValue(); for (BatchQueryResponse singleQueryResponse : batchResponse.getResponses()) { LogsBatchQueryResult logsBatchQueryResult = new LogsBatchQueryResult(singleQueryResponse.getId(), singleQueryResponse.getStatus(), getLogsQueryResult(singleQueryResponse.getBody())); batchResults.add(logsBatchQueryResult); } batchResults.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getId()))); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsBatchQueryResultCollection); } private LogsQueryError mapLogsQueryError(ErrorInfo errors) { if (errors != null) { List<LogsQueryErrorDetail> errorDetails = Collections.emptyList(); if (errors.getDetails() != null) { errorDetails = errors.getDetails() .stream() .map(errorDetail -> new LogsQueryErrorDetail(errorDetail.getCode(), errorDetail.getMessage(), errorDetail.getTarget(), errorDetail.getValue(), errorDetail.getResources(), errorDetail.getAdditionalProperties())) .collect(Collectors.toList()); } ErrorInfo innerError = errors.getInnererror(); ErrorInfo currentError = errors.getInnererror(); while (currentError != null) { innerError = currentError.getInnererror(); currentError = currentError.getInnererror(); } String code = errors.getCode(); if (errors.getCode() != null && innerError != null && errors.getCode().equals(innerError.getCode())) { code = innerError.getCode(); } return new LogsQueryError(errors.getMessage(), code, errorDetails); } return null; } Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options, Context context) { String preferHeader = buildPreferHeaderString(options); QueryBody queryBody = new QueryBody(options.getQuery()); if (options.getTimeSpan() != null) { queryBody.setTimespan(options.getTimeSpan().toString()); } queryBody.setWorkspaces(getAllWorkspaces(options)); return innerClient .getQueries() .executeWithResponseAsync(options.getWorkspaceId(), queryBody, preferHeader, context) .onErrorMap(ex -> { if (ex instanceof ErrorResponseException) { ErrorResponseException error = (ErrorResponseException) ex; ErrorInfo errorInfo = error.getValue().getError(); return new LogsQueryException(error.getResponse(), mapLogsQueryError(errorInfo)); } return ex; }) .map(this::convertToLogQueryResult); } private Response<LogsQueryResult> convertToLogQueryResult(Response<QueryResults> response) { QueryResults queryResults = response.getValue(); LogsQueryResult logsQueryResult = getLogsQueryResult(queryResults); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsQueryResult); } private LogsQueryResult getLogsQueryResult(QueryResults queryResults) { List<LogsTable> tables = null; if (queryResults.getTables() != null) { tables = new ArrayList<>(); for (Table table : queryResults.getTables()) { List<LogsTableCell> tableCells = new ArrayList<>(); List<LogsTableRow> tableRows = new ArrayList<>(); List<LogsTableColumn> tableColumns = new ArrayList<>(); LogsTable logsTable = new LogsTable(tableCells, tableRows, tableColumns); tables.add(logsTable); List<List<String>> rows = table.getRows(); for (int i = 0; i < rows.size(); i++) { List<String> row = rows.get(i); LogsTableRow tableRow = new LogsTableRow(i, new ArrayList<>()); tableRows.add(tableRow); for (int j = 0; j < row.size(); j++) { LogsTableCell cell = new LogsTableCell(table.getColumns().get(j).getName(), table.getColumns().get(j).getType(), j, i, row.get(j)); tableCells.add(cell); tableRow.getTableRow().add(cell); } } } } LogsQueryStatistics statistics = null; if (queryResults.getStatistics() != null) { statistics = new LogsQueryStatistics(queryResults.getStatistics()); } LogsQueryResult logsQueryResult = new LogsQueryResult(tables, statistics, mapLogsQueryError(queryResults.getError())); return logsQueryResult; } private List<String> getAllWorkspaces(LogsQueryOptions body) { List<String> allWorkspaces = new ArrayList<>(); if (!CoreUtils.isNullOrEmpty(body.getWorkspaceNames())) { allWorkspaces.addAll(body.getWorkspaceNames()); } if (!CoreUtils.isNullOrEmpty(body.getAzureResourceIds())) { allWorkspaces.addAll(body.getAzureResourceIds()); } if (!CoreUtils.isNullOrEmpty(body.getQualifiedWorkspaceNames())) { allWorkspaces.addAll(body.getQualifiedWorkspaceNames()); } if (!CoreUtils.isNullOrEmpty(body.getWorkspaceIds())) { allWorkspaces.addAll(body.getWorkspaceIds()); } return allWorkspaces; } }
It should be `groupIdsFromGraph`?
public void setup() { groupInformationFromGraph = new GroupInformation(); allowedGroupIds = groupInformationFromGraph.getGroupsId(); allowedGroupNames = groupInformationFromGraph.getGroupsName(); this.autoCloseable = MockitoAnnotations.openMocks(this); properties.setUserGroup(userGroup); properties.setGraphMembershipUri("https: Mockito.lenient().when(accessToken.getTokenValue()).thenReturn("fake-access-token"); userService = new AADOAuth2UserService(properties, graphClient); }
allowedGroupIds = groupInformationFromGraph.getGroupsId();
public void setup() { this.autoCloseable = MockitoAnnotations.openMocks(this); GroupInformation groupInformationFromGraph = new GroupInformation(); Set<String> groupNamesFromGraph = new HashSet<>(); Set<String> groupIdsFromGraph = new HashSet<>(); groupNamesFromGraph.add("group1"); groupNamesFromGraph.add("group2"); groupIdsFromGraph.add(GROUP_ID_1); groupIdsFromGraph.add(GROUP_ID_2); groupInformationFromGraph.setGroupsIds(groupIdsFromGraph); groupInformationFromGraph.setGroupsNames(groupNamesFromGraph); properties.setUserGroup(userGroup); properties.setGraphMembershipUri("https: Mockito.lenient().when(accessToken.getTokenValue()) .thenReturn("fake-access-token"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); }
class AADAccessTokenGroupRolesExtractionTest { @Mock private OAuth2AccessToken accessToken; @Mock private GraphClient graphClient; private AADAuthenticationProperties properties = new AADAuthenticationProperties(); private AADAuthenticationProperties.UserGroupProperties userGroup = new AADAuthenticationProperties.UserGroupProperties(); private AADOAuth2UserService userService; private AutoCloseable autoCloseable; private GroupInformation groupInformationFromGraph; private Set<String> allowedGroupNames; private Set<String> allowedGroupIds; @BeforeEach @AfterEach public void close() throws Exception { this.autoCloseable.close(); } @Test public void testGroupsName() { allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); userGroup.setAllowedGroupNames(customizeGroupName); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).hasSize(1); } @Test public void testGroupsId() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupId = new ArrayList<>(); customizeGroupId.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); userGroup.setAllowedGroupIds(allowedGroupIds); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(1); } @Test public void testGroupsNameAndGroupsId() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupNames.add("group1"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(2); } @Test public void testWithEnableFullList() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); userGroup.setEnableFullList(true); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); } @Test public void testWithoutEnableFullList() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); List<String> customizeGroupNames = new ArrayList<>(); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); customizeGroupNames.add("group1"); userGroup.setEnableFullList(false); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupNames); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(2); } @Test public void testAllGroupIds() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("all"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); userGroup.setEnableFullList(true); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); } }
class AADAccessTokenGroupRolesExtractionTest { private static final String GROUP_ID_1 = "d07c0bd6-4aab-45ac-b87c-23e8d00194ab"; private static final String GROUP_ID_2 = "6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"; private final AADAuthenticationProperties properties = new AADAuthenticationProperties(); private final AADAuthenticationProperties.UserGroupProperties userGroup = new AADAuthenticationProperties.UserGroupProperties(); private AutoCloseable autoCloseable; @Mock private OAuth2AccessToken accessToken; @Mock private GraphClient graphClient; @BeforeAll @AfterEach public void reset() { userGroup.setAllowedGroupNames(Collections.emptyList()); userGroup.setAllowedGroupIds(Collections.emptySet()); userGroup.setEnableFullList(false); } @AfterAll public void close() throws Exception { this.autoCloseable.close(); } @Test public void testAllowedGroupsNames() { List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(1); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); } @Test public void testAllowedGroupsIds() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); userGroup.setAllowedGroupIds(allowedGroupIds); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testAllowedGroupsNamesAndAllowedGroupsIds() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(2); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testWithEnableFullList() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); userGroup.setEnableFullList(true); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_2); } @Test public void testWithoutEnableFullList() { List<String> allowedGroupNames = new ArrayList<>(); Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); allowedGroupNames.add("group1"); userGroup.setEnableFullList(false); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(2); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testAllowedGroupIdsAllWithoutEnableFullList() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add("all"); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); userGroup.setEnableFullList(false); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_2); } @Test public void testIllegalGroupIdParam() { WebApplicationContextRunnerUtils .getContextRunnerWithRequiredProperties() .withPropertyValues( "azure.activedirectory.user-group.allowed-group-ids = all," + GROUP_ID_1 ) .run(context -> assertThrows(IllegalStateException.class, () -> context.getBean(AADAuthenticationProperties.class))); } }
``` Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); ``` Can put into `setup()`, too.
public void setup() { groupInformationFromGraph = new GroupInformation(); allowedGroupIds = groupInformationFromGraph.getGroupsId(); allowedGroupNames = groupInformationFromGraph.getGroupsName(); this.autoCloseable = MockitoAnnotations.openMocks(this); properties.setUserGroup(userGroup); properties.setGraphMembershipUri("https: Mockito.lenient().when(accessToken.getTokenValue()).thenReturn("fake-access-token"); userService = new AADOAuth2UserService(properties, graphClient); }
allowedGroupIds = groupInformationFromGraph.getGroupsId();
public void setup() { this.autoCloseable = MockitoAnnotations.openMocks(this); GroupInformation groupInformationFromGraph = new GroupInformation(); Set<String> groupNamesFromGraph = new HashSet<>(); Set<String> groupIdsFromGraph = new HashSet<>(); groupNamesFromGraph.add("group1"); groupNamesFromGraph.add("group2"); groupIdsFromGraph.add(GROUP_ID_1); groupIdsFromGraph.add(GROUP_ID_2); groupInformationFromGraph.setGroupsIds(groupIdsFromGraph); groupInformationFromGraph.setGroupsNames(groupNamesFromGraph); properties.setUserGroup(userGroup); properties.setGraphMembershipUri("https: Mockito.lenient().when(accessToken.getTokenValue()) .thenReturn("fake-access-token"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); }
class AADAccessTokenGroupRolesExtractionTest { @Mock private OAuth2AccessToken accessToken; @Mock private GraphClient graphClient; private AADAuthenticationProperties properties = new AADAuthenticationProperties(); private AADAuthenticationProperties.UserGroupProperties userGroup = new AADAuthenticationProperties.UserGroupProperties(); private AADOAuth2UserService userService; private AutoCloseable autoCloseable; private GroupInformation groupInformationFromGraph; private Set<String> allowedGroupNames; private Set<String> allowedGroupIds; @BeforeEach @AfterEach public void close() throws Exception { this.autoCloseable.close(); } @Test public void testGroupsName() { allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); userGroup.setAllowedGroupNames(customizeGroupName); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).hasSize(1); } @Test public void testGroupsId() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupId = new ArrayList<>(); customizeGroupId.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); userGroup.setAllowedGroupIds(allowedGroupIds); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(1); } @Test public void testGroupsNameAndGroupsId() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupNames.add("group1"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(2); } @Test public void testWithEnableFullList() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); userGroup.setEnableFullList(true); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); } @Test public void testWithoutEnableFullList() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); List<String> customizeGroupNames = new ArrayList<>(); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); customizeGroupNames.add("group1"); userGroup.setEnableFullList(false); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupNames); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group5"); assertThat(groupRoles).contains("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); assertThat(groupRoles).doesNotContain("ROLE_d07c0bd6-4aab-45ac-b87c-23e8d00194abaaa"); assertThat(groupRoles).hasSize(2); } @Test public void testAllGroupIds() { allowedGroupIds.add("d07c0bd6-4aab-45ac-b87c-23e8d00194ab"); allowedGroupIds.add("6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"); allowedGroupNames.add("group1"); allowedGroupNames.add("group2"); Set<String> customizeGroupIds = new HashSet<>(); customizeGroupIds.add("all"); List<String> customizeGroupName = new ArrayList<>(); customizeGroupName.add("group1"); userGroup.setAllowedGroupIds(customizeGroupIds); userGroup.setAllowedGroupNames(customizeGroupName); userGroup.setEnableFullList(true); Mockito.lenient().when(graphClient.getGroupInformation(accessToken.getTokenValue())) .thenReturn(groupInformationFromGraph); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); } }
class AADAccessTokenGroupRolesExtractionTest { private static final String GROUP_ID_1 = "d07c0bd6-4aab-45ac-b87c-23e8d00194ab"; private static final String GROUP_ID_2 = "6eddcc22-a24a-4459-b036-b9d9fc0f0bc7"; private final AADAuthenticationProperties properties = new AADAuthenticationProperties(); private final AADAuthenticationProperties.UserGroupProperties userGroup = new AADAuthenticationProperties.UserGroupProperties(); private AutoCloseable autoCloseable; @Mock private OAuth2AccessToken accessToken; @Mock private GraphClient graphClient; @BeforeAll @AfterEach public void reset() { userGroup.setAllowedGroupNames(Collections.emptyList()); userGroup.setAllowedGroupIds(Collections.emptySet()); userGroup.setEnableFullList(false); } @AfterAll public void close() throws Exception { this.autoCloseable.close(); } @Test public void testAllowedGroupsNames() { List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(1); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); } @Test public void testAllowedGroupsIds() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); userGroup.setAllowedGroupIds(allowedGroupIds); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testAllowedGroupsNamesAndAllowedGroupsIds() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(2); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testWithEnableFullList() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); userGroup.setEnableFullList(true); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_2); } @Test public void testWithoutEnableFullList() { List<String> allowedGroupNames = new ArrayList<>(); Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add(GROUP_ID_1); allowedGroupNames.add("group1"); userGroup.setEnableFullList(false); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(2); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).doesNotContain("ROLE_" + GROUP_ID_2); } @Test public void testAllowedGroupIdsAllWithoutEnableFullList() { Set<String> allowedGroupIds = new HashSet<>(); allowedGroupIds.add("all"); List<String> allowedGroupNames = new ArrayList<>(); allowedGroupNames.add("group1"); userGroup.setAllowedGroupIds(allowedGroupIds); userGroup.setAllowedGroupNames(allowedGroupNames); userGroup.setEnableFullList(false); AADOAuth2UserService userService = new AADOAuth2UserService(properties, graphClient); Set<String> groupRoles = userService.extractGroupRolesFromAccessToken(accessToken); assertThat(groupRoles).hasSize(3); assertThat(groupRoles).contains("ROLE_group1"); assertThat(groupRoles).doesNotContain("ROLE_group2"); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_1); assertThat(groupRoles).contains("ROLE_" + GROUP_ID_2); } @Test public void testIllegalGroupIdParam() { WebApplicationContextRunnerUtils .getContextRunnerWithRequiredProperties() .withPropertyValues( "azure.activedirectory.user-group.allowed-group-ids = all," + GROUP_ID_1 ) .run(context -> assertThrows(IllegalStateException.class, () -> context.getBean(AADAuthenticationProperties.class))); } }
This method is not async, it should just be `sendMessages`
public void run() throws InterruptedException { ServiceBusSenderClient senderClient = new ServiceBusClientBuilder() .connectionString(connectionString) .sender() .queueName(queueName) .buildClient(); sendMessagesAsync(senderClient, 1); deadLetterByExceedingMaxDelivery(connectionString, queueName); sendMessagesAsync(senderClient, Integer.MAX_VALUE); this.receiveAndDeadletterMessagesAsync(connectionString, queueName); this.pickUpAndFixDeadletters(connectionString, queueName, senderClient); senderClient.close(); }
sendMessagesAsync(senderClient, 1);
public void run() { final String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); final String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); final ServiceBusClientBuilder builder = new ServiceBusClientBuilder().connectionString(connectionString); try (ServiceBusSenderClient sender = builder.sender().queueName(queueName).buildClient()) { sendMessages(sender, 1); deadLetterByExceedingMaxDelivery(builder, queueName).block(); receiveAndCompleteDeadLetterQueueMessages(builder, queueName).block(); sendMessages(sender, personList.size()); receiveAndDeadletterMessages(builder, queueName).block(); receiveAndFixDeadLetterQueueMessages(builder, queueName, sender).block(); } }
class DeadletterQueueSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); /** * Main method to show how to dead letter within an Azure Service Bus Queue. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { DeadletterQueueSample sample = new DeadletterQueueSample(); sample.run(); } /** * Run method to invoke this demo on how to dead letter within an Azure Service Bus Queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ @Test /** * Send {@link ServiceBusMessage messages} to an Azure Service Bus Queue. * * @Param senderAsyncClient Service Bus Sender Client * @Param maxMessages Maximum Number Of Messages */ void sendMessagesAsync(ServiceBusSenderClient senderClient, int maxMessages) { List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("{\"name\" : \"Einstein\", \"firstName\" : \"Albert\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Heisenberg\", \"firstName\" : \"Werner\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Curie\", \"firstName\" : \"Marie\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Hawking\", \"firstName\" : \"Steven\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Newton\", \"firstName\" : \"Isaac\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Bohr\", \"firstName\" : \"Niels\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Faraday\", \"firstName\" : \"Michael\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Galilei\", \"firstName\" : \"Galileo\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Kepler\", \"firstName\" : \"Johannes\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Kopernikus\", \"firstName\" : \"Nikolaus\"}")); for (int i = 0; i < Math.min(messageList.size(), maxMessages); i++) { final String messageId = Integer.toString(i); ServiceBusMessage message = messageList.get(i); message.setContentType("application/json"); message.setSubject(i % 2 == 0 ? "Scientist" : "Physicist"); message.setMessageId(messageId); message.setTimeToLive(Duration.ofMinutes(2)); System.out.printf("\tMessage sending: Id = %s\n", message.getMessageId()); senderClient.sendMessage(message); System.out.printf("\tMessage acknowledged: Id = %s\n", message.getMessageId()); } } /** * Receive {@link ServiceBusMessage messages} and return {@link ServiceBusMessage messages} back to the queue. * When the time to life of the {@link ServiceBusMessage messages} expires, * the {@link ServiceBusMessage messages} will be dumped as dead letters into the dead letter queue. * We can receive these {@link ServiceBusMessage messages} from the dead letter queue. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ void deadLetterByExceedingMaxDelivery(String connectionString, String queueName) throws InterruptedException { ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); receiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { System.out.printf("Picked up message; DeliveryCount %d\n", receiveMessage.getDeliveryCount()); receiverAsyncClient.abandon(receiveMessage); }); Thread.sleep(10000); receiverAsyncClient.close(); Thread.sleep(120000); ServiceBusReceiverAsyncClient deadletterReceiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .queueName(queueName.concat("/$deadletterqueue")) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); deadletterReceiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { System.out.printf("\nDeadletter message:\n"); receiveMessage.getApplicationProperties().keySet().forEach(key -> System.out.printf("\t%s=%s\n", key, receiveMessage.getApplicationProperties().get(key))); deadletterReceiverAsyncClient.complete(receiveMessage); }); Thread.sleep(10000); deadletterReceiverAsyncClient.close(); } /** * Receive {@link ServiceBusMessage messages} and transfer to the dead letter queue as a dead letter. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name */ void receiveAndDeadletterMessagesAsync(String connectionString, String queueName) { ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName) .buildAsyncClient(); receiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { if (receiveMessage.getSubject() != null && receiveMessage.getContentType() != null && receiveMessage.getSubject().contentEquals("Scientist") && receiveMessage.getContentType().contentEquals("application/json")) { byte[] body = receiveMessage.getBody().toBytes(); JSONObject jsonObject = null; try { jsonObject = JSONObjectUtils.parse(new String(body, UTF_8)); } catch (ParseException e) { e.printStackTrace(); } System.out.printf( "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s," + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\", \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n", receiveMessage.getMessageId(), receiveMessage.getSequenceNumber(), receiveMessage.getEnqueuedTime(), receiveMessage.getExpiresAt(), receiveMessage.getContentType(), jsonObject != null ? jsonObject.get("firstName") : "", jsonObject != null ? jsonObject.get("name") : ""); } else { receiverAsyncClient.deadLetter(receiveMessage); } receiverAsyncClient.complete(receiveMessage); }); } /** * Receive dead letter {@link ServiceBusMessage messages} and resend its. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name * @Param resubmitSender Service Bus Send Client */ void pickUpAndFixDeadletters(String connectionString, String queueName, ServiceBusSenderClient resubmitSender) { ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName.concat("/$deadletterqueue")) .buildAsyncClient(); receiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { if (receiveMessage.getSubject() != null && receiveMessage.getSubject().contentEquals("Physicist")) { ServiceBusMessage resubmitMessage = new ServiceBusMessage(receiveMessage.getBody()); System.out.printf( "\n\t\tFixing: \n\t\t\tMessageId = %s, \n\t\t\tSequenceNumber = %s, \n\t\t\tLabel = %s\n", receiveMessage.getMessageId(), receiveMessage.getSequenceNumber(), receiveMessage.getSubject()); resubmitMessage.setMessageId(receiveMessage.getMessageId()); resubmitMessage.setSubject("Scientist"); resubmitMessage.setContentType(receiveMessage.getContentType()); resubmitMessage.setTimeToLive(Duration.ofMinutes(2)); resubmitSender.sendMessage(resubmitMessage); } receiverAsyncClient.complete(receiveMessage); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label) { ServiceBusMessage message = new ServiceBusMessage(label.getBytes(UTF_8)); return message; } }
class DeadletterQueueSample { private final List<Person> personList = Arrays.asList( new Person("Einstein", "Albert"), new Person("Heisenberg", "Werner"), new Person("Curie", "Marie"), new Person("Hawking", "Steven"), new Person("Newton", "Isaac"), new Person("Bohr", "Niels"), new Person("Faraday", "Michael"), new Person("Galilei", "Galileo"), new Person("Kepler", "Johannes"), new Person("Kopernikus", "Nikolaus") ); /** * Main method to show how to dead letter within an Azure Service Bus Queue. * * @param args Unused arguments to the program. */ public static void main(String[] args) { final DeadletterQueueSample sample = new DeadletterQueueSample(); sample.run(); } /** * Run method to invoke this demo on how to dead letter within an Azure Service Bus Queue. */ @Test /** * Sends {@link ServiceBusMessage messages} to an Azure Service Bus Queue. * * @param sender Sender client. * @param maxMessages Maximum number of messages to send. */ private void sendMessages(ServiceBusSenderClient sender, int maxMessages) { final int numberOfMessages = Math.min(personList.size(), maxMessages); final List<ServiceBusMessage> serviceBusMessages = IntStream.range(0, numberOfMessages) .mapToObj(index -> { final Person person = personList.get(index); return new ServiceBusMessage(person.toJson()) .setContentType("application/json") .setSubject(index % 2 == 0 ? "Scientist" : "Physicist") .setMessageId(Integer.toString(index)) .setTimeToLive(Duration.ofMinutes(2)); }).collect(Collectors.toList()); sender.sendMessages(serviceBusMessages); } /** * <strong>Scenario 1: Part 1</strong> * * <p> * Receive {@link ServiceBusMessage messages} and return the {@link ServiceBusMessage messages} back to the queue. * When the max number of deliveries for each {@link ServiceBusMessage message} expires, then it is moved into the * dead letter queue. * </p> * * @param builder Service Bus client builder. * @param queueName Name of the queue to receive from. * * @return A Mono that completes when all messages in queue have been processed.(because a message has not been * received in the last 30 seconds). */ private Mono<Void> deadLetterByExceedingMaxDelivery(ServiceBusClientBuilder builder, String queueName) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { System.out.printf("Received message. Sequence message.getDeliveryCount()); return receiver.abandon(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Queue is empty."); return Mono.empty(); }) .then(); }, receiver -> { receiver.close(); }); } /** * <strong>Scenario 1: Part 2</strong> * * <p> * This method continues to receive messages from the dead letter queue, then completes them. * </p> * * @param builder Service Bus client builder. * @param queueName Name of the queue to receive from. * * @return A Mono that completes when all messages in queue have been processed (because a message has not been * received in the last 30 seconds). */ private Mono<Void> receiveAndCompleteDeadLetterQueueMessages(ServiceBusClientBuilder builder, String queueName) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); }, deadLetterQueueReceiver -> { return deadLetterQueueReceiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { System.out.printf("Received message from dead-letter queue. Sequence message.getSequenceNumber(), message.getDeliveryCount()); System.out.printf("Dead-Letter Reason: %s. Description: %s. Source: %s%n", message.getDeadLetterReason(), message.getDeadLetterErrorDescription(), message.getDeadLetterSource()); System.out.println("Application properties:"); message.getApplicationProperties().forEach((key, value) -> System.out.printf("\t%s=%s%n", key, value)); return deadLetterQueueReceiver.complete(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Dead-letter queue is empty."); return Mono.empty(); }) .then(); }, deadLetterQueueReceiver -> { deadLetterQueueReceiver.close(); }); } /** * <strong>Scenario 2: Part 1</strong> * * <p> * Receives {@link ServiceBusMessage messages} and dead letters them if it has a subject of "Scientist" and content * type of "application/json". This is to simulate that the message may be malformed or didn't contain the right * content, so we dead letter it so other receivers don't process this message. * </p> * * @param builder Service Bus client builder. * @param queueName Name of queue to receive messages from. * * @return A Mono that completes when all the messages in the queue have been processed (because a message has not * been received in the last 30 seconds). */ private Mono<Void> receiveAndDeadletterMessages(ServiceBusClientBuilder builder, String queueName) { return Mono.using( () -> { return builder.receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { final String subject = message.getSubject(); final String contentType = message.getContentType(); final Person person; try { person = Person.fromJson(message.getBody().toString()); } catch (RuntimeException e) { return Mono.error(new RuntimeException("Could not deserialize message: " + message.getSequenceNumber(), e)); } System.out.printf("Received message. SequenceNumber = %s. EnqueuedTimeUtc = %s. " + "ExpiresAtUtc = %s. ContentType = %s. Content: [ %s ]%n", message.getSequenceNumber(), message.getEnqueuedTime(), message.getExpiresAt(), message.getContentType(), person); if ("Scientist".equals(subject) && "application/json".equals(contentType)) { return receiver.complete(message); } else { return receiver.deadLetter(message); } }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Queue is empty."); return Mono.empty(); }) .then(); }, receiver -> { receiver.close(); }); } /** * <strong>Scenario 2: Part 2</strong> * * <p> * Receives {@link ServiceBusMessage messages} from the dead letter queue, it fixes up the message then resends the * fixed message to the queue again. This simulates messages that may have errors in them, were dead-lettered, * and reprocessed in the dead-letter queue so the data is correct again. * </p> * * @param builder Service Bus client builder. * @param queueName Name of queue to receive messages from. * @param resubmitSender Service Bus sender client. When messages are fixed, they are published via this sender. * * @return A Mono that completes when all the messages in the queue have been processed (because a message has not * been received in the last 30 seconds). */ private Mono<Void> receiveAndFixDeadLetterQueueMessages(ServiceBusClientBuilder builder, String queueName, ServiceBusSenderClient resubmitSender) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); }, deadLetterQueueReceiver -> { return deadLetterQueueReceiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { if ("Physicist".equals(message.getSubject())) { System.out.printf("Fixing DLQ message. MessageId = %s. SequenceNumber = %s. Subject = %s%n", message.getMessageId(), message.getSequenceNumber(), message.getSubject()); ServiceBusMessage resubmitMessage = new ServiceBusMessage(message) .setSubject("Scientist"); resubmitSender.sendMessage(resubmitMessage); } else { System.out.printf("Message resubmission is not required. MessageId = %s. SequenceNumber = %s. " + "Subject = %s%n", message.getMessageId(), message.getSequenceNumber(), message.getSubject()); } return deadLetterQueueReceiver.complete(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Dead-letter queue is empty."); return Mono.empty(); }) .then(); }, deadLetterQueueReceiver -> { deadLetterQueueReceiver.close(); }); } private static final class Person { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final String lastName; private final String firstName; Person(@JsonProperty String lastName, @JsonProperty String firstName) { this.lastName = lastName; this.firstName = firstName; } String getLastName() { return lastName; } String getFirstName() { return firstName; } /** * Serializes an item into its JSON string equivalent. * * @return The JSON representation. * * @throws RuntimeException if the person could not be serialized. */ String toJson() { try { return OBJECT_MAPPER.writeValueAsString(this); } catch (JsonProcessingException e) { throw new RuntimeException("Could not serialize object.", e); } } /** * Deserializes a JSON string into a Person. * * @return The corresponding person. * * @throws RuntimeException if the JSON string could not be deserialized. */ private static Person fromJson(String json) { try { return OBJECT_MAPPER.readValue(json, Person.class); } catch (JsonProcessingException e) { throw new RuntimeException("Could not deserialize object.", e); } } } }
According to your Comment, fixed in new version.
public void run() throws InterruptedException { ServiceBusSenderClient senderClient = new ServiceBusClientBuilder() .connectionString(connectionString) .sender() .queueName(queueName) .buildClient(); sendMessagesAsync(senderClient, 1); deadLetterByExceedingMaxDelivery(connectionString, queueName); sendMessagesAsync(senderClient, Integer.MAX_VALUE); this.receiveAndDeadletterMessagesAsync(connectionString, queueName); this.pickUpAndFixDeadletters(connectionString, queueName, senderClient); senderClient.close(); }
sendMessagesAsync(senderClient, 1);
public void run() { final String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); final String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); final ServiceBusClientBuilder builder = new ServiceBusClientBuilder().connectionString(connectionString); try (ServiceBusSenderClient sender = builder.sender().queueName(queueName).buildClient()) { sendMessages(sender, 1); deadLetterByExceedingMaxDelivery(builder, queueName).block(); receiveAndCompleteDeadLetterQueueMessages(builder, queueName).block(); sendMessages(sender, personList.size()); receiveAndDeadletterMessages(builder, queueName).block(); receiveAndFixDeadLetterQueueMessages(builder, queueName, sender).block(); } }
class DeadletterQueueSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); /** * Main method to show how to dead letter within an Azure Service Bus Queue. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { DeadletterQueueSample sample = new DeadletterQueueSample(); sample.run(); } /** * Run method to invoke this demo on how to dead letter within an Azure Service Bus Queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ @Test /** * Send {@link ServiceBusMessage messages} to an Azure Service Bus Queue. * * @Param senderAsyncClient Service Bus Sender Client * @Param maxMessages Maximum Number Of Messages */ void sendMessagesAsync(ServiceBusSenderClient senderClient, int maxMessages) { List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("{\"name\" : \"Einstein\", \"firstName\" : \"Albert\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Heisenberg\", \"firstName\" : \"Werner\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Curie\", \"firstName\" : \"Marie\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Hawking\", \"firstName\" : \"Steven\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Newton\", \"firstName\" : \"Isaac\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Bohr\", \"firstName\" : \"Niels\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Faraday\", \"firstName\" : \"Michael\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Galilei\", \"firstName\" : \"Galileo\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Kepler\", \"firstName\" : \"Johannes\"}")); messageList.add(createServiceBusMessage("{\"name\" : \"Kopernikus\", \"firstName\" : \"Nikolaus\"}")); for (int i = 0; i < Math.min(messageList.size(), maxMessages); i++) { final String messageId = Integer.toString(i); ServiceBusMessage message = messageList.get(i); message.setContentType("application/json"); message.setSubject(i % 2 == 0 ? "Scientist" : "Physicist"); message.setMessageId(messageId); message.setTimeToLive(Duration.ofMinutes(2)); System.out.printf("\tMessage sending: Id = %s\n", message.getMessageId()); senderClient.sendMessage(message); System.out.printf("\tMessage acknowledged: Id = %s\n", message.getMessageId()); } } /** * Receive {@link ServiceBusMessage messages} and return {@link ServiceBusMessage messages} back to the queue. * When the time to life of the {@link ServiceBusMessage messages} expires, * the {@link ServiceBusMessage messages} will be dumped as dead letters into the dead letter queue. * We can receive these {@link ServiceBusMessage messages} from the dead letter queue. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ void deadLetterByExceedingMaxDelivery(String connectionString, String queueName) throws InterruptedException { ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); receiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { System.out.printf("Picked up message; DeliveryCount %d\n", receiveMessage.getDeliveryCount()); receiverAsyncClient.abandon(receiveMessage); }); Thread.sleep(10000); receiverAsyncClient.close(); Thread.sleep(120000); ServiceBusReceiverAsyncClient deadletterReceiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .queueName(queueName.concat("/$deadletterqueue")) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); deadletterReceiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { System.out.printf("\nDeadletter message:\n"); receiveMessage.getApplicationProperties().keySet().forEach(key -> System.out.printf("\t%s=%s\n", key, receiveMessage.getApplicationProperties().get(key))); deadletterReceiverAsyncClient.complete(receiveMessage); }); Thread.sleep(10000); deadletterReceiverAsyncClient.close(); } /** * Receive {@link ServiceBusMessage messages} and transfer to the dead letter queue as a dead letter. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name */ void receiveAndDeadletterMessagesAsync(String connectionString, String queueName) { ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName) .buildAsyncClient(); receiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { if (receiveMessage.getSubject() != null && receiveMessage.getContentType() != null && receiveMessage.getSubject().contentEquals("Scientist") && receiveMessage.getContentType().contentEquals("application/json")) { byte[] body = receiveMessage.getBody().toBytes(); JSONObject jsonObject = null; try { jsonObject = JSONObjectUtils.parse(new String(body, UTF_8)); } catch (ParseException e) { e.printStackTrace(); } System.out.printf( "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s," + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\", \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n", receiveMessage.getMessageId(), receiveMessage.getSequenceNumber(), receiveMessage.getEnqueuedTime(), receiveMessage.getExpiresAt(), receiveMessage.getContentType(), jsonObject != null ? jsonObject.get("firstName") : "", jsonObject != null ? jsonObject.get("name") : ""); } else { receiverAsyncClient.deadLetter(receiveMessage); } receiverAsyncClient.complete(receiveMessage); }); } /** * Receive dead letter {@link ServiceBusMessage messages} and resend its. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name * @Param resubmitSender Service Bus Send Client */ void pickUpAndFixDeadletters(String connectionString, String queueName, ServiceBusSenderClient resubmitSender) { ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName.concat("/$deadletterqueue")) .buildAsyncClient(); receiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { if (receiveMessage.getSubject() != null && receiveMessage.getSubject().contentEquals("Physicist")) { ServiceBusMessage resubmitMessage = new ServiceBusMessage(receiveMessage.getBody()); System.out.printf( "\n\t\tFixing: \n\t\t\tMessageId = %s, \n\t\t\tSequenceNumber = %s, \n\t\t\tLabel = %s\n", receiveMessage.getMessageId(), receiveMessage.getSequenceNumber(), receiveMessage.getSubject()); resubmitMessage.setMessageId(receiveMessage.getMessageId()); resubmitMessage.setSubject("Scientist"); resubmitMessage.setContentType(receiveMessage.getContentType()); resubmitMessage.setTimeToLive(Duration.ofMinutes(2)); resubmitSender.sendMessage(resubmitMessage); } receiverAsyncClient.complete(receiveMessage); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label) { ServiceBusMessage message = new ServiceBusMessage(label.getBytes(UTF_8)); return message; } }
class DeadletterQueueSample { private final List<Person> personList = Arrays.asList( new Person("Einstein", "Albert"), new Person("Heisenberg", "Werner"), new Person("Curie", "Marie"), new Person("Hawking", "Steven"), new Person("Newton", "Isaac"), new Person("Bohr", "Niels"), new Person("Faraday", "Michael"), new Person("Galilei", "Galileo"), new Person("Kepler", "Johannes"), new Person("Kopernikus", "Nikolaus") ); /** * Main method to show how to dead letter within an Azure Service Bus Queue. * * @param args Unused arguments to the program. */ public static void main(String[] args) { final DeadletterQueueSample sample = new DeadletterQueueSample(); sample.run(); } /** * Run method to invoke this demo on how to dead letter within an Azure Service Bus Queue. */ @Test /** * Sends {@link ServiceBusMessage messages} to an Azure Service Bus Queue. * * @param sender Sender client. * @param maxMessages Maximum number of messages to send. */ private void sendMessages(ServiceBusSenderClient sender, int maxMessages) { final int numberOfMessages = Math.min(personList.size(), maxMessages); final List<ServiceBusMessage> serviceBusMessages = IntStream.range(0, numberOfMessages) .mapToObj(index -> { final Person person = personList.get(index); return new ServiceBusMessage(person.toJson()) .setContentType("application/json") .setSubject(index % 2 == 0 ? "Scientist" : "Physicist") .setMessageId(Integer.toString(index)) .setTimeToLive(Duration.ofMinutes(2)); }).collect(Collectors.toList()); sender.sendMessages(serviceBusMessages); } /** * <strong>Scenario 1: Part 1</strong> * * <p> * Receive {@link ServiceBusMessage messages} and return the {@link ServiceBusMessage messages} back to the queue. * When the max number of deliveries for each {@link ServiceBusMessage message} expires, then it is moved into the * dead letter queue. * </p> * * @param builder Service Bus client builder. * @param queueName Name of the queue to receive from. * * @return A Mono that completes when all messages in queue have been processed.(because a message has not been * received in the last 30 seconds). */ private Mono<Void> deadLetterByExceedingMaxDelivery(ServiceBusClientBuilder builder, String queueName) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { System.out.printf("Received message. Sequence message.getDeliveryCount()); return receiver.abandon(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Queue is empty."); return Mono.empty(); }) .then(); }, receiver -> { receiver.close(); }); } /** * <strong>Scenario 1: Part 2</strong> * * <p> * This method continues to receive messages from the dead letter queue, then completes them. * </p> * * @param builder Service Bus client builder. * @param queueName Name of the queue to receive from. * * @return A Mono that completes when all messages in queue have been processed (because a message has not been * received in the last 30 seconds). */ private Mono<Void> receiveAndCompleteDeadLetterQueueMessages(ServiceBusClientBuilder builder, String queueName) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); }, deadLetterQueueReceiver -> { return deadLetterQueueReceiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { System.out.printf("Received message from dead-letter queue. Sequence message.getSequenceNumber(), message.getDeliveryCount()); System.out.printf("Dead-Letter Reason: %s. Description: %s. Source: %s%n", message.getDeadLetterReason(), message.getDeadLetterErrorDescription(), message.getDeadLetterSource()); System.out.println("Application properties:"); message.getApplicationProperties().forEach((key, value) -> System.out.printf("\t%s=%s%n", key, value)); return deadLetterQueueReceiver.complete(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Dead-letter queue is empty."); return Mono.empty(); }) .then(); }, deadLetterQueueReceiver -> { deadLetterQueueReceiver.close(); }); } /** * <strong>Scenario 2: Part 1</strong> * * <p> * Receives {@link ServiceBusMessage messages} and dead letters them if it has a subject of "Scientist" and content * type of "application/json". This is to simulate that the message may be malformed or didn't contain the right * content, so we dead letter it so other receivers don't process this message. * </p> * * @param builder Service Bus client builder. * @param queueName Name of queue to receive messages from. * * @return A Mono that completes when all the messages in the queue have been processed (because a message has not * been received in the last 30 seconds). */ private Mono<Void> receiveAndDeadletterMessages(ServiceBusClientBuilder builder, String queueName) { return Mono.using( () -> { return builder.receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { final String subject = message.getSubject(); final String contentType = message.getContentType(); final Person person; try { person = Person.fromJson(message.getBody().toString()); } catch (RuntimeException e) { return Mono.error(new RuntimeException("Could not deserialize message: " + message.getSequenceNumber(), e)); } System.out.printf("Received message. SequenceNumber = %s. EnqueuedTimeUtc = %s. " + "ExpiresAtUtc = %s. ContentType = %s. Content: [ %s ]%n", message.getSequenceNumber(), message.getEnqueuedTime(), message.getExpiresAt(), message.getContentType(), person); if ("Scientist".equals(subject) && "application/json".equals(contentType)) { return receiver.complete(message); } else { return receiver.deadLetter(message); } }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Queue is empty."); return Mono.empty(); }) .then(); }, receiver -> { receiver.close(); }); } /** * <strong>Scenario 2: Part 2</strong> * * <p> * Receives {@link ServiceBusMessage messages} from the dead letter queue, it fixes up the message then resends the * fixed message to the queue again. This simulates messages that may have errors in them, were dead-lettered, * and reprocessed in the dead-letter queue so the data is correct again. * </p> * * @param builder Service Bus client builder. * @param queueName Name of queue to receive messages from. * @param resubmitSender Service Bus sender client. When messages are fixed, they are published via this sender. * * @return A Mono that completes when all the messages in the queue have been processed (because a message has not * been received in the last 30 seconds). */ private Mono<Void> receiveAndFixDeadLetterQueueMessages(ServiceBusClientBuilder builder, String queueName, ServiceBusSenderClient resubmitSender) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); }, deadLetterQueueReceiver -> { return deadLetterQueueReceiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { if ("Physicist".equals(message.getSubject())) { System.out.printf("Fixing DLQ message. MessageId = %s. SequenceNumber = %s. Subject = %s%n", message.getMessageId(), message.getSequenceNumber(), message.getSubject()); ServiceBusMessage resubmitMessage = new ServiceBusMessage(message) .setSubject("Scientist"); resubmitSender.sendMessage(resubmitMessage); } else { System.out.printf("Message resubmission is not required. MessageId = %s. SequenceNumber = %s. " + "Subject = %s%n", message.getMessageId(), message.getSequenceNumber(), message.getSubject()); } return deadLetterQueueReceiver.complete(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Dead-letter queue is empty."); return Mono.empty(); }) .then(); }, deadLetterQueueReceiver -> { deadLetterQueueReceiver.close(); }); } private static final class Person { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final String lastName; private final String firstName; Person(@JsonProperty String lastName, @JsonProperty String firstName) { this.lastName = lastName; this.firstName = firstName; } String getLastName() { return lastName; } String getFirstName() { return firstName; } /** * Serializes an item into its JSON string equivalent. * * @return The JSON representation. * * @throws RuntimeException if the person could not be serialized. */ String toJson() { try { return OBJECT_MAPPER.writeValueAsString(this); } catch (JsonProcessingException e) { throw new RuntimeException("Could not serialize object.", e); } } /** * Deserializes a JSON string into a Person. * * @return The corresponding person. * * @throws RuntimeException if the JSON string could not be deserialized. */ private static Person fromJson(String json) { try { return OBJECT_MAPPER.readValue(json, Person.class); } catch (JsonProcessingException e) { throw new RuntimeException("Could not deserialize object.", e); } } } }
Better put this in the finally block, or try(senderClient) {...}
public void run() throws InterruptedException, JsonProcessingException { ServiceBusSenderClient senderClient = new ServiceBusClientBuilder() .connectionString(connectionString) .sender() .queueName(queueName) .buildClient(); sendMessages(senderClient, 1); deadLetterByExceedingMaxDelivery(connectionString, queueName); sendMessages(senderClient, Integer.MAX_VALUE); this.receiveAndDeadletterMessagesAsync(connectionString, queueName).block(); this.pickUpAndFixDeadletters(connectionString, queueName, senderClient).block(); senderClient.close(); }
senderClient.close();
public void run() { final String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); final String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); final ServiceBusClientBuilder builder = new ServiceBusClientBuilder().connectionString(connectionString); try (ServiceBusSenderClient sender = builder.sender().queueName(queueName).buildClient()) { sendMessages(sender, 1); deadLetterByExceedingMaxDelivery(builder, queueName).block(); receiveAndCompleteDeadLetterQueueMessages(builder, queueName).block(); sendMessages(sender, personList.size()); receiveAndDeadletterMessages(builder, queueName).block(); receiveAndFixDeadLetterQueueMessages(builder, queueName, sender).block(); } }
class DeadletterQueueSample { String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME"); static final ObjectMapper objectMapper = new ObjectMapper(); /** * Main method to show how to dead letter within an Azure Service Bus Queue. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException, JsonProcessingException { DeadletterQueueSample sample = new DeadletterQueueSample(); sample.run(); } /** * Run method to invoke this demo on how to dead letter within an Azure Service Bus Queue. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ @Test /** * Send {@link ServiceBusMessage messages} to an Azure Service Bus Queue. * * @Param senderAsyncClient Service Bus Sender Client * @Param maxMessages Maximum Number Of Messages */ void sendMessages(ServiceBusSenderClient senderClient, int maxMessages) throws JsonProcessingException { List<Person> messageList = Arrays.asList( new Person("Einstein", "Albert"), new Person("Heisenberg", "Werner"), new Person("Curie", "Marie"), new Person("Hawking", "Steven"), new Person("Newton", "Isaac"), new Person("Bohr", "Niels"), new Person("Faraday", "Michael"), new Person("Galilei", "Galileo"), new Person("Kepler", "Johannes"), new Person("Kopernikus", "Nikolaus") ); for (int i = 0; i < Math.min(messageList.size(), maxMessages); i++) { final String messageId = Integer.toString(i); ServiceBusMessage message = new ServiceBusMessage(objectMapper.writeValueAsString(messageList.get(i))); message.setContentType("application/json"); message.setSubject(i % 2 == 0 ? "Scientist" : "Physicist"); message.setMessageId(messageId); message.setTimeToLive(Duration.ofMinutes(2)); System.out.printf("\tMessage sending: Id = %s%n", message.getMessageId()); senderClient.sendMessage(message); System.out.printf("\tMessage acknowledged: Id = %s%n", message.getMessageId()); } } /** * Receive {@link ServiceBusMessage messages} and return {@link ServiceBusMessage messages} back to the queue. * When the time to life of the {@link ServiceBusMessage messages} expires, * the {@link ServiceBusMessage messages} will be dumped as dead letters into the dead letter queue. * We can receive these {@link ServiceBusMessage messages} from the dead letter queue. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ void deadLetterByExceedingMaxDelivery(String connectionString, String queueName) throws InterruptedException { ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); receiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { System.out.printf("Picked up message; DeliveryCount %d%n", receiveMessage.getDeliveryCount()); receiverAsyncClient.abandon(receiveMessage).subscribe(); }); Thread.sleep(10000); receiverAsyncClient.close(); Thread.sleep(120000); ServiceBusReceiverAsyncClient deadletterReceiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .queueName(queueName.concat("/$deadletterqueue")) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); deadletterReceiverAsyncClient.receiveMessages().subscribe(receiveMessage -> { System.out.printf("%nDeadletter message:%n"); receiveMessage.getApplicationProperties().keySet().forEach(key -> System.out.printf("\t%s=%s%n", key, receiveMessage.getApplicationProperties().get(key))); deadletterReceiverAsyncClient.complete(receiveMessage).subscribe(); }); Thread.sleep(10000); deadletterReceiverAsyncClient.close(); } /** * Receive {@link ServiceBusMessage messages} and transfer to the dead letter queue as a dead letter. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name */ Mono<Void> receiveAndDeadletterMessagesAsync(String connectionString, String queueName) { Mono<ServiceBusReceiverAsyncClient> createReceiver = Mono.fromCallable(() -> { return new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); }); return Mono.usingWhen(createReceiver, receiver -> { return receiver.receiveMessages().flatMap(receiveMessage -> { if (receiveMessage.getSubject() != null && receiveMessage.getContentType() != null && receiveMessage.getSubject().contentEquals("Scientist") && receiveMessage.getContentType().contentEquals("application/json")) { byte[] body = receiveMessage.getBody().toBytes(); Person person = null; try { person = objectMapper.readValue(new String(body, UTF_8), Person.class); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.printf( "%n\t\t\t\tMessage received: %n\t\t\t\t\t\tMessageId = %s, %n\t\t\t\t\t\tSequenceNumber = %s, %n\t\t\t\t\t\tEnqueuedTimeUtc = %s," + "%n\t\t\t\t\t\tExpiresAtUtc = %s, %n\t\t\t\t\t\tContentType = \"%s\", %n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]%n", receiveMessage.getMessageId(), receiveMessage.getSequenceNumber(), receiveMessage.getEnqueuedTime(), receiveMessage.getExpiresAt(), receiveMessage.getContentType(), person != null ? person.getFirstName() : "", person != null ? person.getName() : ""); } else { return receiver.deadLetter(receiveMessage); } return receiver.complete(receiveMessage); }).then(); }, receiver -> { receiver.close(); return Mono.empty(); }); } /** * Receive dead letter {@link ServiceBusMessage messages} and resend its. * * @Param connectionString Service Bus Connection String * @Param queueName Queue Name * @Param resubmitSender Service Bus Send Client */ Mono<Void> pickUpAndFixDeadletters(String connectionString, String queueName, ServiceBusSenderClient resubmitSender) { Mono<ServiceBusReceiverAsyncClient> createReceiver = Mono.fromCallable(() -> { return new ServiceBusClientBuilder() .connectionString(connectionString) .receiver() .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .queueName(queueName.concat("/$deadletterqueue")) .buildAsyncClient(); }); return Mono.usingWhen(createReceiver, receiver -> { return receiver.receiveMessages().flatMap(receiveMessage -> { if (receiveMessage.getSubject() != null && receiveMessage.getSubject().contentEquals("Physicist")) { ServiceBusMessage resubmitMessage = new ServiceBusMessage(receiveMessage.getBody()); System.out.printf( "%n\t\tFixing: %n\t\t\tMessageId = %s, %n\t\t\tSequenceNumber = %s, %n\t\t\tLabel = %s%n", receiveMessage.getMessageId(), receiveMessage.getSequenceNumber(), receiveMessage.getSubject()); resubmitMessage.setMessageId(receiveMessage.getMessageId()); resubmitMessage.setSubject("Scientist"); resubmitMessage.setContentType(receiveMessage.getContentType()); resubmitMessage.setTimeToLive(Duration.ofMinutes(2)); resubmitSender.sendMessage(resubmitMessage); } return receiver.complete(receiveMessage); }).then(); }, receiver -> { receiver.close(); return Mono.empty(); }); } private static final class Person { private String name; private String firstName; Person() { } Person(String name, String firstName) { this.name = name; this.firstName = firstName; } public String getName() { return name; } public String getFirstName() { return firstName; } public void setName(String name) { this.name = name; } public void setFirstName(String firstName) { this.firstName = firstName; } } }
class DeadletterQueueSample { private final List<Person> personList = Arrays.asList( new Person("Einstein", "Albert"), new Person("Heisenberg", "Werner"), new Person("Curie", "Marie"), new Person("Hawking", "Steven"), new Person("Newton", "Isaac"), new Person("Bohr", "Niels"), new Person("Faraday", "Michael"), new Person("Galilei", "Galileo"), new Person("Kepler", "Johannes"), new Person("Kopernikus", "Nikolaus") ); /** * Main method to show how to dead letter within an Azure Service Bus Queue. * * @param args Unused arguments to the program. */ public static void main(String[] args) { final DeadletterQueueSample sample = new DeadletterQueueSample(); sample.run(); } /** * Run method to invoke this demo on how to dead letter within an Azure Service Bus Queue. */ @Test /** * Sends {@link ServiceBusMessage messages} to an Azure Service Bus Queue. * * @param sender Sender client. * @param maxMessages Maximum number of messages to send. */ private void sendMessages(ServiceBusSenderClient sender, int maxMessages) { final int numberOfMessages = Math.min(personList.size(), maxMessages); final List<ServiceBusMessage> serviceBusMessages = IntStream.range(0, numberOfMessages) .mapToObj(index -> { final Person person = personList.get(index); return new ServiceBusMessage(person.toJson()) .setContentType("application/json") .setSubject(index % 2 == 0 ? "Scientist" : "Physicist") .setMessageId(Integer.toString(index)) .setTimeToLive(Duration.ofMinutes(2)); }).collect(Collectors.toList()); sender.sendMessages(serviceBusMessages); } /** * <strong>Scenario 1: Part 1</strong> * * <p> * Receive {@link ServiceBusMessage messages} and return the {@link ServiceBusMessage messages} back to the queue. * When the max number of deliveries for each {@link ServiceBusMessage message} expires, then it is moved into the * dead letter queue. * </p> * * @param builder Service Bus client builder. * @param queueName Name of the queue to receive from. * * @return A Mono that completes when all messages in queue have been processed.(because a message has not been * received in the last 30 seconds). */ private Mono<Void> deadLetterByExceedingMaxDelivery(ServiceBusClientBuilder builder, String queueName) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { System.out.printf("Received message. Sequence message.getDeliveryCount()); return receiver.abandon(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Queue is empty."); return Mono.empty(); }) .then(); }, receiver -> { receiver.close(); }); } /** * <strong>Scenario 1: Part 2</strong> * * <p> * This method continues to receive messages from the dead letter queue, then completes them. * </p> * * @param builder Service Bus client builder. * @param queueName Name of the queue to receive from. * * @return A Mono that completes when all messages in queue have been processed (because a message has not been * received in the last 30 seconds). */ private Mono<Void> receiveAndCompleteDeadLetterQueueMessages(ServiceBusClientBuilder builder, String queueName) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); }, deadLetterQueueReceiver -> { return deadLetterQueueReceiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { System.out.printf("Received message from dead-letter queue. Sequence message.getSequenceNumber(), message.getDeliveryCount()); System.out.printf("Dead-Letter Reason: %s. Description: %s. Source: %s%n", message.getDeadLetterReason(), message.getDeadLetterErrorDescription(), message.getDeadLetterSource()); System.out.println("Application properties:"); message.getApplicationProperties().forEach((key, value) -> System.out.printf("\t%s=%s%n", key, value)); return deadLetterQueueReceiver.complete(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Dead-letter queue is empty."); return Mono.empty(); }) .then(); }, deadLetterQueueReceiver -> { deadLetterQueueReceiver.close(); }); } /** * <strong>Scenario 2: Part 1</strong> * * <p> * Receives {@link ServiceBusMessage messages} and dead letters them if it has a subject of "Scientist" and content * type of "application/json". This is to simulate that the message may be malformed or didn't contain the right * content, so we dead letter it so other receivers don't process this message. * </p> * * @param builder Service Bus client builder. * @param queueName Name of queue to receive messages from. * * @return A Mono that completes when all the messages in the queue have been processed (because a message has not * been received in the last 30 seconds). */ private Mono<Void> receiveAndDeadletterMessages(ServiceBusClientBuilder builder, String queueName) { return Mono.using( () -> { return builder.receiver() .queueName(queueName) .receiveMode(ServiceBusReceiveMode.PEEK_LOCK) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { final String subject = message.getSubject(); final String contentType = message.getContentType(); final Person person; try { person = Person.fromJson(message.getBody().toString()); } catch (RuntimeException e) { return Mono.error(new RuntimeException("Could not deserialize message: " + message.getSequenceNumber(), e)); } System.out.printf("Received message. SequenceNumber = %s. EnqueuedTimeUtc = %s. " + "ExpiresAtUtc = %s. ContentType = %s. Content: [ %s ]%n", message.getSequenceNumber(), message.getEnqueuedTime(), message.getExpiresAt(), message.getContentType(), person); if ("Scientist".equals(subject) && "application/json".equals(contentType)) { return receiver.complete(message); } else { return receiver.deadLetter(message); } }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Queue is empty."); return Mono.empty(); }) .then(); }, receiver -> { receiver.close(); }); } /** * <strong>Scenario 2: Part 2</strong> * * <p> * Receives {@link ServiceBusMessage messages} from the dead letter queue, it fixes up the message then resends the * fixed message to the queue again. This simulates messages that may have errors in them, were dead-lettered, * and reprocessed in the dead-letter queue so the data is correct again. * </p> * * @param builder Service Bus client builder. * @param queueName Name of queue to receive messages from. * @param resubmitSender Service Bus sender client. When messages are fixed, they are published via this sender. * * @return A Mono that completes when all the messages in the queue have been processed (because a message has not * been received in the last 30 seconds). */ private Mono<Void> receiveAndFixDeadLetterQueueMessages(ServiceBusClientBuilder builder, String queueName, ServiceBusSenderClient resubmitSender) { return Mono.using(() -> { return builder.receiver() .queueName(queueName) .subQueue(SubQueue.DEAD_LETTER_QUEUE) .buildAsyncClient(); }, deadLetterQueueReceiver -> { return deadLetterQueueReceiver.receiveMessages() .timeout(Duration.ofSeconds(30)) .flatMap(message -> { if ("Physicist".equals(message.getSubject())) { System.out.printf("Fixing DLQ message. MessageId = %s. SequenceNumber = %s. Subject = %s%n", message.getMessageId(), message.getSequenceNumber(), message.getSubject()); ServiceBusMessage resubmitMessage = new ServiceBusMessage(message) .setSubject("Scientist"); resubmitSender.sendMessage(resubmitMessage); } else { System.out.printf("Message resubmission is not required. MessageId = %s. SequenceNumber = %s. " + "Subject = %s%n", message.getMessageId(), message.getSequenceNumber(), message.getSubject()); } return deadLetterQueueReceiver.complete(message); }) .onErrorResume(TimeoutException.class, exception -> { System.out.println("No messages received after 30 seconds. Dead-letter queue is empty."); return Mono.empty(); }) .then(); }, deadLetterQueueReceiver -> { deadLetterQueueReceiver.close(); }); } private static final class Person { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final String lastName; private final String firstName; Person(@JsonProperty String lastName, @JsonProperty String firstName) { this.lastName = lastName; this.firstName = firstName; } String getLastName() { return lastName; } String getFirstName() { return firstName; } /** * Serializes an item into its JSON string equivalent. * * @return The JSON representation. * * @throws RuntimeException if the person could not be serialized. */ String toJson() { try { return OBJECT_MAPPER.writeValueAsString(this); } catch (JsonProcessingException e) { throw new RuntimeException("Could not serialize object.", e); } } /** * Deserializes a JSON string into a Person. * * @return The corresponding person. * * @throws RuntimeException if the JSON string could not be deserialized. */ private static Person fromJson(String json) { try { return OBJECT_MAPPER.readValue(json, Person.class); } catch (JsonProcessingException e) { throw new RuntimeException("Could not deserialize object.", e); } } } }
I think this should be a different test case vs without throughput enabled.
public void createItem_withBulk() throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .setGroupName("test-group") .setTargetThroughputThreshold(0.2) .setDefault(true) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); try { Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } }
ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder()
public void createItem_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(15); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(2); Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(1); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(replaceCosmosItemOperationFlux) .flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) { BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulkAndThroughputControl() throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .setGroupName("test-group") .setTargetThroughputThreshold(0.2) .setDefault(true) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); try { Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(15); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(2); Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(1); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(replaceCosmosItemOperationFlux) .flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) { BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } }
nit: since we are in tests, so maybe using assert?
public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); }
if (cosmosBulkOperationResponse.getException() != null) {
public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk() throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .setGroupName("test-group") .setTargetThroughputThreshold(0.2) .setDefault(true) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); try { Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(15); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(2); Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(1); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(replaceCosmosItemOperationFlux) .flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) { BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulkAndThroughputControl() throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .setGroupName("test-group") .setTargetThroughputThreshold(0.2) .setDefault(true) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); try { Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(15); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(2); Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(1); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(replaceCosmosItemOperationFlux) .flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) { BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } }
Agreed
public void createItem_withBulk() throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .setGroupName("test-group") .setTargetThroughputThreshold(0.2) .setDefault(true) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); try { Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } }
ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder()
public void createItem_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(15); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(2); Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(1); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(replaceCosmosItemOperationFlux) .flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) { BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulkAndThroughputControl() throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .setGroupName("test-group") .setTargetThroughputThreshold(0.2) .setDefault(true) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); try { Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(15); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(2); Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(1); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(replaceCosmosItemOperationFlux) .flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) { BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } }
No - I really want the exception details to be in the log.
public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); }
if (cosmosBulkOperationResponse.getException() != null) {
public void createItemMultipleTimesWithOperationOnFly_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 2); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); Object testDoc = cosmosBulkItemResponse.getItem(Object.class); distinctDocs.add(testDoc); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 4); assertThat(distinctDocs.size()).isEqualTo(totalRequest * 4); }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk() throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .setGroupName("test-group") .setTargetThroughputThreshold(0.2) .setDefault(true) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); try { Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(15); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(2); Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(1); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(replaceCosmosItemOperationFlux) .flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) { BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } }
class CosmosBulkAsyncTest extends BatchTestBase { private final static Logger logger = LoggerFactory.getLogger(CosmosBulkAsyncTest.class); private CosmosAsyncClient bulkClient; private CosmosAsyncContainer bulkAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosBulkAsyncTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosBulkAsyncTest() { assertThat(this.bulkClient).isNull(); ThrottlingRetryOptions throttlingOptions = new ThrottlingRetryOptions() .setMaxRetryAttemptsOnThrottledRequests(1000000) .setMaxRetryWaitTime(Duration.ofDays(1)); this.bulkClient = getClientBuilder().throttlingRetryOptions(throttlingOptions).buildAsyncClient(); bulkAsyncContainer = getSharedMultiPartitionCosmosContainer(this.bulkClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.bulkClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulkAndThroughputControl() throws InterruptedException { int totalRequest = getTotalRequest(180, 200); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); pkDefinition.setPaths(Collections.singletonList("/mypk")); CosmosAsyncContainer bulkAsyncContainerWithThroughputControl = createCollection( this.bulkClient, bulkAsyncContainer.getDatabase().getId(), new CosmosContainerProperties(UUID.randomUUID().toString(), pkDefinition)); ThroughputControlGroupConfig groupConfig = new ThroughputControlGroupConfigBuilder() .setGroupName("test-group") .setTargetThroughputThreshold(0.2) .setDefault(true) .build(); bulkAsyncContainerWithThroughputControl.enableLocalThroughputControlGroup(groupConfig); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getUpsertItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); try { Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainerWithThroughputControl .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); Thread.sleep(1000); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } finally { bulkAsyncContainerWithThroughputControl.delete().block(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItem_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.merge( Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey); return BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey)); }), Flux.range(0, totalRequest).map(i -> { String partitionKey = UUID.randomUUID().toString(); EventDoc eventDoc = new EventDoc(UUID.randomUUID().toString(), 2, 4, "type1", partitionKey); return BulkOperations.getCreateItemOperation(eventDoc, new PartitionKey(partitionKey)); })); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest * 2); } @Test(groups = {"simple"}, timeOut = TIMEOUT) @Test(groups = {"simple"}, timeOut = TIMEOUT) public void runCreateItemMultipleTimesWithFixedOperations_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<Object> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> createResponseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); createResponseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkOperationResponse); }) .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createItemWithError_withBulk() { int totalRequest = getTotalRequest(); Flux<CosmosItemOperation> cosmosItemOperationFlux = Flux.range(0, totalRequest).flatMap(i -> { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); if (i == 20 || i == 40 || i == 60) { return Mono.error(new Exception("ex")); } return Mono.just(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); }); BulkProcessingOptions<CosmosBulkAsyncTest> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(15); Flux<CosmosBulkOperationResponse<CosmosBulkAsyncTest>> responseFlux = bulkAsyncContainer .processBulkOperations(cosmosItemOperationFlux, bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); AtomicInteger erroredDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<CosmosBulkAsyncTest> cosmosBulkOperationResponse) -> { CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if(cosmosBulkItemResponse == null) { erroredDoc.incrementAndGet(); return Mono.empty(); } else { processedDoc.incrementAndGet(); assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); } }).blockLast(); assertThat(erroredDoc.get()).isEqualTo(0); assertThat(processedDoc.get()).isEqualTo(totalRequest - 3); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void upsertItem_withbulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(2); Flux<CosmosBulkOperationResponse<Object>> responseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); AtomicInteger processedDoc = new AtomicInteger(0); responseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteItem_withBulk() { int totalRequest = Math.min(getTotalRequest(), 20); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> deleteCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getDeleteItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<TestDoc> bulkProcessingOptions = new BulkProcessingOptions<>(); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(1); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(deleteCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<TestDoc> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readItemMultipleTimes_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getUpsertItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> readCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReadItemOperation(testDoc.getId(), cosmosItemOperation.getPartitionKeyValue()); }); BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(30); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); HashSet<TestDoc> distinctDocs = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); Flux<CosmosBulkOperationResponse<Object>> readResponseFlux = bulkAsyncContainer .processBulkOperations(readCosmosItemOperationFlux, bulkProcessingOptions) .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctDocs.add(testDoc); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkOperationResponse); }); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); readResponseFlux .blockLast(); assertThat(processedDoc.get()).isEqualTo(2 * totalRequest); assertThat(distinctDocs.size()).isEqualTo(totalRequest); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceItem_withBulk() { int totalRequest = getTotalRequest(); List<CosmosItemOperation> cosmosItemOperations = new ArrayList<>(); for (int i = 0; i < totalRequest; i++) { String partitionKey = UUID.randomUUID().toString(); TestDoc testDoc = this.populateTestDoc(partitionKey, i, 20); cosmosItemOperations.add(BulkOperations.getCreateItemOperation(testDoc, new PartitionKey(partitionKey))); } createItemsAndVerify(cosmosItemOperations); Flux<CosmosItemOperation> replaceCosmosItemOperationFlux = Flux.fromIterable(cosmosItemOperations).map((CosmosItemOperation cosmosItemOperation) -> { TestDoc testDoc = cosmosItemOperation.getItem(); return BulkOperations.getReplaceItemOperation( testDoc.getId(), cosmosItemOperation.getItem(), cosmosItemOperation.getPartitionKeyValue()); }); AtomicInteger processedDoc = new AtomicInteger(0); bulkAsyncContainer .processBulkOperations(replaceCosmosItemOperationFlux) .flatMap((CosmosBulkOperationResponse<?> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(totalRequest); } private void createItemsAndVerify(List<CosmosItemOperation> cosmosItemOperations) { BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class); bulkProcessingOptions.setMaxMicroBatchSize(100); bulkProcessingOptions.setMaxMicroBatchConcurrency(5); Flux<CosmosBulkOperationResponse<Object>> createResonseFlux = bulkAsyncContainer .processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions); HashSet<Integer> distinctIndex = new HashSet<>(); AtomicInteger processedDoc = new AtomicInteger(0); createResonseFlux .flatMap((CosmosBulkOperationResponse<Object> cosmosBulkOperationResponse) -> { processedDoc.incrementAndGet(); CosmosBulkItemResponse cosmosBulkItemResponse = cosmosBulkOperationResponse.getResponse(); if (cosmosBulkOperationResponse.getException() != null) { logger.error("Bulk operation failed", cosmosBulkOperationResponse.getException()); fail(cosmosBulkOperationResponse.getException().toString()); } assertThat(cosmosBulkItemResponse.getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(cosmosBulkItemResponse.getRequestCharge()).isGreaterThan(0); assertThat(cosmosBulkItemResponse.getCosmosDiagnostics().toString()).isNotNull(); assertThat(cosmosBulkItemResponse.getSessionToken()).isNotNull(); assertThat(cosmosBulkItemResponse.getActivityId()).isNotNull(); assertThat(cosmosBulkItemResponse.getRequestCharge()).isNotNull(); TestDoc testDoc = cosmosBulkItemResponse.getItem(TestDoc.class); distinctIndex.add(testDoc.getCost()); assertThat(cosmosBulkOperationResponse.getOperation()).isEqualTo(cosmosItemOperations.get(testDoc.getCost())); assertThat(testDoc).isEqualTo(cosmosBulkOperationResponse.getOperation().getItem()); assertThat(testDoc).isEqualTo(cosmosItemOperations.get(testDoc.getCost()).getItem()); return Mono.just(cosmosBulkItemResponse); }).blockLast(); assertThat(processedDoc.get()).isEqualTo(cosmosItemOperations.size()); assertThat(distinctIndex.size()).isEqualTo(cosmosItemOperations.size()); } private int getTotalRequest(int min, int max) { int countRequest = new Random().nextInt(max - min) + min; logger.info("Total count of request for this test case: " + countRequest); return countRequest; } private int getTotalRequest() { return getTotalRequest(200, 300); } }
How about adding some code that uses sync eh client? We have more sync users.
public static void main(String[] args) throws IOException { final String iotHubConnectionString = "HostName=<your-iot-hub>.azure-devices.net;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>"; final Mono<String> connectionStringMono = getConnectionString(iotHubConnectionString) .cache(); final Mono<EventHubProperties> runOperation = Mono.usingWhen( connectionStringMono.map(connectionString -> { System.out.println("Acquired Event Hubs compatible connection string."); return new EventHubClientBuilder() .connectionString(connectionString) .buildAsyncProducerClient(); }), producer -> { System.out.println("Created producer client."); return producer.getEventHubProperties(); }, producer -> Mono.fromRunnable(() -> { System.out.println("Disposing of producer client."); producer.close(); })); final EventHubProperties eventHubProperties = runOperation.block(); if (eventHubProperties == null) { System.err.println("No properties were retrieved."); return; } final String partitionIds = eventHubProperties.getPartitionIds() .stream() .collect(Collectors.joining(", ")); System.out.printf("Event Hub Name: [%s]. Created At: %s. partitionIds: [%s]%n", eventHubProperties.getName(), eventHubProperties.getCreatedAt(), partitionIds); }
final Mono<EventHubProperties> runOperation = Mono.usingWhen(
public static void main(String[] args) throws IOException { final String iotHubConnectionString = "HostName=<your-iot-hub>.azure-devices.net;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>"; final Mono<String> connectionStringMono = getConnectionString(iotHubConnectionString) .cache(); final Mono<EventHubProperties> runOperation = Mono.usingWhen( connectionStringMono.map(connectionString -> { System.out.println("Acquired Event Hubs compatible connection string."); return new EventHubClientBuilder() .connectionString(connectionString) .buildAsyncProducerClient(); }), producer -> { System.out.println("Created producer client."); return producer.getEventHubProperties(); }, producer -> Mono.fromRunnable(() -> { System.out.println("Disposing of producer client."); producer.close(); })); final EventHubProperties eventHubProperties = runOperation.block(); if (eventHubProperties == null) { System.err.println("No properties were retrieved."); return; } final String partitionIds = eventHubProperties.getPartitionIds() .stream() .collect(Collectors.joining(", ")); System.out.printf("Event Hub Name: [%s]. Created At: %s. partitionIds: [%s]%n", eventHubProperties.getName(), eventHubProperties.getCreatedAt(), partitionIds); }
class IoTHubConnectionSample { /** * Main method for sample. * * @param args Unused arguments. * * @throws IOException IOException if we could not open the reactor IO pipe. */ /** * Mono that completes with the corresponding Event Hubs connection string. * * @param iotHubConnectionString The IoT Hub connection string. In the format: "{@code * HostName=<your-iot-hub>.azure-devices.net;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>}". * * @return A Mono that completes when the connection string is retrieved. Or errors if the transport, connection, or * link could not be opened. * * @throws IllegalArgumentException If the connection string could not be parsed or the shared access key is * invalid. * @throws NullPointerException if the connection string was null or one of the IoT connection string components * is null. * @throws UnsupportedOperationException if the hashing algorithm could not be instantiated. * @throws UncheckedIOException if proton-j could not be started. */ private static Mono<String> getConnectionString(String iotHubConnectionString) { final IoTConnectionStringProperties properties; try { properties = new IoTConnectionStringProperties(iotHubConnectionString); } catch (IllegalArgumentException | NullPointerException error) { return Mono.error(error); } final String entityPath = "messages/events"; final String username = properties.getSharedAccessKeyName() + "@sas.root." + properties.getIoTHubName(); final String resource = properties.getHostname() + "/" + entityPath; final AccessToken accessToken; try { accessToken = generateSharedAccessSignature(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), resource, Duration.ofMinutes(10)); } catch (UnsupportedOperationException | IllegalArgumentException error) { return Mono.error(error); } final Reactor reactor; try { reactor = Proton.reactor(); } catch (IOException e) { return Mono.error(new UncheckedIOException("Unable to create IO pipe for proton-j reactor.", e)); } return Mono.usingWhen( Mono.fromCallable(() -> { final ProtonJHandler handler = new ProtonJHandler("iot-connection-id", properties.getHostname(), username, accessToken); reactor.setHandler(handler); Schedulers.boundedElastic().schedule(() -> reactor.run()); return handler; }), handler -> { return handler.getReceiver(entityPath + "/$management") .map(receiver -> { System.out.println("IoTHub string was compatible with Event Hubs. Did not redirect."); return properties.getRawConnectionString(); }) .onErrorResume(error -> { return error instanceof AmqpException && ((AmqpException) error).getErrorCondition() == AmqpErrorCondition.LINK_REDIRECT; }, error -> { final AmqpException amqpException = (AmqpException) error; final Map<String, Object> errorInfo = amqpException.getContext().getErrorInfo(); final String eventHubsHostname = (String) errorInfo.get("hostname"); if (eventHubsHostname == null) { return Mono.error(new UnsupportedOperationException( "Could not get Event Hubs connection string from error info.", error)); } final String eventHubsConnection = String.format(Locale.ROOT, "Endpoint=sb: eventHubsHostname, properties.getIoTHubName(), properties.getSharedAccessKeyName(), properties.getSharedAccessKey()); return Mono.just(eventHubsConnection); }); }, handler -> { reactor.stop(); return handler.closeAsync(); }); } private static class ProtonJHandler extends BaseHandler implements AsyncCloseable { private static final int PORT = 5671; private final String hostname; private final String username; private final AccessToken token; private final String connectionId; private final Sinks.One<Connection> connectionSink = Sinks.one(); private final ConcurrentMap<String, Sinks.One<Receiver>> receiverSinks = new ConcurrentHashMap<>(); ProtonJHandler(String connectionId, String hostname, String username, AccessToken token) { this.connectionId = connectionId; this.hostname = hostname; this.username = username; this.token = token; } /** * Gets an active connection. Completes with an error if the connection could not be opened. * * @return An active connection. Completes with an error if the connection could not be opened. */ Mono<Connection> getConnection() { return connectionSink.asMono().cache(); } Mono<Receiver> getReceiver(String entityPath) { System.out.println("Creating receiver: " + entityPath); return getConnection().flatMap(activeConnection -> { final Sinks.One<Receiver> receiverSink = receiverSinks.computeIfAbsent(entityPath, key -> { final Session session = activeConnection.session(); final Receiver receiver = session.receiver("receiver " + entityPath); final Source source = new Source(); source.setAddress(entityPath); receiver.setSource(source); receiver.setTarget(new Target()); receiver.setSenderSettleMode(SenderSettleMode.SETTLED); receiver.setReceiverSettleMode(ReceiverSettleMode.SECOND); session.open(); receiver.open(); return Sinks.one(); }); return receiverSink.asMono(); }); } @Override public void onLinkRemoteOpen(Event e) { final Receiver link = e.getReceiver(); if (link == null) { System.out.printf("Was expecting a receiver. Did not get one. Type: %s. Name: %s%n", e.getLink(), e.getLink().getName()); return; } if (link.getCondition() != null) { return; } else if (link.getRemoteState() != EndpointState.ACTIVE) { System.out.println(link.getRemoteState() + ": Remote state is not open. " + link.getCondition()); return; } final String entityPath = link.getSource().getAddress(); final Sinks.One<Receiver> sink = receiverSinks.remove(entityPath); if (sink != null) { sink.emitValue(e.getReceiver(), Sinks.EmitFailureHandler.FAIL_FAST); } else { System.err.printf("There was no corresponding receiver '%s' sink. Closing link.%n", entityPath); link.close(); } } @Override public void onLinkRemoteClose(Event e) { final Link link = e.getLink(); final ErrorCondition remoteCondition = link.getRemoteCondition(); final AmqpErrorCondition errorCondition = AmqpErrorCondition.fromString( remoteCondition.getCondition().toString()); @SuppressWarnings("unchecked") final Map<Symbol, Object> errorInfo = remoteCondition.getInfo(); final Map<String, Object> errorInfoMap = errorInfo != null ? errorInfo.entrySet().stream().collect(HashMap::new, (existing, entry) -> existing.put(entry.getKey().toString(), entry.getValue()), (HashMap::putAll)) : Collections.emptyMap(); final AmqpErrorContext context = new AmqpErrorContext(hostname, errorInfoMap); final AmqpException exception = new AmqpException(false, errorCondition, remoteCondition.getDescription(), context); final String entityPath = link.getSource().getAddress(); final Sinks.One<Receiver> sink = receiverSinks.remove(entityPath); if (sink != null) { sink.emitError(exception, Sinks.EmitFailureHandler.FAIL_FAST); } else { System.err.printf("There was no corresponding receiver '%s' sink. Closing link.%n", entityPath); link.close(); } } @Override public void onConnectionBound(Event e) { final Transport transport = e.getTransport(); final Sasl sasl = transport.sasl(); sasl.plain(username, token.getToken()); final SslDomain sslDomain = Proton.sslDomain(); sslDomain.init(SslDomain.Mode.CLIENT); try { sslDomain.setSslContext(SSLContext.getDefault()); } catch (NoSuchAlgorithmException error) { connectionSink.emitError(new RuntimeException("Could not bind SslContext.", error), Sinks.EmitFailureHandler.FAIL_FAST); } final SslPeerDetails peerDetails = Proton.sslPeerDetails(hostname, PORT); transport.ssl(sslDomain, peerDetails); } @Override public void onConnectionInit(Event e) { final Connection connection = e.getConnection(); connection.setHostname(hostname); connection.setContainer(connectionId); final Map<Symbol, Object> properties = new HashMap<>(); connection.setProperties(properties); connection.open(); } @Override public void onConnectionRemoteOpen(Event e) { System.out.println("Connection state: " + e.getConnection().getRemoteState()); final Connection connection = e.getConnection(); connectionSink.emitValue(connection, Sinks.EmitFailureHandler.FAIL_FAST); } @Override public void onReactorInit(Event e) { e.getReactor().connectionToHost(hostname, PORT, this); } @Override public void onTransportError(Event event) { final AmqpErrorContext context = new AmqpErrorContext(hostname); ErrorCondition condition = event.getTransport().getCondition(); if (condition != null) { final AmqpException exception = new AmqpException(false, AmqpErrorCondition.fromString(condition.getCondition().toString()), condition.getDescription(), context); connectionSink.emitError(exception, Sinks.EmitFailureHandler.FAIL_FAST); } else { connectionSink.emitError(new AmqpException(false, "Error (no description returned).", context), Sinks.EmitFailureHandler.FAIL_FAST); } } @Override public Mono<Void> closeAsync() { return connectionSink .asMono() .flatMap(connection -> Mono.fromRunnable(() -> connection.close())); } } /** * Generates a shared access signature. Details for generating security tokens can be found at: * <a href="https: * tokens</a> * * @param policyName Name of the shared access key policy. * @param sharedAccessKey Value of the shared access key. * @param resourceUri URI of the resource to access. Does not have the scheme in it. * @param tokenDuration Duration of the token. * * @return An access token. */ private static AccessToken generateSharedAccessSignature(String policyName, String sharedAccessKey, String resourceUri, Duration tokenDuration) { final OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plus(tokenDuration); final String expiresOnEpochSeconds = Long.toString(expiresOn.toEpochSecond()); final String stringToSign = URLEncoder.encode(resourceUri, UTF_8) + "\n" + expiresOnEpochSeconds; final byte[] decodedKey = Base64.getDecoder().decode(sharedAccessKey); final Mac sha256HMAC; final SecretKeySpec secretKey; final String hmacSHA256 = "HmacSHA256"; try { sha256HMAC = Mac.getInstance(hmacSHA256); secretKey = new SecretKeySpec(decodedKey, hmacSHA256); sha256HMAC.init(secretKey); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException( String.format("Unable to create hashing algorithm '%s'", hmacSHA256), e); } catch (InvalidKeyException e) { throw new IllegalArgumentException("'sharedAccessKey' is an invalid value for the hashing algorithm.", e); } final byte[] bytes = sha256HMAC.doFinal(stringToSign.getBytes(UTF_8)); final String signature = new String(Base64.getEncoder().encode(bytes), UTF_8); final String token = String.format(Locale.ROOT, "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s", URLEncoder.encode(resourceUri, UTF_8), URLEncoder.encode(signature, UTF_8), expiresOnEpochSeconds, policyName); return new AccessToken(token, expiresOn); } /** * Contains properties from parsing an IoT connection string. */ private static class IoTConnectionStringProperties { private static final String TOKEN_VALUE_SEPARATOR = "="; private static final String TOKEN_VALUE_PAIR_DELIMITER = ";"; private static final String HOST_NAME = "HostName"; private static final String ENDPOINT = "Endpoint"; private static final String SHARED_ACCESS_KEY_NAME = "SharedAccessKeyName"; private static final String SHARED_ACCESS_KEY = "SharedAccessKey"; private final String endpoint; private final String sharedAccessKeyName; private final String sharedAccessKey; private final String iotHubName; private final String connectionString; /** * Parses an IoT Hub connection string into its components. Expects the string to be in format: {@code * "HostName=<your-iot-hub>.azure-devices.net;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>} * * @param connectionString Connection string to parse. * * @throws IllegalArgumentException if the IoT Hub connection string does not have a valid URI endpoint. If * there was not a valid key value pair in the connection string. Or the parameter name is unknown. * @throws NullPointerException if there was no {@code endpoint}, {@code sharedAccessKey} or {@code * sharedAccessKeyName} in the input string. */ private IoTConnectionStringProperties(String connectionString) { this.connectionString = Objects.requireNonNull(connectionString, "'connectionString' is null."); URI endpointUri = null; String sharedAccessKeyName = null; String sharedAccessKeyValue = null; for (String tokenValuePair : connectionString.split(TOKEN_VALUE_PAIR_DELIMITER)) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); if (pair.length != 2) { throw new IllegalArgumentException(String.format(Locale.US, "Connection string has invalid key value pair: %s", tokenValuePair)); } final String key = pair[0].trim(); final String value = pair[1].trim(); if (key.equalsIgnoreCase(HOST_NAME) || key.equalsIgnoreCase(ENDPOINT)) { try { endpointUri = new URI(value); } catch (URISyntaxException e) { throw new IllegalArgumentException( String.format(Locale.US, "Invalid endpoint: %s", tokenValuePair), e); } } else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY_NAME)) { sharedAccessKeyName = value; } else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY)) { sharedAccessKeyValue = value; } else { throw new IllegalArgumentException( String.format(Locale.US, "Illegal connection string parameter name: %s", key)); } } Objects.requireNonNull(endpointUri, "'endpointUri' IoT Hub connection string requires an endpoint."); this.endpoint = endpointUri.getHost() != null ? endpointUri.getHost() : endpointUri.getPath(); this.sharedAccessKeyName = Objects.requireNonNull(sharedAccessKeyName, "'sharedAccessKeyName' IoTHub connection string requires a shared access key policy name."); this.sharedAccessKey = Objects.requireNonNull(sharedAccessKeyValue, "'sharedAccessKeyValue' IoTHub connection string requires a shared access key value."); final String[] split = this.endpoint.split("\\."); if (split[0] == null) { throw new IllegalArgumentException("Could not get the IoT hub name from: " + this.endpoint); } this.iotHubName = split[0]; } private String getIoTHubName() { return iotHubName; } private String getHostname() { return endpoint; } private String getSharedAccessKeyName() { return sharedAccessKeyName; } private String getSharedAccessKey() { return sharedAccessKey; } private String getRawConnectionString() { return connectionString; } } }
class IoTHubConnectionSample { /** * Main method for sample. * * @param args Unused arguments. * * @throws IOException IOException if we could not open the reactor IO pipe. */ /** * Mono that completes with the corresponding Event Hubs connection string. * * @param iotHubConnectionString The IoT Hub connection string. In the format: "{@code * HostName=<your-iot-hub>.azure-devices.net;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>}". * * @return A Mono that completes when the connection string is retrieved. Or errors if the transport, connection, or * link could not be opened. * * @throws IllegalArgumentException If the connection string could not be parsed or the shared access key is * invalid. * @throws NullPointerException if the connection string was null or one of the IoT connection string components * is null. * @throws UnsupportedOperationException if the hashing algorithm could not be instantiated. * @throws UncheckedIOException if proton-j could not be started. */ private static Mono<String> getConnectionString(String iotHubConnectionString) { final IoTConnectionStringProperties properties; try { properties = new IoTConnectionStringProperties(iotHubConnectionString); } catch (IllegalArgumentException | NullPointerException error) { return Mono.error(error); } final String entityPath = "messages/events"; final String username = properties.getSharedAccessKeyName() + "@sas.root." + properties.getIoTHubName(); final String resource = properties.getHostname() + "/" + entityPath; final AccessToken accessToken; try { accessToken = generateSharedAccessSignature(properties.getSharedAccessKeyName(), properties.getSharedAccessKey(), resource, Duration.ofMinutes(10)); } catch (UnsupportedOperationException | IllegalArgumentException | UnsupportedEncodingException error) { return Mono.error(error); } final Reactor reactor; try { reactor = Proton.reactor(); } catch (IOException e) { return Mono.error(new UncheckedIOException("Unable to create IO pipe for proton-j reactor.", e)); } return Mono.usingWhen( Mono.fromCallable(() -> { final ProtonJHandler handler = new ProtonJHandler("iot-connection-id", properties.getHostname(), username, accessToken); reactor.setHandler(handler); Schedulers.boundedElastic().schedule(() -> reactor.run()); return handler; }), handler -> { return handler.getReceiver(entityPath + "/$management") .map(receiver -> { System.out.println("IoTHub string was compatible with Event Hubs. Did not redirect."); return properties.getRawConnectionString(); }) .onErrorResume(error -> { return error instanceof AmqpException && ((AmqpException) error).getErrorCondition() == AmqpErrorCondition.LINK_REDIRECT; }, error -> { final AmqpException amqpException = (AmqpException) error; final Map<String, Object> errorInfo = amqpException.getContext().getErrorInfo(); final String eventHubsHostname = (String) errorInfo.get("hostname"); if (eventHubsHostname == null) { return Mono.error(new UnsupportedOperationException( "Could not get Event Hubs connection string from error info.", error)); } final String eventHubsConnection = String.format(Locale.ROOT, "Endpoint=sb: eventHubsHostname, properties.getIoTHubName(), properties.getSharedAccessKeyName(), properties.getSharedAccessKey()); return Mono.just(eventHubsConnection); }); }, handler -> { reactor.stop(); return handler.closeAsync(); }); } private static class ProtonJHandler extends BaseHandler implements AsyncCloseable { private static final int PORT = 5671; private final String hostname; private final String username; private final AccessToken token; private final String connectionId; private final Sinks.One<Connection> connectionSink = Sinks.one(); private final ConcurrentMap<String, Sinks.One<Receiver>> receiverSinks = new ConcurrentHashMap<>(); ProtonJHandler(String connectionId, String hostname, String username, AccessToken token) { this.connectionId = connectionId; this.hostname = hostname; this.username = username; this.token = token; } /** * Gets an active connection. Completes with an error if the connection could not be opened. * * @return An active connection. Completes with an error if the connection could not be opened. */ Mono<Connection> getConnection() { return connectionSink.asMono().cache(); } Mono<Receiver> getReceiver(String entityPath) { System.out.println("Creating receiver: " + entityPath); return getConnection().flatMap(activeConnection -> { final Sinks.One<Receiver> receiverSink = receiverSinks.computeIfAbsent(entityPath, key -> { final Session session = activeConnection.session(); final Receiver receiver = session.receiver("receiver " + entityPath); final Source source = new Source(); source.setAddress(entityPath); receiver.setSource(source); receiver.setTarget(new Target()); receiver.setSenderSettleMode(SenderSettleMode.SETTLED); receiver.setReceiverSettleMode(ReceiverSettleMode.SECOND); session.open(); receiver.open(); return Sinks.one(); }); return receiverSink.asMono(); }); } @Override public void onLinkRemoteOpen(Event e) { final Receiver link = e.getReceiver(); if (link == null) { System.out.printf("Was expecting a receiver. Did not get one. Type: %s. Name: %s%n", e.getLink(), e.getLink().getName()); return; } if (link.getCondition() != null) { return; } else if (link.getRemoteState() != EndpointState.ACTIVE) { System.out.println(link.getRemoteState() + ": Remote state is not open. " + link.getCondition()); return; } final String entityPath = link.getSource().getAddress(); final Sinks.One<Receiver> sink = receiverSinks.remove(entityPath); if (sink != null) { sink.emitValue(e.getReceiver(), Sinks.EmitFailureHandler.FAIL_FAST); } else { System.err.printf("There was no corresponding receiver '%s' sink. Closing link.%n", entityPath); link.close(); } } @Override public void onLinkRemoteClose(Event e) { final Link link = e.getLink(); final ErrorCondition remoteCondition = link.getRemoteCondition(); final AmqpErrorCondition errorCondition = AmqpErrorCondition.fromString( remoteCondition.getCondition().toString()); @SuppressWarnings("unchecked") final Map<Symbol, Object> errorInfo = remoteCondition.getInfo(); final Map<String, Object> errorInfoMap = errorInfo != null ? errorInfo.entrySet().stream().collect(HashMap::new, (existing, entry) -> existing.put(entry.getKey().toString(), entry.getValue()), (HashMap::putAll)) : Collections.emptyMap(); final AmqpErrorContext context = new AmqpErrorContext(hostname, errorInfoMap); final AmqpException exception = new AmqpException(false, errorCondition, remoteCondition.getDescription(), context); final String entityPath = link.getSource().getAddress(); final Sinks.One<Receiver> sink = receiverSinks.remove(entityPath); if (sink != null) { sink.emitError(exception, Sinks.EmitFailureHandler.FAIL_FAST); } else { System.err.printf("There was no corresponding receiver '%s' sink. Closing link.%n", entityPath); link.close(); } } @Override public void onConnectionBound(Event e) { final Transport transport = e.getTransport(); final Sasl sasl = transport.sasl(); sasl.plain(username, token.getToken()); final SslDomain sslDomain = Proton.sslDomain(); sslDomain.init(SslDomain.Mode.CLIENT); try { sslDomain.setSslContext(SSLContext.getDefault()); } catch (NoSuchAlgorithmException error) { connectionSink.emitError(new RuntimeException("Could not bind SslContext.", error), Sinks.EmitFailureHandler.FAIL_FAST); } final SslPeerDetails peerDetails = Proton.sslPeerDetails(hostname, PORT); transport.ssl(sslDomain, peerDetails); } @Override public void onConnectionInit(Event e) { final Connection connection = e.getConnection(); connection.setHostname(hostname); connection.setContainer(connectionId); final Map<Symbol, Object> properties = new HashMap<>(); connection.setProperties(properties); connection.open(); } @Override public void onConnectionRemoteOpen(Event e) { System.out.println("Connection state: " + e.getConnection().getRemoteState()); final Connection connection = e.getConnection(); connectionSink.emitValue(connection, Sinks.EmitFailureHandler.FAIL_FAST); } @Override public void onReactorInit(Event e) { e.getReactor().connectionToHost(hostname, PORT, this); } @Override public void onTransportError(Event event) { final AmqpErrorContext context = new AmqpErrorContext(hostname); ErrorCondition condition = event.getTransport().getCondition(); if (condition != null) { final AmqpException exception = new AmqpException(false, AmqpErrorCondition.fromString(condition.getCondition().toString()), condition.getDescription(), context); connectionSink.emitError(exception, Sinks.EmitFailureHandler.FAIL_FAST); } else { connectionSink.emitError(new AmqpException(false, "Error (no description returned).", context), Sinks.EmitFailureHandler.FAIL_FAST); } } @Override public Mono<Void> closeAsync() { return connectionSink .asMono() .flatMap(connection -> Mono.fromRunnable(() -> connection.close())); } } /** * Generates a shared access signature. Details for generating security tokens can be found at: * <a href="https: * tokens</a> * * @param policyName Name of the shared access key policy. * @param sharedAccessKey Value of the shared access key. * @param resourceUri URI of the resource to access. Does not have the scheme in it. * @param tokenDuration Duration of the token. * * @return An access token. */ private static AccessToken generateSharedAccessSignature(String policyName, String sharedAccessKey, String resourceUri, Duration tokenDuration) throws UnsupportedEncodingException { final OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plus(tokenDuration); final String utf8Encoding = UTF_8.name(); final String expiresOnEpochSeconds = Long.toString(expiresOn.toEpochSecond()); final String stringToSign = URLEncoder.encode(resourceUri, utf8Encoding) + "\n" + expiresOnEpochSeconds; final byte[] decodedKey = Base64.getDecoder().decode(sharedAccessKey); final Mac sha256HMAC; final SecretKeySpec secretKey; final String hmacSHA256 = "HmacSHA256"; try { sha256HMAC = Mac.getInstance(hmacSHA256); secretKey = new SecretKeySpec(decodedKey, hmacSHA256); sha256HMAC.init(secretKey); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException( String.format("Unable to create hashing algorithm '%s'", hmacSHA256), e); } catch (InvalidKeyException e) { throw new IllegalArgumentException("'sharedAccessKey' is an invalid value for the hashing algorithm.", e); } final byte[] bytes = sha256HMAC.doFinal(stringToSign.getBytes(UTF_8)); final String signature = new String(Base64.getEncoder().encode(bytes), UTF_8); final String token = String.format(Locale.ROOT, "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s", URLEncoder.encode(resourceUri, utf8Encoding), URLEncoder.encode(signature, utf8Encoding), expiresOnEpochSeconds, policyName); return new AccessToken(token, expiresOn); } /** * Contains properties from parsing an IoT connection string. */ private static final class IoTConnectionStringProperties { private static final String TOKEN_VALUE_SEPARATOR = "="; private static final String TOKEN_VALUE_PAIR_DELIMITER = ";"; private static final String HOST_NAME = "HostName"; private static final String ENDPOINT = "Endpoint"; private static final String SHARED_ACCESS_KEY_NAME = "SharedAccessKeyName"; private static final String SHARED_ACCESS_KEY = "SharedAccessKey"; private final String endpoint; private final String sharedAccessKeyName; private final String sharedAccessKey; private final String iotHubName; private final String connectionString; /** * Parses an IoT Hub connection string into its components. Expects the string to be in format: {@code * "HostName=<your-iot-hub>.azure-devices.net;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>} * * @param connectionString Connection string to parse. * * @throws IllegalArgumentException if the IoT Hub connection string does not have a valid URI endpoint. If * there was not a valid key value pair in the connection string. Or the parameter name is unknown. * @throws NullPointerException if there was no {@code endpoint}, {@code sharedAccessKey} or {@code * sharedAccessKeyName} in the input string. */ private IoTConnectionStringProperties(String connectionString) { this.connectionString = Objects.requireNonNull(connectionString, "'connectionString' is null."); URI endpointUri = null; String sharedAccessKeyName = null; String sharedAccessKeyValue = null; for (String tokenValuePair : connectionString.split(TOKEN_VALUE_PAIR_DELIMITER)) { final String[] pair = tokenValuePair.split(TOKEN_VALUE_SEPARATOR, 2); if (pair.length != 2) { throw new IllegalArgumentException(String.format(Locale.US, "Connection string has invalid key value pair: %s", tokenValuePair)); } final String key = pair[0].trim(); final String value = pair[1].trim(); if (key.equalsIgnoreCase(HOST_NAME) || key.equalsIgnoreCase(ENDPOINT)) { try { endpointUri = new URI(value); } catch (URISyntaxException e) { throw new IllegalArgumentException( String.format(Locale.US, "Invalid endpoint: %s", tokenValuePair), e); } } else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY_NAME)) { sharedAccessKeyName = value; } else if (key.equalsIgnoreCase(SHARED_ACCESS_KEY)) { sharedAccessKeyValue = value; } else { throw new IllegalArgumentException( String.format(Locale.US, "Illegal connection string parameter name: %s", key)); } } Objects.requireNonNull(endpointUri, "'endpointUri' IoT Hub connection string requires an endpoint."); this.endpoint = endpointUri.getHost() != null ? endpointUri.getHost() : endpointUri.getPath(); this.sharedAccessKeyName = Objects.requireNonNull(sharedAccessKeyName, "'sharedAccessKeyName' IoTHub connection string requires a shared access key policy name."); this.sharedAccessKey = Objects.requireNonNull(sharedAccessKeyValue, "'sharedAccessKeyValue' IoTHub connection string requires a shared access key value."); final String[] split = this.endpoint.split("\\."); if (split[0] == null) { throw new IllegalArgumentException("Could not get the IoT hub name from: " + this.endpoint); } this.iotHubName = split[0]; } private String getIoTHubName() { return iotHubName; } private String getHostname() { return endpoint; } private String getSharedAccessKeyName() { return sharedAccessKeyName; } private String getSharedAccessKey() { return sharedAccessKey; } private String getRawConnectionString() { return connectionString; } } }
I remember this is default value? Then we don't need it even though it doesn't hurt.
void run() throws InterruptedException { topicSenderAsyncClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildAsyncClient(); administrationAsyncClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .serviceVersion(ServiceBusServiceVersion.getLatest()) .buildAsyncClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new TrueRuleFilter())).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new SqlRuleFilter("Color = 'Red'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions().setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))).block(); administrationAsyncClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME).collectList() .doOnSuccess(listRuleProperties -> { listRuleProperties.forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); }).block(); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); topicSenderAsyncClient.close(); }
.serviceVersion(ServiceBusServiceVersion.getLatest())
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = "{Your Service Bus Connection String}"; static final String SERVICE_BUS_TOPIC_NAME = "{Your Service Bus Topic Name}"; static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; static final String MESSAGE_JSON_ITEM_NAME_LABEL = "label"; static final String MESSAGE_JSON_ITEM_NAME_CORRELATION_ID = "correlationId"; static final Gson GSON = new Gson(); static ServiceBusSenderAsyncClient topicSenderAsyncClient; static ServiceBusAdministrationAsyncClient administrationAsyncClient; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("EntityPath = %s, Label = %s, CorrelationId = %s", subscriptionName, receivedMessage.getBody().toString(), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { List<HashMap<String, String>> messageDataList = GSON.fromJson("[{\"label\":\"Red\"}," + "{\"label\":\"Blue\"}," + "{\"label\":\"Red\", \"correlationId\":\"important\"}," + "{\"label\":\"Blue\", \"correlationId\":\"important\"}," + "{\"label\":\"Red\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Blue\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Green\"}," + "{\"label\":\"Green\", \"correlationId\":\"important\"}," + "{\"label\":\"Green\", \"correlationId\":\"notimportant\"}]", new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType()); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch batchMessage = topicSenderAsyncClient.createMessageBatch() .doOnSuccess(messageBatch -> { messageDataList.forEach(messageMap -> { ServiceBusMessage message = new ServiceBusMessage(BinaryData.fromString(messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL))); message.getApplicationProperties().put("Color", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL)); if (messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) && messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) != null) { message.setCorrelationId(messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID)); } messageBatch.tryAddMessage(message); System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL), !messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) || messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) == null ? "" : messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID))); }); }).block(); topicSenderAsyncClient.sendMessages(batchMessage) .doOnError(onError -> System.out.println(String.format("%s :: Exception: %s", OffsetDateTime.now(), onError.getMessage()))) .doOnSuccess(onSuccess -> System.out.println(String.format("%s :: Sent message success to topic: %s", OffsetDateTime.now(), SERVICE_BUS_TOPIC_NAME))) .block(); } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
Use `deleteRule` instead of `deleteRuleWithResponse` since you don't care the response.
void run() throws InterruptedException { topicSenderAsyncClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildAsyncClient(); administrationAsyncClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .serviceVersion(ServiceBusServiceVersion.getLatest()) .buildAsyncClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new TrueRuleFilter())).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new SqlRuleFilter("Color = 'Red'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions().setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))).block(); administrationAsyncClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME).collectList() .doOnSuccess(listRuleProperties -> { listRuleProperties.forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); }).block(); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); topicSenderAsyncClient.close(); }
administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block();
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = "{Your Service Bus Connection String}"; static final String SERVICE_BUS_TOPIC_NAME = "{Your Service Bus Topic Name}"; static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; static final String MESSAGE_JSON_ITEM_NAME_LABEL = "label"; static final String MESSAGE_JSON_ITEM_NAME_CORRELATION_ID = "correlationId"; static final Gson GSON = new Gson(); static ServiceBusSenderAsyncClient topicSenderAsyncClient; static ServiceBusAdministrationAsyncClient administrationAsyncClient; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("EntityPath = %s, Label = %s, CorrelationId = %s", subscriptionName, receivedMessage.getBody().toString(), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { List<HashMap<String, String>> messageDataList = GSON.fromJson("[{\"label\":\"Red\"}," + "{\"label\":\"Blue\"}," + "{\"label\":\"Red\", \"correlationId\":\"important\"}," + "{\"label\":\"Blue\", \"correlationId\":\"important\"}," + "{\"label\":\"Red\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Blue\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Green\"}," + "{\"label\":\"Green\", \"correlationId\":\"important\"}," + "{\"label\":\"Green\", \"correlationId\":\"notimportant\"}]", new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType()); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch batchMessage = topicSenderAsyncClient.createMessageBatch() .doOnSuccess(messageBatch -> { messageDataList.forEach(messageMap -> { ServiceBusMessage message = new ServiceBusMessage(BinaryData.fromString(messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL))); message.getApplicationProperties().put("Color", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL)); if (messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) && messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) != null) { message.setCorrelationId(messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID)); } messageBatch.tryAddMessage(message); System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL), !messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) || messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) == null ? "" : messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID))); }); }).block(); topicSenderAsyncClient.sendMessages(batchMessage) .doOnError(onError -> System.out.println(String.format("%s :: Exception: %s", OffsetDateTime.now(), onError.getMessage()))) .doOnSuccess(onSuccess -> System.out.println(String.format("%s :: Sent message success to topic: %s", OffsetDateTime.now(), SERVICE_BUS_TOPIC_NAME))) .block(); } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
I suggest we use the sync client for this sample since there are a lot of .block()
void run() throws InterruptedException { topicSenderAsyncClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildAsyncClient(); administrationAsyncClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .serviceVersion(ServiceBusServiceVersion.getLatest()) .buildAsyncClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new TrueRuleFilter())).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new SqlRuleFilter("Color = 'Red'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions().setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))).block(); administrationAsyncClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME).collectList() .doOnSuccess(listRuleProperties -> { listRuleProperties.forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); }).block(); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); topicSenderAsyncClient.close(); }
new CreateRuleOptions(new TrueRuleFilter())).block();
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = "{Your Service Bus Connection String}"; static final String SERVICE_BUS_TOPIC_NAME = "{Your Service Bus Topic Name}"; static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; static final String MESSAGE_JSON_ITEM_NAME_LABEL = "label"; static final String MESSAGE_JSON_ITEM_NAME_CORRELATION_ID = "correlationId"; static final Gson GSON = new Gson(); static ServiceBusSenderAsyncClient topicSenderAsyncClient; static ServiceBusAdministrationAsyncClient administrationAsyncClient; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("EntityPath = %s, Label = %s, CorrelationId = %s", subscriptionName, receivedMessage.getBody().toString(), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { List<HashMap<String, String>> messageDataList = GSON.fromJson("[{\"label\":\"Red\"}," + "{\"label\":\"Blue\"}," + "{\"label\":\"Red\", \"correlationId\":\"important\"}," + "{\"label\":\"Blue\", \"correlationId\":\"important\"}," + "{\"label\":\"Red\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Blue\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Green\"}," + "{\"label\":\"Green\", \"correlationId\":\"important\"}," + "{\"label\":\"Green\", \"correlationId\":\"notimportant\"}]", new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType()); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch batchMessage = topicSenderAsyncClient.createMessageBatch() .doOnSuccess(messageBatch -> { messageDataList.forEach(messageMap -> { ServiceBusMessage message = new ServiceBusMessage(BinaryData.fromString(messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL))); message.getApplicationProperties().put("Color", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL)); if (messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) && messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) != null) { message.setCorrelationId(messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID)); } messageBatch.tryAddMessage(message); System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL), !messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) || messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) == null ? "" : messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID))); }); }).block(); topicSenderAsyncClient.sendMessages(batchMessage) .doOnError(onError -> System.out.println(String.format("%s :: Exception: %s", OffsetDateTime.now(), onError.getMessage()))) .doOnSuccess(onSuccess -> System.out.println(String.format("%s :: Sent message success to topic: %s", OffsetDateTime.now(), SERVICE_BUS_TOPIC_NAME))) .block(); } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
We usually don't use side-effect APIs like `doOn...` to process data. If you change to use sync client, this isn't relevant any more.
void run() throws InterruptedException { topicSenderAsyncClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildAsyncClient(); administrationAsyncClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .serviceVersion(ServiceBusServiceVersion.getLatest()) .buildAsyncClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new TrueRuleFilter())).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new SqlRuleFilter("Color = 'Red'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions().setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))).block(); administrationAsyncClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME).collectList() .doOnSuccess(listRuleProperties -> { listRuleProperties.forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); }).block(); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); topicSenderAsyncClient.close(); }
.doOnSuccess(listRuleProperties -> {
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = "{Your Service Bus Connection String}"; static final String SERVICE_BUS_TOPIC_NAME = "{Your Service Bus Topic Name}"; static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; static final String MESSAGE_JSON_ITEM_NAME_LABEL = "label"; static final String MESSAGE_JSON_ITEM_NAME_CORRELATION_ID = "correlationId"; static final Gson GSON = new Gson(); static ServiceBusSenderAsyncClient topicSenderAsyncClient; static ServiceBusAdministrationAsyncClient administrationAsyncClient; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("EntityPath = %s, Label = %s, CorrelationId = %s", subscriptionName, receivedMessage.getBody().toString(), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { List<HashMap<String, String>> messageDataList = GSON.fromJson("[{\"label\":\"Red\"}," + "{\"label\":\"Blue\"}," + "{\"label\":\"Red\", \"correlationId\":\"important\"}," + "{\"label\":\"Blue\", \"correlationId\":\"important\"}," + "{\"label\":\"Red\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Blue\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Green\"}," + "{\"label\":\"Green\", \"correlationId\":\"important\"}," + "{\"label\":\"Green\", \"correlationId\":\"notimportant\"}]", new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType()); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch batchMessage = topicSenderAsyncClient.createMessageBatch() .doOnSuccess(messageBatch -> { messageDataList.forEach(messageMap -> { ServiceBusMessage message = new ServiceBusMessage(BinaryData.fromString(messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL))); message.getApplicationProperties().put("Color", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL)); if (messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) && messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) != null) { message.setCorrelationId(messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID)); } messageBatch.tryAddMessage(message); System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL), !messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) || messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) == null ? "" : messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID))); }); }).block(); topicSenderAsyncClient.sendMessages(batchMessage) .doOnError(onError -> System.out.println(String.format("%s :: Exception: %s", OffsetDateTime.now(), onError.getMessage()))) .doOnSuccess(onSuccess -> System.out.println(String.format("%s :: Sent message success to topic: %s", OffsetDateTime.now(), SERVICE_BUS_TOPIC_NAME))) .block(); } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
According to your comment, fixed in new version.
void run() throws InterruptedException { topicSenderAsyncClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildAsyncClient(); administrationAsyncClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .serviceVersion(ServiceBusServiceVersion.getLatest()) .buildAsyncClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new TrueRuleFilter())).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new SqlRuleFilter("Color = 'Red'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions().setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))).block(); administrationAsyncClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME).collectList() .doOnSuccess(listRuleProperties -> { listRuleProperties.forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); }).block(); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); topicSenderAsyncClient.close(); }
.serviceVersion(ServiceBusServiceVersion.getLatest())
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = "{Your Service Bus Connection String}"; static final String SERVICE_BUS_TOPIC_NAME = "{Your Service Bus Topic Name}"; static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; static final String MESSAGE_JSON_ITEM_NAME_LABEL = "label"; static final String MESSAGE_JSON_ITEM_NAME_CORRELATION_ID = "correlationId"; static final Gson GSON = new Gson(); static ServiceBusSenderAsyncClient topicSenderAsyncClient; static ServiceBusAdministrationAsyncClient administrationAsyncClient; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("EntityPath = %s, Label = %s, CorrelationId = %s", subscriptionName, receivedMessage.getBody().toString(), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { List<HashMap<String, String>> messageDataList = GSON.fromJson("[{\"label\":\"Red\"}," + "{\"label\":\"Blue\"}," + "{\"label\":\"Red\", \"correlationId\":\"important\"}," + "{\"label\":\"Blue\", \"correlationId\":\"important\"}," + "{\"label\":\"Red\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Blue\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Green\"}," + "{\"label\":\"Green\", \"correlationId\":\"important\"}," + "{\"label\":\"Green\", \"correlationId\":\"notimportant\"}]", new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType()); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch batchMessage = topicSenderAsyncClient.createMessageBatch() .doOnSuccess(messageBatch -> { messageDataList.forEach(messageMap -> { ServiceBusMessage message = new ServiceBusMessage(BinaryData.fromString(messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL))); message.getApplicationProperties().put("Color", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL)); if (messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) && messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) != null) { message.setCorrelationId(messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID)); } messageBatch.tryAddMessage(message); System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL), !messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) || messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) == null ? "" : messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID))); }); }).block(); topicSenderAsyncClient.sendMessages(batchMessage) .doOnError(onError -> System.out.println(String.format("%s :: Exception: %s", OffsetDateTime.now(), onError.getMessage()))) .doOnSuccess(onSuccess -> System.out.println(String.format("%s :: Sent message success to topic: %s", OffsetDateTime.now(), SERVICE_BUS_TOPIC_NAME))) .block(); } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
According to your comment, fixed in new version.
void run() throws InterruptedException { topicSenderAsyncClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildAsyncClient(); administrationAsyncClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .serviceVersion(ServiceBusServiceVersion.getLatest()) .buildAsyncClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new TrueRuleFilter())).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new SqlRuleFilter("Color = 'Red'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions().setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))).block(); administrationAsyncClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME).collectList() .doOnSuccess(listRuleProperties -> { listRuleProperties.forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); }).block(); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); topicSenderAsyncClient.close(); }
administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block();
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = "{Your Service Bus Connection String}"; static final String SERVICE_BUS_TOPIC_NAME = "{Your Service Bus Topic Name}"; static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; static final String MESSAGE_JSON_ITEM_NAME_LABEL = "label"; static final String MESSAGE_JSON_ITEM_NAME_CORRELATION_ID = "correlationId"; static final Gson GSON = new Gson(); static ServiceBusSenderAsyncClient topicSenderAsyncClient; static ServiceBusAdministrationAsyncClient administrationAsyncClient; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("EntityPath = %s, Label = %s, CorrelationId = %s", subscriptionName, receivedMessage.getBody().toString(), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { List<HashMap<String, String>> messageDataList = GSON.fromJson("[{\"label\":\"Red\"}," + "{\"label\":\"Blue\"}," + "{\"label\":\"Red\", \"correlationId\":\"important\"}," + "{\"label\":\"Blue\", \"correlationId\":\"important\"}," + "{\"label\":\"Red\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Blue\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Green\"}," + "{\"label\":\"Green\", \"correlationId\":\"important\"}," + "{\"label\":\"Green\", \"correlationId\":\"notimportant\"}]", new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType()); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch batchMessage = topicSenderAsyncClient.createMessageBatch() .doOnSuccess(messageBatch -> { messageDataList.forEach(messageMap -> { ServiceBusMessage message = new ServiceBusMessage(BinaryData.fromString(messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL))); message.getApplicationProperties().put("Color", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL)); if (messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) && messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) != null) { message.setCorrelationId(messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID)); } messageBatch.tryAddMessage(message); System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL), !messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) || messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) == null ? "" : messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID))); }); }).block(); topicSenderAsyncClient.sendMessages(batchMessage) .doOnError(onError -> System.out.println(String.format("%s :: Exception: %s", OffsetDateTime.now(), onError.getMessage()))) .doOnSuccess(onSuccess -> System.out.println(String.format("%s :: Sent message success to topic: %s", OffsetDateTime.now(), SERVICE_BUS_TOPIC_NAME))) .block(); } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
According to your comment, fixed in new version.
void run() throws InterruptedException { topicSenderAsyncClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildAsyncClient(); administrationAsyncClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .serviceVersion(ServiceBusServiceVersion.getLatest()) .buildAsyncClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new TrueRuleFilter())).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new SqlRuleFilter("Color = 'Red'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions().setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))).block(); administrationAsyncClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME).collectList() .doOnSuccess(listRuleProperties -> { listRuleProperties.forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); }).block(); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); topicSenderAsyncClient.close(); }
new CreateRuleOptions(new TrueRuleFilter())).block();
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = "{Your Service Bus Connection String}"; static final String SERVICE_BUS_TOPIC_NAME = "{Your Service Bus Topic Name}"; static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; static final String MESSAGE_JSON_ITEM_NAME_LABEL = "label"; static final String MESSAGE_JSON_ITEM_NAME_CORRELATION_ID = "correlationId"; static final Gson GSON = new Gson(); static ServiceBusSenderAsyncClient topicSenderAsyncClient; static ServiceBusAdministrationAsyncClient administrationAsyncClient; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("EntityPath = %s, Label = %s, CorrelationId = %s", subscriptionName, receivedMessage.getBody().toString(), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { List<HashMap<String, String>> messageDataList = GSON.fromJson("[{\"label\":\"Red\"}," + "{\"label\":\"Blue\"}," + "{\"label\":\"Red\", \"correlationId\":\"important\"}," + "{\"label\":\"Blue\", \"correlationId\":\"important\"}," + "{\"label\":\"Red\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Blue\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Green\"}," + "{\"label\":\"Green\", \"correlationId\":\"important\"}," + "{\"label\":\"Green\", \"correlationId\":\"notimportant\"}]", new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType()); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch batchMessage = topicSenderAsyncClient.createMessageBatch() .doOnSuccess(messageBatch -> { messageDataList.forEach(messageMap -> { ServiceBusMessage message = new ServiceBusMessage(BinaryData.fromString(messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL))); message.getApplicationProperties().put("Color", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL)); if (messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) && messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) != null) { message.setCorrelationId(messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID)); } messageBatch.tryAddMessage(message); System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL), !messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) || messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) == null ? "" : messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID))); }); }).block(); topicSenderAsyncClient.sendMessages(batchMessage) .doOnError(onError -> System.out.println(String.format("%s :: Exception: %s", OffsetDateTime.now(), onError.getMessage()))) .doOnSuccess(onSuccess -> System.out.println(String.format("%s :: Sent message success to topic: %s", OffsetDateTime.now(), SERVICE_BUS_TOPIC_NAME))) .block(); } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
According to your comment, fixed in new version.
void run() throws InterruptedException { topicSenderAsyncClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildAsyncClient(); administrationAsyncClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .serviceVersion(ServiceBusServiceVersion.getLatest()) .buildAsyncClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new TrueRuleFilter())).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new SqlRuleFilter("Color = 'Red'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions().setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))).block(); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationAsyncClient.deleteRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME).block(); administrationAsyncClient.createRuleWithResponse(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME, new CreateRuleOptions(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))).block(); administrationAsyncClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME).collectList() .doOnSuccess(listRuleProperties -> { listRuleProperties.forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); }).block(); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); topicSenderAsyncClient.close(); }
.doOnSuccess(listRuleProperties -> {
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = "{Your Service Bus Connection String}"; static final String SERVICE_BUS_TOPIC_NAME = "{Your Service Bus Topic Name}"; static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; static final String MESSAGE_JSON_ITEM_NAME_LABEL = "label"; static final String MESSAGE_JSON_ITEM_NAME_CORRELATION_ID = "correlationId"; static final Gson GSON = new Gson(); static ServiceBusSenderAsyncClient topicSenderAsyncClient; static ServiceBusAdministrationAsyncClient administrationAsyncClient; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("EntityPath = %s, Label = %s, CorrelationId = %s", subscriptionName, receivedMessage.getBody().toString(), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { List<HashMap<String, String>> messageDataList = GSON.fromJson("[{\"label\":\"Red\"}," + "{\"label\":\"Blue\"}," + "{\"label\":\"Red\", \"correlationId\":\"important\"}," + "{\"label\":\"Blue\", \"correlationId\":\"important\"}," + "{\"label\":\"Red\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Blue\", \"correlationId\":\"notimportant\"}," + "{\"label\":\"Green\"}," + "{\"label\":\"Green\", \"correlationId\":\"important\"}," + "{\"label\":\"Green\", \"correlationId\":\"notimportant\"}]", new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType()); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch batchMessage = topicSenderAsyncClient.createMessageBatch() .doOnSuccess(messageBatch -> { messageDataList.forEach(messageMap -> { ServiceBusMessage message = new ServiceBusMessage(BinaryData.fromString(messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL))); message.getApplicationProperties().put("Color", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL)); if (messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) && messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) != null) { message.setCorrelationId(messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID)); } messageBatch.tryAddMessage(message); System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", messageMap.get(MESSAGE_JSON_ITEM_NAME_LABEL), !messageMap.containsKey(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) || messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID) == null ? "" : messageMap.get(MESSAGE_JSON_ITEM_NAME_CORRELATION_ID))); }); }).block(); topicSenderAsyncClient.sendMessages(batchMessage) .doOnError(onError -> System.out.println(String.format("%s :: Exception: %s", OffsetDateTime.now(), onError.getMessage()))) .doOnSuccess(onSuccess -> System.out.println(String.format("%s :: Sent message success to topic: %s", OffsetDateTime.now(), SERVICE_BUS_TOPIC_NAME))) .block(); } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
You can use `System.out.printf()`. And end the format string with `%n` to get that new line.
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME));
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
You're not leaving the rule as is? You're actually deleting the rule and adding a "TrueRuleFilter" rule back.
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
This applies to all other instances where you do the same pattern.
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME);
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
This is not an asynchronous function, I would remove the `async` keyword.
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME);
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
According to your comment, fixed within new version
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME));
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
According to your comment, fixed within new version
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
According to your comment, fixed within new version
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME);
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
According to your comment, fixed within new version
void run() throws InterruptedException { ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildClient(); System.out.println(String.format("SubscriptionName: %s, Removing and re-adding Default Rule", ALL_MESSAGES_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, ALL_MESSAGES_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME) .setFilter(new TrueRuleFilter())); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter", SQL_FILTER_ONLY_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_NAME, SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Red'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME, SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME) .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'"))); System.out.println(String.format("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter", CORRELATION_FILTER_SUBSCRIPTION_NAME)); administrationClient.deleteRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, DEFAULT_SUBSCRIPTION_RULE_NAME); administrationClient.createRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME); administrationClient.updateRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, administrationClient.getRule(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME, CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME) .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red"))); administrationClient.listRules(SERVICE_BUS_TOPIC_NAME, CORRELATION_FILTER_SUBSCRIPTION_NAME) .forEach(ruleProperties -> { System.out.println(String.format("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s", CORRELATION_FILTER_SUBSCRIPTION_NAME, ruleProperties.getName(), ruleProperties.getFilter())); }); sendMessagesAsync(); receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_ONLY_SUBSCRIPTION_NAME); receiveMessagesAsync(SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME); receiveMessagesAsync(CORRELATION_FILTER_SUBSCRIPTION_NAME); }
receiveMessagesAsync(ALL_MESSAGES_SUBSCRIPTION_NAME);
void run() { final String allMessagesSubscription = "{Subscription 1 Name}"; final String sqlFilterOnlySubscription = "{Subscription 2 Name}"; final String sqlFilterWithActionSubscription = "{Subscription 3 Name}"; final String correlationFilterSubscription = "{Subscription 4 Name}"; final String defaultRuleName = "$Default"; final String sqlFilterOnlyRuleName = "RedSqlRule"; final String sqlFilterWithActionRuleName = "BlueSqlRule"; final String correlationFilterSubscriptionRule = "ImportantCorrelationRule"; final ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .buildClient(); System.out.printf("SubscriptionName: %s, Removing and re-adding Default Rule%n", allMessagesSubscription); administrationClient.deleteRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName); final CreateRuleOptions defaultRuleOptions = new CreateRuleOptions() .setFilter(new TrueRuleFilter()); administrationClient.createRule(TOPIC_NAME, allMessagesSubscription, defaultRuleName, defaultRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding SqlFilter%n", sqlFilterOnlySubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterOnlySubscription, defaultRuleName); final CreateRuleOptions sqlFilterRuleOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Red'")); administrationClient.createRule(TOPIC_NAME, sqlFilterOnlySubscription, sqlFilterOnlyRuleName, sqlFilterRuleOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", sqlFilterWithActionSubscription); administrationClient.deleteRule(TOPIC_NAME, sqlFilterWithActionSubscription, defaultRuleName); final CreateRuleOptions sqlRuleWithActionOptions = new CreateRuleOptions() .setFilter(new SqlRuleFilter("Color = 'Blue'")) .setAction(new SqlRuleAction("SET Color = 'BlueProcessed'")); administrationClient.createRule(TOPIC_NAME, sqlFilterWithActionSubscription, sqlFilterWithActionRuleName, sqlRuleWithActionOptions); System.out.printf("SubscriptionName: %s, Removing Default Rule and Adding CorrelationFilter%n", correlationFilterSubscription); administrationClient.deleteRule(TOPIC_NAME, correlationFilterSubscription, defaultRuleName); final CreateRuleOptions correlationFilterRuleOptions = new CreateRuleOptions() .setFilter(new CorrelationRuleFilter().setCorrelationId("important").setLabel("Red")); administrationClient.createRule(TOPIC_NAME, correlationFilterSubscription, correlationFilterSubscriptionRule, correlationFilterRuleOptions); administrationClient.listRules(TOPIC_NAME, correlationFilterSubscription) .forEach(ruleProperties -> System.out.printf("GetRules:: SubscriptionName: %s, CorrelationFilter Name: %s, Rule: %s%n", correlationFilterSubscription, ruleProperties.getName(), ruleProperties.getFilter())); sendMessages(); receiveMessages(allMessagesSubscription).block(); receiveMessages(sqlFilterOnlySubscription).block(); receiveMessages(sqlFilterWithActionSubscription).block(); receiveMessages(correlationFilterSubscription).block(); }
class TopicSubscriptionWithRuleOperationsSample { static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); static final String SERVICE_BUS_TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); static final String ALL_MESSAGES_SUBSCRIPTION_NAME = "{Subscription 1 Name}"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_NAME = "{Subscription 2 Name}"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_NAME = "{Subscription 3 Name}"; static final String CORRELATION_FILTER_SUBSCRIPTION_NAME = "{Subscription 4 Name}"; static final String DEFAULT_SUBSCRIPTION_RULE_NAME = "$Default"; static final String SQL_FILTER_ONLY_SUBSCRIPTION_RULE_NAME = "RedSqlRule"; static final String SQL_FILTER_WITH_ACTION_SUBSCRIPTION_RULE_NAME = "BlueSqlRule"; static final String CORRELATION_FILTER_SUBSCRIPTION_RULE_NAME = "ImportantCorrelationRule"; /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ public static void main(String[] args) throws InterruptedException { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} * by topic subscriptions from an Azure Service Bus Topic. * * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * @throws InterruptedException If the program is unable to sleep while waiting for the receive to complete. */ static void receiveMessagesAsync(String subscriptionName) throws InterruptedException { AtomicReference<ServiceBusReceiverAsyncClient> receiverAsyncClient = new AtomicReference<>(); AtomicReference<CountDownLatch> countdownLatch = new AtomicReference<>(); countdownLatch.set(new CountDownLatch(1)); receiverAsyncClient.set(new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .receiver() .topicName(SERVICE_BUS_TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient()); System.out.println("=========================================================================="); System.out.println(String.format("%s :: Receiving Messages From Subscription: %s", OffsetDateTime.now(), subscriptionName)); AtomicLong receiveMessagesCount = new AtomicLong(0L); receiverAsyncClient.get().receiveMessages().parallel().subscribe(receivedMessage -> { receiveMessagesCount.incrementAndGet(); System.out.println(String.format("Color Property = %s, CorrelationId = %s", receivedMessage.getApplicationProperties().get("Color"), receivedMessage.getCorrelationId() == null ? "" : receivedMessage.getCorrelationId())); } ); countdownLatch.get().await(10, TimeUnit.SECONDS); System.out.println(String.format("%s :: Received '%s' Messages From Subscription: %s", OffsetDateTime.now(), receiveMessagesCount.get(), subscriptionName)); System.out.println("=========================================================================="); receiverAsyncClient.get().close(); } /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ static void sendMessagesAsync() { ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .sender() .topicName(SERVICE_BUS_TOPIC_NAME) .buildClient(); List<ServiceBusMessage> messageList = new ArrayList<ServiceBusMessage>(); messageList.add(createServiceBusMessage("Red", null)); messageList.add(createServiceBusMessage("Blue", null)); messageList.add(createServiceBusMessage("Red", "important")); messageList.add(createServiceBusMessage("Blue", "important")); messageList.add(createServiceBusMessage("Red", "notimportant")); messageList.add(createServiceBusMessage("Blue", "notimportant")); messageList.add(createServiceBusMessage("Green", null)); messageList.add(createServiceBusMessage("Green", "important")); messageList.add(createServiceBusMessage("Green", "notimportant")); System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); ServiceBusMessageBatch messageBatch = topicSenderClient.createMessageBatch(); messageList.forEach(message -> { System.out.println(String.format("Sent Message:: Label: %s, CorrelationId: %s", message.getBody().toString(), message.getCorrelationId() == null ? "" : message.getCorrelationId())); messageBatch.tryAddMessage(message); }); topicSenderClient.sendMessages(messageBatch); topicSenderClient.close(); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
class TopicSubscriptionWithRuleOperationsSample { private static final String SERVICEBUS_NAMESPACE_CONNECTION_STRING = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING"); private static final String TOPIC_NAME = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME"); /** * Main method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TopicSubscriptionWithRuleOperationsSample app = new TopicSubscriptionWithRuleOperationsSample(); app.run(); } /** * This method to invoke this demo on how to receive {@link ServiceBusReceivedMessage messages} by topic * subscriptions from an Azure Service Bus Topic. */ /** * Send a {@link ServiceBusMessageBatch} to an Azure Service Bus Topic. */ private static void sendMessages() { List<ServiceBusMessage> messageList = Arrays.asList( createServiceBusMessage("Red", null), createServiceBusMessage("Blue", null), createServiceBusMessage("Red", "important"), createServiceBusMessage("Blue", "important"), createServiceBusMessage("Red", "not_important"), createServiceBusMessage("Blue", "not_important"), createServiceBusMessage("Green", null), createServiceBusMessage("Green", "important"), createServiceBusMessage("Green", "not_important") ); ServiceBusSenderClient topicSenderClient = new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .sender() .topicName(TOPIC_NAME) .buildClient(); try { System.out.println("=========================================================================="); System.out.println("Sending Messages to Topic"); topicSenderClient.sendMessages(messageList); } finally { topicSenderClient.close(); } } /** * Receive {@link ServiceBusReceivedMessage messages} by topic subscriptions from an Azure Service Bus Topic. * * @param subscriptionName Subscription Name. * * @return A Mono that completes when all messages have been received from the subscription. That is, when there is * a period of 5 seconds where no message has been received. */ private static Mono<Void> receiveMessages(String subscriptionName) { System.out.println("=========================================================================="); System.out.printf("%s: Receiving Messages From Subscription: %s%n", OffsetDateTime.now(), subscriptionName); return Mono.using(() -> { return new ServiceBusClientBuilder() .connectionString(SERVICEBUS_NAMESPACE_CONNECTION_STRING) .receiver() .topicName(TOPIC_NAME) .subscriptionName(subscriptionName) .receiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }, receiver -> { return receiver.receiveMessages() .timeout(Duration.ofSeconds(5)) .map(message -> { System.out.printf("Color Property = %s, CorrelationId = %s%n", message.getApplicationProperties().get("Color"), message.getCorrelationId() == null ? "" : message.getCorrelationId()); return message; }) .onErrorResume(TimeoutException.class, error -> { System.out.println("There were no more messages to receive. Error: " + error); return Mono.empty(); }).then(); }, receiver -> { receiver.close(); }); } /** * Create a {@link ServiceBusMessage} for add to a {@link ServiceBusMessageBatch}. */ private static ServiceBusMessage createServiceBusMessage(String label, String correlationId) { ServiceBusMessage message = new ServiceBusMessage(label); message.getApplicationProperties().put("Color", label); if (correlationId != null) { message.setCorrelationId(correlationId); } return message; } }
is this a category that is not avialable in the swagger? or why is it different?
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; }
HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.fromString("Course"));
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; }
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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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() { } }
same question on why the need to create the type...
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; }
HealthcareEntityRelationType.fromString("CourseOfCondition"));
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; }
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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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() { } }
The category is not available in the swagger. So we can have it by extending it.
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; }
HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.fromString("Course"));
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; }
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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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() { } }
same answer in https://github.com/Azure/azure-sdk-for-java/pull/22174#discussion_r652169498
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; }
HealthcareEntityRelationType.fromString("CourseOfCondition"));
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; }
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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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() { } }
ohhh we should push either the service team to add it to the swagger, or you can go ahead and create a PR for their swagger that adds the missing types you found
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; }
HealthcareEntityPropertiesHelper.setCategory(healthcareEntity3, HealthcareEntityCategory.fromString("Course"));
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; }
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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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> 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 String PII_TASK = "entityRecognitionPiiTasks"; static final String ENTITY_TASK = "entityRecognitionTasks"; static final String KEY_PHRASES_TASK = "keyPhraseExtractionTasks"; 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 categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26); CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34); return asList(categorizedEntity2, categorizedEntity3); } /** * Helper method to get the expected Categorized Entities List 2 */ static List<CategorizedEntity> getCategorizedEntitiesList2() { return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10)); } /** * Helper method to get the expected Categorized entity result for PII document input. */ static List<CategorizedEntity> getCategorizedEntitiesForPiiInput() { return asList( new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 0), new CategorizedEntity("employee", EntityCategory.PERSON_TYPE, null, 0.0, 10), new CategorizedEntity("859", EntityCategory.QUANTITY, "Number", 0.0, 28), new CategorizedEntity("98", EntityCategory.QUANTITY, "Number", 0.0, 32), new CategorizedEntity("0987", EntityCategory.QUANTITY, "Number", 0.0, 35), new CategorizedEntity("API", EntityCategory.SKILL, null, 0.0, 61) ); } /** * 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.USSOCIAL_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.ABAROUTING_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.NZSOCIAL_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, 26); LinkedEntity linkedEntity = new LinkedEntity( "Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Seattle", "https: "Wikipedia", "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, 10); LinkedEntity linkedEntity = new LinkedEntity( "Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)), "en", "Microsoft", "https: "Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85"); return asList(linkedEntity); } /** * 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); } /** * 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); } /** * Helper method that get a single-page (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForSinglePage() { return asList( getExpectedHealthcareTaskResult(2, asList(getRecognizeHealthcareEntitiesResult1("0"), getRecognizeHealthcareEntitiesResult2()))); } /** * Helper method that get a multiple-pages (healthcareTaskResult) list. */ static List<AnalyzeHealthcareEntitiesResultCollection> getExpectedHealthcareTaskResultListForMultiplePages(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(getExpectedHealthcareTaskResult(firstPage, healthcareEntitiesResults1)); if (secondPage != 0) { result.add(getExpectedHealthcareTaskResult(secondPage, healthcareEntitiesResults2)); } return result; } /** * Helper method that get the expected HealthcareTaskResult result. * * @param sizePerPage batch size per page. * @param healthcareEntitiesResults a collection of {@link AnalyzeHealthcareEntitiesResult}. */ static AnalyzeHealthcareEntitiesResultCollection getExpectedHealthcareTaskResult(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.", */ /** * 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 RecognizeEntitiesActionResult getExpectedRecognizeEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeEntitiesActionResult recognizeEntitiesActionResult = new RecognizeEntitiesActionResult(); RecognizeEntitiesActionResultPropertiesHelper.setDocumentResults(recognizeEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizeEntitiesActionResult, completeAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizeEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizeEntitiesActionResult, actionError); return recognizeEntitiesActionResult; } static RecognizePiiEntitiesActionResult getExpectedRecognizePiiEntitiesActionResult(boolean isError, OffsetDateTime completedAt, RecognizePiiEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizePiiEntitiesActionResult recognizePiiEntitiesActionResult = new RecognizePiiEntitiesActionResult(); RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentResults(recognizePiiEntitiesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(recognizePiiEntitiesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(recognizePiiEntitiesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(recognizePiiEntitiesActionResult, actionError); return recognizePiiEntitiesActionResult; } static ExtractKeyPhrasesActionResult getExpectedExtractKeyPhrasesActionResult(boolean isError, OffsetDateTime completedAt, ExtractKeyPhrasesResultCollection resultCollection, TextAnalyticsError actionError) { ExtractKeyPhrasesActionResult extractKeyPhrasesActionResult = new ExtractKeyPhrasesActionResult(); ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentResults(extractKeyPhrasesActionResult, resultCollection); TextAnalyticsActionResultPropertiesHelper.setCompletedAt(extractKeyPhrasesActionResult, completedAt); TextAnalyticsActionResultPropertiesHelper.setIsError(extractKeyPhrasesActionResult, isError); TextAnalyticsActionResultPropertiesHelper.setError(extractKeyPhrasesActionResult, actionError); return extractKeyPhrasesActionResult; } static RecognizeLinkedEntitiesActionResult getExpectedRecognizeLinkedEntitiesActionResult(boolean isError, OffsetDateTime completeAt, RecognizeLinkedEntitiesResultCollection resultCollection, TextAnalyticsError actionError) { RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult(); RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentResults(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.setDocumentResults(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<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults, IterableStream<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults, IterableStream<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults, IterableStream<AnalyzeSentimentActionResult> analyzeSentimentActionResults) { final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult(); AnalyzeActionsResultPropertiesHelper.setStatistics(analyzeActionsResult, new TextDocumentBatchStatistics(1, 1, 0, 1)); AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesActionResults(analyzeActionsResult, recognizeEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesActionResults(analyzeActionsResult, recognizePiiEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesActionResults(analyzeActionsResult, extractKeyPhrasesActionResults); AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesActionResults(analyzeActionsResult, recognizeLinkedEntitiesActionResults); AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentActionResults(analyzeActionsResult, analyzeSentimentActionResults); return analyzeActionsResult; } /** * ExtractKeyPhrasesResultCollection 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)); } /** * ExtractKeyPhrasesResultCollection 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)); } /** * 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(getExpectedRecognizePiiEntitiesActionResult( false, TIME_NOW, getRecognizePiiEntitiesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult( false, TIME_NOW, getExtractKeyPhrasesResultCollectionForPagination(startIndex, firstPage), null))), IterableStream.of(Collections.emptyList()), IterableStream.of(Collections.emptyList()) )); startIndex += firstPage; analyzeActionsResults.add(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult( false, TIME_NOW, getRecognizeEntitiesResultCollectionForPagination(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(Collections.emptyList()), 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() { } }
This could take the file length hint
private byte[] getBytes() { return FluxUtil.collectBytesInByteBufferStream(toFluxByteBuffer()) .share() .block(); }
return FluxUtil.collectBytesInByteBufferStream(toFluxByteBuffer())
private byte[] getBytes() { try { return Files.readAllBytes(file); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } }
class FileContent extends BinaryDataContent { private static final ClientLogger LOGGER = new ClientLogger(FileContent.class); private final Path file; private final int chunkSize; private final long length; private final AtomicReference<byte[]> bytes = new AtomicReference<>(); /** * Creates a new instance of {@link FileContent}. * * @param file The {@link Path} content. * @param chunkSize The requested size for each read of the path. * @throws NullPointerException if {@code file} is null. * @throws IllegalArgumentException if {@code chunkSize} is less than or equal to zero. */ public FileContent(Path file, int chunkSize) { Objects.requireNonNull(file, "'file' cannot be null."); if (chunkSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'chunkSize' cannot be less than or equal to 0.")); } this.file = file; this.chunkSize = chunkSize; if (!file.toFile().exists()) { throw LOGGER.logExceptionAsError(new UncheckedIOException( new FileNotFoundException("File does not exist " + file))); } this.length = file.toFile().length(); } @Override public Long getLength() { return this.length; } @Override public String toString() { return new String(toBytes(), StandardCharsets.UTF_8); } @Override public byte[] toBytes() { byte[] data = this.bytes.get(); if (data == null) { bytes.set(getBytes()); data = this.bytes.get(); } return data; } @Override public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) { return serializer.deserialize(toStream(), typeReference); } @Override public InputStream toStream() { try { return new BufferedInputStream(new FileInputStream(file.toFile()), chunkSize); } catch (FileNotFoundException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException("File not found " + file, e)); } } @Override public ByteBuffer toByteBuffer() { try { FileChannel fileChannel = FileChannel.open(file); return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, length); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } @Override public Flux<ByteBuffer> toFluxByteBuffer() { return Flux.using(() -> FileChannel.open(file), channel -> Flux.generate(() -> 0, (count, sink) -> { if (count == length) { sink.complete(); return count; } int readCount = (int) Math.min(chunkSize, length - count); try { sink.next(channel.map(FileChannel.MapMode.READ_ONLY, count, readCount)); } catch (IOException ex) { sink.error(ex); } return count + readCount; }), channel -> { try { channel.close(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(Exceptions.propagate(ex)); } }); } }
class FileContent extends BinaryDataContent { private static final ClientLogger LOGGER = new ClientLogger(FileContent.class); private final Path file; private final int chunkSize; private final long length; private final AtomicReference<byte[]> bytes = new AtomicReference<>(); /** * Creates a new instance of {@link FileContent}. * * @param file The {@link Path} content. * @param chunkSize The requested size for each read of the path. * @throws NullPointerException if {@code file} is null. * @throws IllegalArgumentException if {@code chunkSize} is less than or equal to zero. */ public FileContent(Path file, int chunkSize) { Objects.requireNonNull(file, "'file' cannot be null."); if (chunkSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'chunkSize' cannot be less than or equal to 0.")); } this.file = file; this.chunkSize = chunkSize; if (!file.toFile().exists()) { throw LOGGER.logExceptionAsError(new UncheckedIOException( new FileNotFoundException("File does not exist " + file))); } this.length = file.toFile().length(); } @Override public Long getLength() { return this.length; } @Override public String toString() { return new String(toBytes(), StandardCharsets.UTF_8); } @Override public byte[] toBytes() { byte[] data = this.bytes.get(); if (data == null) { bytes.set(getBytes()); data = this.bytes.get(); } return data; } @Override public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) { return serializer.deserialize(toStream(), typeReference); } @Override public InputStream toStream() { try { return new BufferedInputStream(new FileInputStream(file.toFile()), chunkSize); } catch (FileNotFoundException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException("File not found " + file, e)); } } @Override public ByteBuffer toByteBuffer() { try { FileChannel fileChannel = FileChannel.open(file); return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, length); } catch (IOException exception) { throw LOGGER.logExceptionAsError(new UncheckedIOException(exception)); } } @Override public Flux<ByteBuffer> toFluxByteBuffer() { return Flux.using(() -> FileChannel.open(file), channel -> Flux.generate(() -> 0, (count, sink) -> { if (count == length) { sink.complete(); return count; } int readCount = (int) Math.min(chunkSize, length - count); try { sink.next(channel.map(FileChannel.MapMode.READ_ONLY, count, readCount)); } catch (IOException ex) { sink.error(ex); } return count + readCount; }), channel -> { try { channel.close(); } catch (IOException ex) { throw LOGGER.logExceptionAsError(Exceptions.propagate(ex)); } }); } }
A new pipeline is created if it's not provided in the builder. So, this isn't required.
public void getStatistics() throws URISyntaxException { URI primaryEndpoint = new URI(serviceClient.getServiceEndpoint()); String[] hostParts = primaryEndpoint.getHost().split("\\."); StringJoiner secondaryHostJoiner = new StringJoiner("."); secondaryHostJoiner.add(hostParts[0] + "-secondary"); for (int i = 1; i < hostParts.length; i++) { secondaryHostJoiner.add(hostParts[i]); } String secondaryEndpoint = primaryEndpoint.getScheme() + ": TableServiceAsyncClient secondaryClient = new TableServiceClientBuilder() .endpoint(secondaryEndpoint) .serviceVersion(serviceClient.getServiceVersion()) .pipeline(serviceClient.getHttpPipeline()) .buildAsyncClient(); StepVerifier.create(secondaryClient.getStatistics()) .assertNext(statistics -> { assertNotNull(statistics); assertNotNull(statistics.getGeoReplication()); assertNotNull(statistics.getGeoReplication().getStatus()); assertNotNull(statistics.getGeoReplication().getLastSyncTime()); }) .expectComplete() .verify(); }
.pipeline(serviceClient.getHttpPipeline())
public void getStatistics() throws URISyntaxException { URI primaryEndpoint = new URI(serviceClient.getServiceEndpoint()); String[] hostParts = primaryEndpoint.getHost().split("\\."); StringJoiner secondaryHostJoiner = new StringJoiner("."); secondaryHostJoiner.add(hostParts[0] + "-secondary"); for (int i = 1; i < hostParts.length; i++) { secondaryHostJoiner.add(hostParts[i]); } String secondaryEndpoint = primaryEndpoint.getScheme() + ": TableServiceAsyncClient secondaryClient = new TableServiceClientBuilder() .endpoint(secondaryEndpoint) .serviceVersion(serviceClient.getServiceVersion()) .pipeline(serviceClient.getHttpPipeline()) .buildAsyncClient(); StepVerifier.create(secondaryClient.getStatistics()) .assertNext(statistics -> { assertNotNull(statistics); assertNotNull(statistics.getGeoReplication()); assertNotNull(statistics.getGeoReplication().getStatus()); assertNotNull(statistics.getGeoReplication().getLastSyncTime()); }) .expectComplete() .verify(); }
class TableServiceAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableServiceAsyncClient serviceClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableServiceClientBuilder builder = new TableServiceClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } serviceClient = builder.buildAsyncClient(); } @Test void serviceCreateTableAsync() { String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.createTable(tableName)) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void serviceCreateTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; StepVerifier.create(serviceClient.createTableWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceCreateTableFailsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTable(tableName)) .expectErrorMatches(e -> e instanceof TableServiceException && ((TableServiceException) e).getResponse().getStatusCode() == 409) .verify(); } @Test void serviceCreateTableIfNotExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.createTableIfNotExists(tableName)) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsSucceedsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTableIfNotExists(tableName)) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsWithResponseSucceedsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 409; serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceDeleteTableAsync() { final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.deleteTable(tableName)) .expectComplete() .verify(); } @Test void serviceDeleteNonExistingTableAsync() { final String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.deleteTable(tableName)) .expectComplete() .verify(); } @Test void serviceDeleteTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; serviceClient.createTable(tableName).block(); StepVerifier.create(serviceClient.deleteTableWithResponse(tableName)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void serviceDeleteNonExistingTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 404; StepVerifier.create(serviceClient.deleteTableWithResponse(tableName)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test @Tag("ListTables") void serviceListTablesAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); StepVerifier.create(serviceClient.listTables()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListTables") void serviceListTablesWithFilterAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'"); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); StepVerifier.create(serviceClient.listTables(options)) .assertNext(table -> { assertEquals(tableName, table.getName()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListTables") void serviceListTablesWithTopAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); final String tableName3 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setTop(2); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); serviceClient.createTable(tableName3).block(TIMEOUT); StepVerifier.create(serviceClient.listTables(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void serviceGetTableClientAsync() { final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); TableAsyncClient tableClient = serviceClient.getTableClient(tableName); TableAsyncClientTest.getEntityWithResponseAsyncImpl(tableClient, this.testResourceNamer); } @Test @Tag("SAS") public void generateAccountSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("r"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test @Tag("SAS") public void generateAccountSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("rdau"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); 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 TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=rdau" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Tag("SAS") public void canUseSasTokenToCreateValidTableClient() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("a"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(serviceClient.getServiceEndpoint()) .sasToken(sas) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(HttpClient.createDefault()); 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 setGetProperties() { TableServiceRetentionPolicy retentionPolicy = new TableServiceRetentionPolicy() .setDaysToRetain(5) .setEnabled(true); TableServiceLogging logging = new TableServiceLogging() .setReadLogged(true) .setAnalyticsVersion("1.0") .setRetentionPolicy(retentionPolicy); List<TableServiceCorsRule> corsRules = new ArrayList<>(); corsRules.add(new TableServiceCorsRule() .setAllowedMethods("GET,PUT,HEAD") .setAllowedOrigins("*") .setAllowedHeaders("x-ms-version") .setExposedHeaders("x-ms-client-request-id") .setMaxAgeInSeconds(10)); TableServiceMetrics hourMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceMetrics minuteMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceProperties properties = new TableServiceProperties() .setLogging(logging) .setCorsRules(corsRules) .setMinuteMetrics(minuteMetrics) .setHourMetrics(hourMetrics); StepVerifier.create(serviceClient.setProperties(properties)) .expectComplete() .verify(); StepVerifier.create(serviceClient.getProperties()) .assertNext(retrievedProperties -> { assertNotNull(retrievedProperties); assertNotNull(retrievedProperties.getCorsRules()); assertEquals(1, retrievedProperties.getCorsRules().size()); assertNotNull(retrievedProperties.getCorsRules().get(0)); assertNotNull(retrievedProperties.getHourMetrics()); assertNotNull(retrievedProperties.getMinuteMetrics()); assertNotNull(retrievedProperties.getLogging()); }) .expectComplete() .verify(); } @Test }
class TableServiceAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private TableServiceAsyncClient serviceClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableServiceClientBuilder builder = new TableServiceClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } serviceClient = builder.buildAsyncClient(); } @Test void serviceCreateTableAsync() { String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.createTable(tableName)) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void serviceCreateTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; StepVerifier.create(serviceClient.createTableWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceCreateTableFailsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTable(tableName)) .expectErrorMatches(e -> e instanceof TableServiceException && ((TableServiceException) e).getResponse().getStatusCode() == 409) .verify(); } @Test void serviceCreateTableIfNotExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.createTableIfNotExists(tableName)) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsSucceedsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTableIfNotExists(tableName)) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsWithResponseSucceedsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 409; serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceDeleteTableAsync() { final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.deleteTable(tableName)) .expectComplete() .verify(); } @Test void serviceDeleteNonExistingTableAsync() { final String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.deleteTable(tableName)) .expectComplete() .verify(); } @Test void serviceDeleteTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; serviceClient.createTable(tableName).block(); StepVerifier.create(serviceClient.deleteTableWithResponse(tableName)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void serviceDeleteNonExistingTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 404; StepVerifier.create(serviceClient.deleteTableWithResponse(tableName)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void serviceListTablesAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); StepVerifier.create(serviceClient.listTables()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void serviceListTablesWithFilterAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'"); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); StepVerifier.create(serviceClient.listTables(options)) .assertNext(table -> { assertEquals(tableName, table.getName()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void serviceListTablesWithTopAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); final String tableName3 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setTop(2); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); serviceClient.createTable(tableName3).block(TIMEOUT); StepVerifier.create(serviceClient.listTables(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void serviceGetTableClientAsync() { final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); TableAsyncClient tableClient = serviceClient.getTableClient(tableName); TableAsyncClientTest.getEntityWithResponseAsyncImpl(tableClient, this.testResourceNamer); } @Test public void generateAccountSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("r"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateAccountSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("rdau"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); 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 TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=rdau" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("a"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(serviceClient.getServiceEndpoint()) .sasToken(sas) .tableName(tableName); 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 setGetProperties() { TableServiceRetentionPolicy retentionPolicy = new TableServiceRetentionPolicy() .setDaysToRetain(5) .setEnabled(true); TableServiceLogging logging = new TableServiceLogging() .setReadLogged(true) .setAnalyticsVersion("1.0") .setRetentionPolicy(retentionPolicy); List<TableServiceCorsRule> corsRules = new ArrayList<>(); corsRules.add(new TableServiceCorsRule() .setAllowedMethods("GET,PUT,HEAD") .setAllowedOrigins("*") .setAllowedHeaders("x-ms-version") .setExposedHeaders("x-ms-client-request-id") .setMaxAgeInSeconds(10)); TableServiceMetrics hourMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceMetrics minuteMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceProperties properties = new TableServiceProperties() .setLogging(logging) .setCorsRules(corsRules) .setMinuteMetrics(minuteMetrics) .setHourMetrics(hourMetrics); StepVerifier.create(serviceClient.setProperties(properties)) .expectComplete() .verify(); StepVerifier.create(serviceClient.getProperties()) .assertNext(retrievedProperties -> { assertNotNull(retrievedProperties); assertNotNull(retrievedProperties.getCorsRules()); assertEquals(1, retrievedProperties.getCorsRules().size()); assertNotNull(retrievedProperties.getCorsRules().get(0)); assertNotNull(retrievedProperties.getHourMetrics()); assertNotNull(retrievedProperties.getMinuteMetrics()); assertNotNull(retrievedProperties.getLogging()); }) .expectComplete() .verify(); } @Test }
I thought it would be better to use the same pipeline from the first client to use the same configuration. I think can write things better to make it so that we can get those settings in the test class itself.
public void getStatistics() throws URISyntaxException { URI primaryEndpoint = new URI(serviceClient.getServiceEndpoint()); String[] hostParts = primaryEndpoint.getHost().split("\\."); StringJoiner secondaryHostJoiner = new StringJoiner("."); secondaryHostJoiner.add(hostParts[0] + "-secondary"); for (int i = 1; i < hostParts.length; i++) { secondaryHostJoiner.add(hostParts[i]); } String secondaryEndpoint = primaryEndpoint.getScheme() + ": TableServiceAsyncClient secondaryClient = new TableServiceClientBuilder() .endpoint(secondaryEndpoint) .serviceVersion(serviceClient.getServiceVersion()) .pipeline(serviceClient.getHttpPipeline()) .buildAsyncClient(); StepVerifier.create(secondaryClient.getStatistics()) .assertNext(statistics -> { assertNotNull(statistics); assertNotNull(statistics.getGeoReplication()); assertNotNull(statistics.getGeoReplication().getStatus()); assertNotNull(statistics.getGeoReplication().getLastSyncTime()); }) .expectComplete() .verify(); }
.pipeline(serviceClient.getHttpPipeline())
public void getStatistics() throws URISyntaxException { URI primaryEndpoint = new URI(serviceClient.getServiceEndpoint()); String[] hostParts = primaryEndpoint.getHost().split("\\."); StringJoiner secondaryHostJoiner = new StringJoiner("."); secondaryHostJoiner.add(hostParts[0] + "-secondary"); for (int i = 1; i < hostParts.length; i++) { secondaryHostJoiner.add(hostParts[i]); } String secondaryEndpoint = primaryEndpoint.getScheme() + ": TableServiceAsyncClient secondaryClient = new TableServiceClientBuilder() .endpoint(secondaryEndpoint) .serviceVersion(serviceClient.getServiceVersion()) .pipeline(serviceClient.getHttpPipeline()) .buildAsyncClient(); StepVerifier.create(secondaryClient.getStatistics()) .assertNext(statistics -> { assertNotNull(statistics); assertNotNull(statistics.getGeoReplication()); assertNotNull(statistics.getGeoReplication().getStatus()); assertNotNull(statistics.getGeoReplication().getLastSyncTime()); }) .expectComplete() .verify(); }
class TableServiceAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableServiceAsyncClient serviceClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableServiceClientBuilder builder = new TableServiceClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } serviceClient = builder.buildAsyncClient(); } @Test void serviceCreateTableAsync() { String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.createTable(tableName)) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void serviceCreateTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; StepVerifier.create(serviceClient.createTableWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceCreateTableFailsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTable(tableName)) .expectErrorMatches(e -> e instanceof TableServiceException && ((TableServiceException) e).getResponse().getStatusCode() == 409) .verify(); } @Test void serviceCreateTableIfNotExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.createTableIfNotExists(tableName)) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsSucceedsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTableIfNotExists(tableName)) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsWithResponseSucceedsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 409; serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceDeleteTableAsync() { final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.deleteTable(tableName)) .expectComplete() .verify(); } @Test void serviceDeleteNonExistingTableAsync() { final String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.deleteTable(tableName)) .expectComplete() .verify(); } @Test void serviceDeleteTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; serviceClient.createTable(tableName).block(); StepVerifier.create(serviceClient.deleteTableWithResponse(tableName)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void serviceDeleteNonExistingTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 404; StepVerifier.create(serviceClient.deleteTableWithResponse(tableName)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test @Tag("ListTables") void serviceListTablesAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); StepVerifier.create(serviceClient.listTables()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListTables") void serviceListTablesWithFilterAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'"); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); StepVerifier.create(serviceClient.listTables(options)) .assertNext(table -> { assertEquals(tableName, table.getName()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListTables") void serviceListTablesWithTopAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); final String tableName3 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setTop(2); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); serviceClient.createTable(tableName3).block(TIMEOUT); StepVerifier.create(serviceClient.listTables(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void serviceGetTableClientAsync() { final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); TableAsyncClient tableClient = serviceClient.getTableClient(tableName); TableAsyncClientTest.getEntityWithResponseAsyncImpl(tableClient, this.testResourceNamer); } @Test @Tag("SAS") public void generateAccountSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("r"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test @Tag("SAS") public void generateAccountSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("rdau"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); 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 TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=rdau" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Tag("SAS") public void canUseSasTokenToCreateValidTableClient() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("a"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(serviceClient.getServiceEndpoint()) .sasToken(sas) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(HttpClient.createDefault()); 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 setGetProperties() { TableServiceRetentionPolicy retentionPolicy = new TableServiceRetentionPolicy() .setDaysToRetain(5) .setEnabled(true); TableServiceLogging logging = new TableServiceLogging() .setReadLogged(true) .setAnalyticsVersion("1.0") .setRetentionPolicy(retentionPolicy); List<TableServiceCorsRule> corsRules = new ArrayList<>(); corsRules.add(new TableServiceCorsRule() .setAllowedMethods("GET,PUT,HEAD") .setAllowedOrigins("*") .setAllowedHeaders("x-ms-version") .setExposedHeaders("x-ms-client-request-id") .setMaxAgeInSeconds(10)); TableServiceMetrics hourMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceMetrics minuteMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceProperties properties = new TableServiceProperties() .setLogging(logging) .setCorsRules(corsRules) .setMinuteMetrics(minuteMetrics) .setHourMetrics(hourMetrics); StepVerifier.create(serviceClient.setProperties(properties)) .expectComplete() .verify(); StepVerifier.create(serviceClient.getProperties()) .assertNext(retrievedProperties -> { assertNotNull(retrievedProperties); assertNotNull(retrievedProperties.getCorsRules()); assertEquals(1, retrievedProperties.getCorsRules().size()); assertNotNull(retrievedProperties.getCorsRules().get(0)); assertNotNull(retrievedProperties.getHourMetrics()); assertNotNull(retrievedProperties.getMinuteMetrics()); assertNotNull(retrievedProperties.getLogging()); }) .expectComplete() .verify(); } @Test }
class TableServiceAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private TableServiceAsyncClient serviceClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableServiceClientBuilder builder = new TableServiceClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } serviceClient = builder.buildAsyncClient(); } @Test void serviceCreateTableAsync() { String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.createTable(tableName)) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void serviceCreateTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; StepVerifier.create(serviceClient.createTableWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceCreateTableFailsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTable(tableName)) .expectErrorMatches(e -> e instanceof TableServiceException && ((TableServiceException) e).getResponse().getStatusCode() == 409) .verify(); } @Test void serviceCreateTableIfNotExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.createTableIfNotExists(tableName)) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsSucceedsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTableIfNotExists(tableName)) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceCreateTableIfNotExistsWithResponseSucceedsIfExistsAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 409; serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); assertNull(response.getValue()); }) .expectComplete() .verify(); } @Test void serviceDeleteTableAsync() { final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); StepVerifier.create(serviceClient.deleteTable(tableName)) .expectComplete() .verify(); } @Test void serviceDeleteNonExistingTableAsync() { final String tableName = testResourceNamer.randomName("test", 20); StepVerifier.create(serviceClient.deleteTable(tableName)) .expectComplete() .verify(); } @Test void serviceDeleteTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; serviceClient.createTable(tableName).block(); StepVerifier.create(serviceClient.deleteTableWithResponse(tableName)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void serviceDeleteNonExistingTableWithResponseAsync() { String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 404; StepVerifier.create(serviceClient.deleteTableWithResponse(tableName)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test void serviceListTablesAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); StepVerifier.create(serviceClient.listTables()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void serviceListTablesWithFilterAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'"); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); StepVerifier.create(serviceClient.listTables(options)) .assertNext(table -> { assertEquals(tableName, table.getName()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void serviceListTablesWithTopAsync() { final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); final String tableName3 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setTop(2); serviceClient.createTable(tableName).block(TIMEOUT); serviceClient.createTable(tableName2).block(TIMEOUT); serviceClient.createTable(tableName3).block(TIMEOUT); StepVerifier.create(serviceClient.listTables(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test void serviceGetTableClientAsync() { final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); TableAsyncClient tableClient = serviceClient.getTableClient(tableName); TableAsyncClientTest.getEntityWithResponseAsyncImpl(tableClient, this.testResourceNamer); } @Test public void generateAccountSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("r"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateAccountSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("rdau"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); 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 TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=rdau" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("a"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName).block(TIMEOUT); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(serviceClient.getServiceEndpoint()) .sasToken(sas) .tableName(tableName); 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 setGetProperties() { TableServiceRetentionPolicy retentionPolicy = new TableServiceRetentionPolicy() .setDaysToRetain(5) .setEnabled(true); TableServiceLogging logging = new TableServiceLogging() .setReadLogged(true) .setAnalyticsVersion("1.0") .setRetentionPolicy(retentionPolicy); List<TableServiceCorsRule> corsRules = new ArrayList<>(); corsRules.add(new TableServiceCorsRule() .setAllowedMethods("GET,PUT,HEAD") .setAllowedOrigins("*") .setAllowedHeaders("x-ms-version") .setExposedHeaders("x-ms-client-request-id") .setMaxAgeInSeconds(10)); TableServiceMetrics hourMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceMetrics minuteMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceProperties properties = new TableServiceProperties() .setLogging(logging) .setCorsRules(corsRules) .setMinuteMetrics(minuteMetrics) .setHourMetrics(hourMetrics); StepVerifier.create(serviceClient.setProperties(properties)) .expectComplete() .verify(); StepVerifier.create(serviceClient.getProperties()) .assertNext(retrievedProperties -> { assertNotNull(retrievedProperties); assertNotNull(retrievedProperties.getCorsRules()); assertEquals(1, retrievedProperties.getCorsRules().size()); assertNotNull(retrievedProperties.getCorsRules().get(0)); assertNotNull(retrievedProperties.getHourMetrics()); assertNotNull(retrievedProperties.getMinuteMetrics()); assertNotNull(retrievedProperties.getLogging()); }) .expectComplete() .verify(); } @Test }
nit: `%n` not `\n`
public static void main(String[] args) { TableClient tableClient = new TableClientBuilder() .tableName("OfficeSupplies") .connectionString("<your-connection-string>") .buildClient(); List<TableTransactionAction> transactionActions = new ArrayList<>(); String partitionKey = "markers4"; String firstEntityRowKey = "m001"; String secondEntityRowKey = "m002"; TableEntity firstEntity = new TableEntity(partitionKey, firstEntityRowKey) .addProperty("Brand", "Crayola") .addProperty("Color", "Red"); transactionActions.add(new TableTransactionAction(TableTransactionActionType.CREATE, firstEntity)); System.out.printf("Added create action for entity with partition key: %s, and row key: %s\n", partitionKey, firstEntityRowKey); TableEntity secondEntity = new TableEntity(partitionKey, secondEntityRowKey) .addProperty("Brand", "Crayola") .addProperty("Color", "Blue"); transactionActions.add(new TableTransactionAction(TableTransactionActionType.CREATE, secondEntity)); System.out.printf("Added create action for entity with partition key: %s, and row key: %s\n", partitionKey, secondEntityRowKey); String rowKeyForUpdate = "m003"; TableEntity entityToUpdate = new TableEntity(partitionKey, rowKeyForUpdate) .addProperty("Brand", "Crayola") .addProperty("Color", "Blue"); transactionActions.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, entityToUpdate)); System.out.printf("Added update action for entity with partition key: %s, and row key: %s\n", partitionKey, rowKeyForUpdate); String rowKeyForDelete = "m004"; TableEntity entityToDelete = new TableEntity(partitionKey, rowKeyForDelete) .addProperty("Brand", "Crayola") .addProperty("Color", "Blue"); transactionActions.add(new TableTransactionAction(TableTransactionActionType.DELETE, entityToDelete)); System.out.printf("Added delete action for entity with partition key: %s, and row key: %s\n", partitionKey, rowKeyForDelete); TableTransactionResult tableTransactionResult = tableClient.submitTransaction(transactionActions); }
System.out.printf("Added create action for entity with partition key: %s, and row key: %s\n", partitionKey,
public static void main(String[] args) { TableClient tableClient = new TableClientBuilder() .tableName("OfficeSupplies") .connectionString("<your-connection-string>") .buildClient(); List<TableTransactionAction> transactionActions = new ArrayList<>(); String partitionKey = "markers4"; String firstEntityRowKey = "m001"; String secondEntityRowKey = "m002"; TableEntity firstEntity = new TableEntity(partitionKey, firstEntityRowKey) .addProperty("Brand", "Crayola") .addProperty("Color", "Red"); transactionActions.add(new TableTransactionAction(TableTransactionActionType.CREATE, firstEntity)); System.out.printf("Added create action for entity with partition key: %s, and row key: %s%n", partitionKey, firstEntityRowKey); TableEntity secondEntity = new TableEntity(partitionKey, secondEntityRowKey) .addProperty("Brand", "Crayola") .addProperty("Color", "Blue"); transactionActions.add(new TableTransactionAction(TableTransactionActionType.CREATE, secondEntity)); System.out.printf("Added create action for entity with partition key: %s, and row key: %s%n", partitionKey, secondEntityRowKey); String rowKeyForUpdate = "m003"; TableEntity entityToUpdate = new TableEntity(partitionKey, rowKeyForUpdate) .addProperty("Brand", "Crayola") .addProperty("Color", "Blue"); transactionActions.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, entityToUpdate)); System.out.printf("Added update action for entity with partition key: %s, and row key: %s%n", partitionKey, rowKeyForUpdate); String rowKeyForDelete = "m004"; TableEntity entityToDelete = new TableEntity(partitionKey, rowKeyForDelete) .addProperty("Brand", "Crayola") .addProperty("Color", "Blue"); transactionActions.add(new TableTransactionAction(TableTransactionActionType.DELETE, entityToDelete)); System.out.printf("Added delete action for entity with partition key: %s, and row key: %s%n", partitionKey, rowKeyForDelete); TableTransactionResult tableTransactionResult = tableClient.submitTransaction(transactionActions); }
class TransactionalBatchOperation { /** * Authenticates with the service and shows how to create and submit a batch of operations. * * @param args Unused. Arguments to the program. */ }
class TransactionalBatchOperation { /** * Authenticates with the service and shows how to create and submit a batch of operations. * * @param args Unused. Arguments to the program. */ }
Should use a static for `HttpClient`, right now this is creating a new `HttpClient` per test which is a costly operation. This doesn't need to be a change in this PR.
protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); 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(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildClient(); tableClient.createTable(); }
builder.httpClient(HttpClient.createDefault());
protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildClient(); tableClient.createTable(); }
class TableClientTest extends TestBase { private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @Override @Test void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.buildClient(); assertNotNull(tableClient2.createTable()); } @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.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 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; } fail(); } @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) { 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() { 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(HttpClient.createDefault()); 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() { 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() { 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 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 @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 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; } fail(); } @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) { 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() { 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() { 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() { 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()); } } }
Any reason for this custom retry policy?
protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); 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(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildClient(); tableClient.createTable(); }
builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500),
protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildClient(); tableClient.createTable(); }
class TableClientTest extends TestBase { private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @Override @Test void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.buildClient(); assertNotNull(tableClient2.createTable()); } @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.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 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; } fail(); } @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) { 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() { 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(HttpClient.createDefault()); 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() { 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() { 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 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 @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 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; } fail(); } @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) { 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() { 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() { 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() { 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()); } } }
This logic seems very duplicative, could this be made into a separate method
void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.buildClient(); assertNotNull(tableClient2.createTable()); }
Duration.ofSeconds(100))));
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()); }
class TableClientTest extends TestBase { private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); 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(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildClient(); tableClient.createTable(); } @Test @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.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 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; } fail(); } @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) { 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() { 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(HttpClient.createDefault()); 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() { 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() { 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 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 @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 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; } fail(); } @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) { 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() { 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() { 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() { 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()); } } }
Not really that I know of, I can look into it a bit.
protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); 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(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildClient(); tableClient.createTable(); }
builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500),
protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildClient(); tableClient.createTable(); }
class TableClientTest extends TestBase { private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @Override @Test void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.buildClient(); assertNotNull(tableClient2.createTable()); } @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.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 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; } fail(); } @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) { 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() { 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(HttpClient.createDefault()); 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() { 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() { 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 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 @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 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; } fail(); } @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) { 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() { 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() { 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() { 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()); } } }
I think it's there just to be super safe in live tests, but I don't thinks it's necessarily required. I'll get rid of it for now.
protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); 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(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildClient(); tableClient.createTable(); }
builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500),
protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildClient(); tableClient.createTable(); }
class TableClientTest extends TestBase { private TableClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @Override @Test void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.buildClient(); assertNotNull(tableClient2.createTable()); } @Test void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableClient tableClient2 = builder.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 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; } fail(); } @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) { 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() { 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(HttpClient.createDefault()); 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() { 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() { 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 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 @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 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; } fail(); } @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) { 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() { 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() { 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() { 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()); } } }
shouldn't this be warning, here and else where? do we expect these failure to happen frequently?
private Flux<FeedResponse<T>> byPage(CosmosPagedFluxOptions pagedFluxOptions, Context context) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); AtomicReference<Instant> startTime = new AtomicReference<>(); return this.optionsFluxFunction.apply(pagedFluxOptions).doOnSubscribe(ignoredValue -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { parentContext.set(pagedFluxOptions.getTracerProvider().startSpan(pagedFluxOptions.getTracerSpanName(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getServiceEndpoint(), context)); } startTime.set(Instant.now()); }).doOnComplete(() -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.complete(), HttpConstants.StatusCodes.OK); } }).doOnError(throwable -> { if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient())) && throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) throwable; if (pagedFluxOptions.getTracerProvider().isEnabled()) { ((Span) parentContext.get().getData(PARENT_SPAN_KEY).get()).makeCurrent(); try { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), cosmosException.getDiagnostics(), parentContext.get()); } catch (JsonProcessingException ex) { LOGGER.debug("Error while serializing diagnostics for tracer", ex); } } fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), 0, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) cosmosException.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); } if (pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.error(throwable), TracerProvider.ERROR_CODE); } startTime.set(Instant.now()); }).doOnNext(feedResponse -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { ((Span) parentContext.get().getData(PARENT_SPAN_KEY).get()).makeCurrent(); try { Duration threshold = pagedFluxOptions.getThresholdForDiagnosticsOnTracer(); if (threshold == null) { threshold = TracerProvider.QUERY_THRESHOLD_FOR_DIAGNOSTICS; } if (Duration.between(startTime.get(), Instant.now()).compareTo(threshold) > 0) { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), feedResponse.getCosmosDiagnostics(), parentContext.get()); } } catch (JsonProcessingException ex) { LOGGER.debug("Error while serializing diagnostics for tracer", ex); } } if (feedResponseConsumer != null) { feedResponseConsumer.accept(feedResponse); } if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient()))) { fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), HttpConstants.StatusCodes.OK, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) feedResponse.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); startTime.set(Instant.now()); } }); }
LOGGER.debug("Error while serializing diagnostics for tracer", ex);
then call it with each feedResponse if (feedResponseConsumer != null) { feedResponseConsumer.accept(feedResponse); }
class CosmosPagedFlux<T> extends ContinuablePagedFlux<String, T, FeedResponse<T>> { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosPagedFlux.class); private final Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction; private final Consumer<FeedResponse<T>> feedResponseConsumer; private CosmosDiagnosticsAccessor cosmosDiagnosticsAccessor; CosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction) { this.optionsFluxFunction = optionsFluxFunction; this.feedResponseConsumer = null; this.cosmosDiagnosticsAccessor = CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); } CosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction, Consumer<FeedResponse<T>> feedResponseConsumer) { this.optionsFluxFunction = optionsFluxFunction; this.feedResponseConsumer = feedResponseConsumer; this.cosmosDiagnosticsAccessor = CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); } /** * Handle for invoking "side-effects" on each FeedResponse returned by CosmosPagedFlux * * @param newFeedResponseConsumer handler * @return CosmosPagedFlux instance with attached handler */ public CosmosPagedFlux<T> handle(Consumer<FeedResponse<T>> newFeedResponseConsumer) { if (this.feedResponseConsumer != null) { return new CosmosPagedFlux<T>( this.optionsFluxFunction, this.feedResponseConsumer.andThen(newFeedResponseConsumer)); } else { return new CosmosPagedFlux<T>(this.optionsFluxFunction, newFeedResponseConsumer); } } @Override public Flux<FeedResponse<T>> byPage() { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(String continuationToken) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setRequestContinuation(continuationToken); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(int preferredPageSize) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setMaxItemCount(preferredPageSize); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(String continuationToken, int preferredPageSize) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setRequestContinuation(continuationToken); cosmosPagedFluxOptions.setMaxItemCount(preferredPageSize); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } /** * Subscribe to consume all items of type {@code T} in the sequence respectively. This is recommended for most * common scenarios. This will seamlessly fetch next page when required and provide with a {@link Flux} of items. * * @param coreSubscriber The subscriber for this {@link CosmosPagedFlux} */ @Override public void subscribe(CoreSubscriber<? super T> coreSubscriber) { Flux<FeedResponse<T>> pagedResponse = this.byPage(); pagedResponse.flatMap(tFeedResponse -> { IterableStream<T> elements = tFeedResponse.getElements(); if (elements == null) { return Flux.empty(); } return Flux.fromIterable(elements); }).subscribe(coreSubscriber); } private Flux<FeedResponse<T>> byPage(CosmosPagedFluxOptions pagedFluxOptions, Context context) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); AtomicReference<Instant> startTime = new AtomicReference<>(); return this.optionsFluxFunction.apply(pagedFluxOptions).doOnSubscribe(ignoredValue -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { parentContext.set(pagedFluxOptions.getTracerProvider().startSpan(pagedFluxOptions.getTracerSpanName(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getServiceEndpoint(), context)); } startTime.set(Instant.now()); }).doOnComplete(() -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.complete(), HttpConstants.StatusCodes.OK); } }).doOnError(throwable -> { if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient())) && throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) throwable; if (pagedFluxOptions.getTracerProvider().isEnabled()) { ((Span) parentContext.get().getData(PARENT_SPAN_KEY).get()).makeCurrent(); try { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), cosmosException.getDiagnostics(), parentContext.get()); } catch (JsonProcessingException ex) { LOGGER.debug("Error while serializing diagnostics for tracer", ex); } } fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), 0, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) cosmosException.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); } if (pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.error(throwable), TracerProvider.ERROR_CODE); } startTime.set(Instant.now()); }).doOnNext(feedResponse -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { ((Span) parentContext.get().getData(PARENT_SPAN_KEY).get()).makeCurrent(); try { Duration threshold = pagedFluxOptions.getThresholdForDiagnosticsOnTracer(); if (threshold == null) { threshold = TracerProvider.QUERY_THRESHOLD_FOR_DIAGNOSTICS; } if (Duration.between(startTime.get(), Instant.now()).compareTo(threshold) > 0) { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), feedResponse.getCosmosDiagnostics(), parentContext.get()); } } catch (JsonProcessingException ex) { LOGGER.debug("Error while serializing diagnostics for tracer", ex); } } if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient()))) { fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), HttpConstants.StatusCodes.OK, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) feedResponse.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); startTime.set(Instant.now()); } }); } private void fillClientTelemetry(CosmosAsyncClient cosmosAsyncClient, int statusCode, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, float requestCharge, Duration latency) { ClientTelemetry telemetry = BridgeInternal.getContextClient(cosmosAsyncClient).getClientTelemetry(); ReportPayload reportPayloadLatency = createReportPayload(cosmosAsyncClient, statusCode, containerId, databaseId , operationType, resourceType, consistencyLevel, ClientTelemetry.REQUEST_LATENCY_NAME, ClientTelemetry.REQUEST_LATENCY_UNIT); ConcurrentDoubleHistogram latencyHistogram = telemetry.getClientTelemetryInfo().getOperationInfoMap().get(reportPayloadLatency); if (latencyHistogram != null) { ClientTelemetry.recordValue(latencyHistogram, latency.toNanos() / 1000); } else { if (statusCode == HttpConstants.StatusCodes.OK) { latencyHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_LATENCY_MAX_MICRO_SEC, ClientTelemetry.REQUEST_LATENCY_SUCCESS_PRECISION); } else { latencyHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_LATENCY_MAX_MICRO_SEC, ClientTelemetry.REQUEST_LATENCY_FAILURE_PRECISION); } latencyHistogram.setAutoResize(true); ClientTelemetry.recordValue(latencyHistogram, latency.toNanos() / 1000); telemetry.getClientTelemetryInfo().getOperationInfoMap().put(reportPayloadLatency, latencyHistogram); } ReportPayload reportPayloadRequestCharge = createReportPayload(cosmosAsyncClient, statusCode, containerId, databaseId , operationType, resourceType, consistencyLevel, ClientTelemetry.REQUEST_CHARGE_NAME, ClientTelemetry.REQUEST_CHARGE_UNIT); ConcurrentDoubleHistogram requestChargeHistogram = telemetry.getClientTelemetryInfo().getOperationInfoMap().get(reportPayloadRequestCharge); if (requestChargeHistogram != null) { ClientTelemetry.recordValue(requestChargeHistogram, requestCharge); } else { requestChargeHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_CHARGE_MAX, ClientTelemetry.REQUEST_CHARGE_PRECISION); requestChargeHistogram.setAutoResize(true); ClientTelemetry.recordValue(requestChargeHistogram, requestCharge); telemetry.getClientTelemetryInfo().getOperationInfoMap().put(reportPayloadRequestCharge, requestChargeHistogram); } } private ReportPayload createReportPayload(CosmosAsyncClient cosmosAsyncClient, int statusCode, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, String metricsName, String unitName) { ReportPayload reportPayload = new ReportPayload(metricsName, unitName); reportPayload.setConsistency(consistencyLevel == null ? BridgeInternal.getContextClient(cosmosAsyncClient).getConsistencyLevel() : consistencyLevel); reportPayload.setDatabaseName(databaseId); reportPayload.setContainerName(containerId); reportPayload.setOperation(operationType); reportPayload.setResource(resourceType); reportPayload.setStatusCode(statusCode); return reportPayload; } private void addDiagnosticsOnTracerEvent(TracerProvider tracerProvider, CosmosDiagnostics cosmosDiagnostics, Context parentContext) throws JsonProcessingException { if (cosmosDiagnostics == null) { return; } Map<String, Object> attributes = new HashMap<>(); QueryInfo.QueryPlanDiagnosticsContext queryPlanDiagnosticsContext = cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics) != null ? cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics).getQueryPlanDiagnosticsContext() : null; if (queryPlanDiagnosticsContext != null) { attributes.put("JSON", Utils.getSimpleObjectMapper().writeValueAsString(queryPlanDiagnosticsContext)); tracerProvider.addEvent("Query Plan Statistics", attributes, OffsetDateTime.ofInstant(queryPlanDiagnosticsContext.getStartTimeUTC(), ZoneOffset.UTC)); } FeedResponseDiagnostics feedResponseDiagnostics = cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics); if (feedResponseDiagnostics != null && feedResponseDiagnostics.getQueryMetricsMap() != null && feedResponseDiagnostics.getQueryMetricsMap().size() > 0) { for(Map.Entry<String, QueryMetrics> entry : feedResponseDiagnostics.getQueryMetricsMap().entrySet()) { attributes = new HashMap<>(); attributes.put("Query Metrics", entry.getValue().toString()); tracerProvider.addEvent("Query Metrics for PKRange " + entry.getKey(), attributes, OffsetDateTime.now()); } } int queryDiagnosticsCounter = 1; for (ClientSideRequestStatistics clientSideRequestStatistics : BridgeInternal.getClientSideRequestStatisticsList(cosmosDiagnostics)) { attributes = new HashMap<>(); int counter = 1; for (ClientSideRequestStatistics.StoreResponseStatistics statistics : clientSideRequestStatistics.getResponseStatisticsList()) { attributes.put("StoreResponse" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(statistics)); } counter = 1; for (ClientSideRequestStatistics.StoreResponseStatistics statistics : ClientSideRequestStatistics.getCappedSupplementalResponseStatisticsList(clientSideRequestStatistics.getSupplementalResponseStatisticsList())) { attributes.put("Supplemental StoreResponse" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(statistics)); } if (clientSideRequestStatistics.getRetryContext().getRetryStartTime() != null) { attributes.put("Retry Context", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getRetryContext())); } counter = 1; for (ClientSideRequestStatistics.AddressResolutionStatistics addressResolutionStatistics : clientSideRequestStatistics.getAddressResolutionStatistics().values()) { attributes.put("AddressResolutionStatistics" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(addressResolutionStatistics)); } if (clientSideRequestStatistics.getSerializationDiagnosticsContext().serializationDiagnosticsList != null) { counter = 1; for (SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics : clientSideRequestStatistics.getSerializationDiagnosticsContext().serializationDiagnosticsList) { attributes = new HashMap<>(); attributes.put("SerializationDiagnostics" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(serializationDiagnostics)); } } if(clientSideRequestStatistics.getGatewayStatistics() != null) { attributes.put("GatewayStatistics", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getGatewayStatistics())); } attributes.put("RegionContacted", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getRegionsContacted())); attributes.put("SystemInformation", Utils.getSimpleObjectMapper().writeValueAsString(ClientSideRequestStatistics.fetchSystemInformation())); attributes.put("ClientCfgs", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getDiagnosticsClientContext())); if (clientSideRequestStatistics.getResponseStatisticsList() != null && clientSideRequestStatistics.getResponseStatisticsList().size() > 0 && clientSideRequestStatistics.getResponseStatisticsList().get(0).getStoreResult() != null) { String eventName = "Diagnostics for PKRange " + clientSideRequestStatistics.getResponseStatisticsList().get(0).getStoreResult().partitionKeyRangeId; tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC)); } else if (clientSideRequestStatistics.getGatewayStatistics() != null) { String eventName = "Diagnostics for PKRange " + clientSideRequestStatistics.getGatewayStatistics().getPartitionKeyRangeId(); tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC)); } else { String eventName = "Diagnostics " + queryDiagnosticsCounter++; tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC)); } } } }
class CosmosPagedFlux<T> extends ContinuablePagedFlux<String, T, FeedResponse<T>> { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosPagedFlux.class); private final Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction; private final Consumer<FeedResponse<T>> feedResponseConsumer; private ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor cosmosDiagnosticsAccessor; CosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction) { this.optionsFluxFunction = optionsFluxFunction; this.feedResponseConsumer = null; this.cosmosDiagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); } CosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction, Consumer<FeedResponse<T>> feedResponseConsumer) { this.optionsFluxFunction = optionsFluxFunction; this.feedResponseConsumer = feedResponseConsumer; this.cosmosDiagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); } /** * Handle for invoking "side-effects" on each FeedResponse returned by CosmosPagedFlux * * @param newFeedResponseConsumer handler * @return CosmosPagedFlux instance with attached handler */ public CosmosPagedFlux<T> handle(Consumer<FeedResponse<T>> newFeedResponseConsumer) { if (this.feedResponseConsumer != null) { return new CosmosPagedFlux<T>( this.optionsFluxFunction, this.feedResponseConsumer.andThen(newFeedResponseConsumer)); } else { return new CosmosPagedFlux<T>(this.optionsFluxFunction, newFeedResponseConsumer); } } @Override public Flux<FeedResponse<T>> byPage() { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(String continuationToken) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setRequestContinuation(continuationToken); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(int preferredPageSize) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setMaxItemCount(preferredPageSize); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(String continuationToken, int preferredPageSize) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setRequestContinuation(continuationToken); cosmosPagedFluxOptions.setMaxItemCount(preferredPageSize); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } /** * Subscribe to consume all items of type {@code T} in the sequence respectively. This is recommended for most * common scenarios. This will seamlessly fetch next page when required and provide with a {@link Flux} of items. * * @param coreSubscriber The subscriber for this {@link CosmosPagedFlux} */ @Override public void subscribe(CoreSubscriber<? super T> coreSubscriber) { Flux<FeedResponse<T>> pagedResponse = this.byPage(); pagedResponse.flatMap(tFeedResponse -> { IterableStream<T> elements = tFeedResponse.getElements(); if (elements == null) { return Flux.empty(); } return Flux.fromIterable(elements); }).subscribe(coreSubscriber); } private Flux<FeedResponse<T>> byPage(CosmosPagedFluxOptions pagedFluxOptions, Context context) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); AtomicReference<Instant> startTime = new AtomicReference<>(); return this.optionsFluxFunction.apply(pagedFluxOptions).doOnSubscribe(ignoredValue -> { if (pagedFluxOptions.getTracerProvider() != null && pagedFluxOptions.getTracerProvider().isEnabled()) { parentContext.set(pagedFluxOptions.getTracerProvider().startSpan(pagedFluxOptions.getTracerSpanName(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getServiceEndpoint(), context)); } startTime.set(Instant.now()); }).doOnComplete(() -> { if (pagedFluxOptions.getTracerProvider() != null && pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.complete(), HttpConstants.StatusCodes.OK); } }).doOnError(throwable -> { if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient())) && throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) throwable; if (isTracerEnabled(pagedFluxOptions) && this.cosmosDiagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(cosmosException.getDiagnostics()).compareAndSet(false, true)) { try { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), cosmosException.getDiagnostics(), parentContext.get()); } catch (JsonProcessingException ex) { LOGGER.warn("Error while serializing diagnostics for tracer", ex.getMessage()); } } if (this.cosmosDiagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(cosmosException.getDiagnostics()).compareAndSet(false, true)) { fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), 0, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) cosmosException.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); } } if (isTracerEnabled(pagedFluxOptions)) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.error(throwable), TracerProvider.ERROR_CODE); } startTime.set(Instant.now()); }).doOnNext(feedResponse -> { if (isTracerEnabled(pagedFluxOptions) && this.cosmosDiagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(feedResponse.getCosmosDiagnostics()).compareAndSet(false, true)) { try { Duration threshold = pagedFluxOptions.getThresholdForDiagnosticsOnTracer(); if (threshold == null) { threshold = pagedFluxOptions.getTracerProvider().QUERY_THRESHOLD_FOR_DIAGNOSTICS; } if (Duration.between(startTime.get(), Instant.now()).compareTo(threshold) > 0) { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), feedResponse.getCosmosDiagnostics(), parentContext.get()); } } catch (JsonProcessingException ex) { LOGGER.warn("Error while serializing diagnostics for tracer", ex.getMessage()); } } if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient()))) { if (this.cosmosDiagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(feedResponse.getCosmosDiagnostics()).compareAndSet(false, true)) { fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), HttpConstants.StatusCodes.OK, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) feedResponse.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); startTime.set(Instant.now()); }; } }); } private void fillClientTelemetry(CosmosAsyncClient cosmosAsyncClient, int statusCode, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, float requestCharge, Duration latency) { ClientTelemetry telemetry = BridgeInternal.getContextClient(cosmosAsyncClient).getClientTelemetry(); ReportPayload reportPayloadLatency = createReportPayload(cosmosAsyncClient, statusCode, containerId, databaseId , operationType, resourceType, consistencyLevel, ClientTelemetry.REQUEST_LATENCY_NAME, ClientTelemetry.REQUEST_LATENCY_UNIT); ConcurrentDoubleHistogram latencyHistogram = telemetry.getClientTelemetryInfo().getOperationInfoMap().get(reportPayloadLatency); if (latencyHistogram != null) { ClientTelemetry.recordValue(latencyHistogram, latency.toNanos() / 1000); } else { if (statusCode == HttpConstants.StatusCodes.OK) { latencyHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_LATENCY_MAX_MICRO_SEC, ClientTelemetry.REQUEST_LATENCY_SUCCESS_PRECISION); } else { latencyHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_LATENCY_MAX_MICRO_SEC, ClientTelemetry.REQUEST_LATENCY_FAILURE_PRECISION); } latencyHistogram.setAutoResize(true); ClientTelemetry.recordValue(latencyHistogram, latency.toNanos() / 1000); telemetry.getClientTelemetryInfo().getOperationInfoMap().put(reportPayloadLatency, latencyHistogram); } ReportPayload reportPayloadRequestCharge = createReportPayload(cosmosAsyncClient, statusCode, containerId, databaseId , operationType, resourceType, consistencyLevel, ClientTelemetry.REQUEST_CHARGE_NAME, ClientTelemetry.REQUEST_CHARGE_UNIT); ConcurrentDoubleHistogram requestChargeHistogram = telemetry.getClientTelemetryInfo().getOperationInfoMap().get(reportPayloadRequestCharge); if (requestChargeHistogram != null) { ClientTelemetry.recordValue(requestChargeHistogram, requestCharge); } else { requestChargeHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_CHARGE_MAX, ClientTelemetry.REQUEST_CHARGE_PRECISION); requestChargeHistogram.setAutoResize(true); ClientTelemetry.recordValue(requestChargeHistogram, requestCharge); telemetry.getClientTelemetryInfo().getOperationInfoMap().put(reportPayloadRequestCharge, requestChargeHistogram); } } static { ImplementationBridgeHelpers.CosmosPageFluxHelper.setCosmosPageFluxAccessor( new ImplementationBridgeHelpers.CosmosPageFluxHelper.CosmosPageFluxAccessor() { @Override public <T> CosmosPagedFlux<T> getCosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction) { return new CosmosPagedFlux<>(optionsFluxFunction); } }); } private ReportPayload createReportPayload(CosmosAsyncClient cosmosAsyncClient, int statusCode, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, String metricsName, String unitName) { ReportPayload reportPayload = new ReportPayload(metricsName, unitName); reportPayload.setConsistency(consistencyLevel == null ? BridgeInternal.getContextClient(cosmosAsyncClient).getConsistencyLevel() : consistencyLevel); reportPayload.setDatabaseName(databaseId); reportPayload.setContainerName(containerId); reportPayload.setOperation(operationType); reportPayload.setResource(resourceType); reportPayload.setStatusCode(statusCode); return reportPayload; } private void addDiagnosticsOnTracerEvent(TracerProvider tracerProvider, CosmosDiagnostics cosmosDiagnostics, Context parentContext) throws JsonProcessingException { if (cosmosDiagnostics == null) { return; } Map<String, Object> attributes = new HashMap<>(); QueryInfo.QueryPlanDiagnosticsContext queryPlanDiagnosticsContext = cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics) != null ? cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics).getQueryPlanDiagnosticsContext() : null; if (queryPlanDiagnosticsContext != null) { attributes.put("JSON", Utils.getSimpleObjectMapper().writeValueAsString(queryPlanDiagnosticsContext)); tracerProvider.addEvent("Query Plan Statistics", attributes, OffsetDateTime.ofInstant(queryPlanDiagnosticsContext.getStartTimeUTC(), ZoneOffset.UTC), parentContext); } FeedResponseDiagnostics feedResponseDiagnostics = cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics); if (feedResponseDiagnostics != null && feedResponseDiagnostics.getQueryMetricsMap() != null && feedResponseDiagnostics.getQueryMetricsMap().size() > 0) { for(Map.Entry<String, QueryMetrics> entry : feedResponseDiagnostics.getQueryMetricsMap().entrySet()) { attributes = new HashMap<>(); attributes.put("Query Metrics", entry.getValue().toString()); tracerProvider.addEvent("Query Metrics for PKRange " + entry.getKey(), attributes, OffsetDateTime.now(), parentContext); } } int queryDiagnosticsCounter = 1; for (ClientSideRequestStatistics clientSideRequestStatistics : BridgeInternal.getClientSideRequestStatisticsList(cosmosDiagnostics)) { attributes = new HashMap<>(); int counter = 1; for (ClientSideRequestStatistics.StoreResponseStatistics statistics : clientSideRequestStatistics.getResponseStatisticsList()) { attributes.put("StoreResponse" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(statistics)); } counter = 1; for (ClientSideRequestStatistics.StoreResponseStatistics statistics : ClientSideRequestStatistics.getCappedSupplementalResponseStatisticsList(clientSideRequestStatistics.getSupplementalResponseStatisticsList())) { attributes.put("Supplemental StoreResponse" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(statistics)); } if (clientSideRequestStatistics.getRetryContext().getRetryStartTime() != null) { attributes.put("Retry Context", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getRetryContext())); } counter = 1; for (ClientSideRequestStatistics.AddressResolutionStatistics addressResolutionStatistics : clientSideRequestStatistics.getAddressResolutionStatistics().values()) { attributes.put("AddressResolutionStatistics" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(addressResolutionStatistics)); } if (clientSideRequestStatistics.getSerializationDiagnosticsContext().serializationDiagnosticsList != null) { counter = 1; for (SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics : clientSideRequestStatistics.getSerializationDiagnosticsContext().serializationDiagnosticsList) { attributes = new HashMap<>(); attributes.put("SerializationDiagnostics" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(serializationDiagnostics)); } } if(clientSideRequestStatistics.getGatewayStatistics() != null) { attributes.put("GatewayStatistics", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getGatewayStatistics())); } attributes.put("RegionContacted", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getRegionsContacted())); attributes.put("SystemInformation", Utils.getSimpleObjectMapper().writeValueAsString(ClientSideRequestStatistics.fetchSystemInformation())); attributes.put("ClientCfgs", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getDiagnosticsClientContext())); if (clientSideRequestStatistics.getResponseStatisticsList() != null && clientSideRequestStatistics.getResponseStatisticsList().size() > 0 && clientSideRequestStatistics.getResponseStatisticsList().get(0).getStoreResult() != null) { String eventName = "Diagnostics for PKRange " + clientSideRequestStatistics.getResponseStatisticsList().get(0).getStoreResult().partitionKeyRangeId; tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC), parentContext); } else if (clientSideRequestStatistics.getGatewayStatistics() != null) { String eventName = "Diagnostics for PKRange " + clientSideRequestStatistics.getGatewayStatistics().getPartitionKeyRangeId(); tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC), parentContext); } else { String eventName = "Diagnostics " + queryDiagnosticsCounter++; tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC), parentContext); } } } private boolean isTracerEnabled(CosmosPagedFluxOptions pagedFluxOptions) { return pagedFluxOptions.getTracerProvider() != null && pagedFluxOptions.getTracerProvider().isEnabled(); } }
why can't we rely on the targetRange please see here: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DocumentProducer.java#L93 is that going be different than this one from the header response?
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); if (StringUtils.isEmpty(pkrId)) { pkrId = "0"; } String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } }
String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID);
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } }
on which scenario we come here? is this code reachable? can't we rely on the `targetRage` see my above comment for this?
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); if (StringUtils.isEmpty(pkrId)) { pkrId = "0"; } String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } }
pkrId = "0";
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } }
I'll add a more detailed comment. The following is a class and JSON string I'll use as an example: ```java public class AClass { @JsonFlatten @JsonProperty("flattened.string") private String flattenedString; @JsonIgnore private Map<String, Object> additionalProperties; @JsonAnySetter void addAdditionalProperty(String key, Object value) { if (additionalProperties == null) { additionalProperties = new HashMap<>(); } additionalProperties.put(key, value); } } ``` ```json { "flattened": { "string": "string" }, "additionalProperty1": "value1", "additionalProperty2": "value2" } ``` Before this change, after applying the un-flattening of `flattened.string` the JSON tree structure would have been equivalent to the following JSON: ```json { "flattened": { "string": "string" }, "additionalProperty1": "value1", "additionalProperty2": "value2", "flattened.string": "string" } ``` With the `JsonAnySetter` existing this would have then resulted in an errant entry existing in `additionalProperties` of: ``` additionalProperties.get("flattened") => map of "string":"string" ``` After this change, after applying the un-flattening of `flattened.string` the JSON tree structure leading to the flattened value will be cleaned up for every sub-tree which is now empty, resulting the following JSON: ```json { "additionalProperty1": "value1", "additionalProperty2": "value2", "flattened.string": "string" } ``` So, there will no longer be any errant properties existing in `additionalProperties`.
private void handleFlatteningForField(AnnotatedField annotatedField, JsonNode jsonNode) { final JsonProperty jsonProperty = annotatedField.getAnnotation(JsonProperty.class); if (jsonProperty != null) { final String jsonPropValue = jsonProperty.value(); if (jsonNode.has(jsonPropValue)) { final String escapedJsonPropValue = jsonPropValue.replace(".", "\\."); ((ObjectNode) jsonNode).set(escapedJsonPropValue, jsonNode.get(jsonPropValue)); } if ((classHasJsonFlatten || annotatedField.hasAnnotation(JsonFlatten.class)) && IS_FLATTENED_PATTERN.matcher(jsonPropValue).matches()) { String[] jsonNodeKeys = Arrays.stream(SPLIT_KEY_PATTERN.split(jsonPropValue)) .map(FlatteningDeserializer::unescapeEscapedDots) .toArray(String[]::new); List<JsonNode> nodePath = new ArrayList<>(); nodePath.add(jsonNode); JsonNode nodeToAdd = jsonNode; for (String jsonNodeKey : jsonNodeKeys) { nodeToAdd = nodeToAdd.get(jsonNodeKey); if (nodeToAdd == null) { break; } nodePath.add(nodeToAdd); } if (nodePath.size() == 1) { ((ObjectNode) jsonNode).set(jsonPropValue, null); return; } if (!nodePath.get(nodePath.size() - 2).has(jsonNodeKeys[jsonNodeKeys.length - 1])) { ((ObjectNode) jsonNode).set(jsonPropValue, null); } else { ((ObjectNode) jsonNode).set(jsonPropValue, nodePath.get(nodePath.size() - 1)); } for (int i = nodePath.size() - 2; i >= 0; i--) { if (i == nodePath.size() - 2 && nodePath.size() - 1 != jsonNodeKeys.length && nodePath.get(i).get(jsonNodeKeys[i]).size() != 0) { break; } ((ObjectNode) nodePath.get(i)).remove(jsonNodeKeys[i]); if (nodePath.get(i).size() > 0) { break; } } } } }
private void handleFlatteningForField(AnnotatedField annotatedField, JsonNode jsonNode) { final JsonProperty jsonProperty = annotatedField.getAnnotation(JsonProperty.class); if (jsonProperty != null) { final String jsonPropValue = jsonProperty.value(); if (jsonNode.has(jsonPropValue)) { final String escapedJsonPropValue = jsonPropValue.replace(".", "\\."); ((ObjectNode) jsonNode).set(escapedJsonPropValue, jsonNode.get(jsonPropValue)); } if ((classHasJsonFlatten || annotatedField.hasAnnotation(JsonFlatten.class)) && IS_FLATTENED_PATTERN.matcher(jsonPropValue).matches()) { String[] jsonNodeKeys = Arrays.stream(SPLIT_KEY_PATTERN.split(jsonPropValue)) .map(FlatteningDeserializer::unescapeEscapedDots) .toArray(String[]::new); List<JsonNode> nodePath = new ArrayList<>(); nodePath.add(jsonNode); JsonNode nodeToAdd = jsonNode; for (String jsonNodeKey : jsonNodeKeys) { nodeToAdd = nodeToAdd.get(jsonNodeKey); if (nodeToAdd == null) { break; } nodePath.add(nodeToAdd); } if (nodePath.size() == 1) { ((ObjectNode) jsonNode).set(jsonPropValue, null); return; } if (!nodePath.get(nodePath.size() - 2).has(jsonNodeKeys[jsonNodeKeys.length - 1])) { ((ObjectNode) jsonNode).set(jsonPropValue, null); } else { ((ObjectNode) jsonNode).set(jsonPropValue, nodePath.get(nodePath.size() - 1)); } for (int i = nodePath.size() - 2; i >= 0; i--) { if (i == nodePath.size() - 2 && nodePath.size() - 1 != jsonNodeKeys.length && nodePath.get(i).get(jsonNodeKeys[i]).size() != 0) { break; } ((ObjectNode) nodePath.get(i)).remove(jsonNodeKeys[i]); if (nodePath.get(i).size() > 0) { break; } } } } }
class that field belongs to */
class that field belongs to */
I was debating myself, i.e. if for any reason , cx start getting this on every request it will fill the logs. However we are not expecting this at all , so lets have warning . Done
private Flux<FeedResponse<T>> byPage(CosmosPagedFluxOptions pagedFluxOptions, Context context) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); AtomicReference<Instant> startTime = new AtomicReference<>(); return this.optionsFluxFunction.apply(pagedFluxOptions).doOnSubscribe(ignoredValue -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { parentContext.set(pagedFluxOptions.getTracerProvider().startSpan(pagedFluxOptions.getTracerSpanName(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getServiceEndpoint(), context)); } startTime.set(Instant.now()); }).doOnComplete(() -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.complete(), HttpConstants.StatusCodes.OK); } }).doOnError(throwable -> { if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient())) && throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) throwable; if (pagedFluxOptions.getTracerProvider().isEnabled()) { ((Span) parentContext.get().getData(PARENT_SPAN_KEY).get()).makeCurrent(); try { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), cosmosException.getDiagnostics(), parentContext.get()); } catch (JsonProcessingException ex) { LOGGER.debug("Error while serializing diagnostics for tracer", ex); } } fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), 0, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) cosmosException.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); } if (pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.error(throwable), TracerProvider.ERROR_CODE); } startTime.set(Instant.now()); }).doOnNext(feedResponse -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { ((Span) parentContext.get().getData(PARENT_SPAN_KEY).get()).makeCurrent(); try { Duration threshold = pagedFluxOptions.getThresholdForDiagnosticsOnTracer(); if (threshold == null) { threshold = TracerProvider.QUERY_THRESHOLD_FOR_DIAGNOSTICS; } if (Duration.between(startTime.get(), Instant.now()).compareTo(threshold) > 0) { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), feedResponse.getCosmosDiagnostics(), parentContext.get()); } } catch (JsonProcessingException ex) { LOGGER.debug("Error while serializing diagnostics for tracer", ex); } } if (feedResponseConsumer != null) { feedResponseConsumer.accept(feedResponse); } if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient()))) { fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), HttpConstants.StatusCodes.OK, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) feedResponse.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); startTime.set(Instant.now()); } }); }
LOGGER.debug("Error while serializing diagnostics for tracer", ex);
then call it with each feedResponse if (feedResponseConsumer != null) { feedResponseConsumer.accept(feedResponse); }
class CosmosPagedFlux<T> extends ContinuablePagedFlux<String, T, FeedResponse<T>> { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosPagedFlux.class); private final Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction; private final Consumer<FeedResponse<T>> feedResponseConsumer; private CosmosDiagnosticsAccessor cosmosDiagnosticsAccessor; CosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction) { this.optionsFluxFunction = optionsFluxFunction; this.feedResponseConsumer = null; this.cosmosDiagnosticsAccessor = CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); } CosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction, Consumer<FeedResponse<T>> feedResponseConsumer) { this.optionsFluxFunction = optionsFluxFunction; this.feedResponseConsumer = feedResponseConsumer; this.cosmosDiagnosticsAccessor = CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); } /** * Handle for invoking "side-effects" on each FeedResponse returned by CosmosPagedFlux * * @param newFeedResponseConsumer handler * @return CosmosPagedFlux instance with attached handler */ public CosmosPagedFlux<T> handle(Consumer<FeedResponse<T>> newFeedResponseConsumer) { if (this.feedResponseConsumer != null) { return new CosmosPagedFlux<T>( this.optionsFluxFunction, this.feedResponseConsumer.andThen(newFeedResponseConsumer)); } else { return new CosmosPagedFlux<T>(this.optionsFluxFunction, newFeedResponseConsumer); } } @Override public Flux<FeedResponse<T>> byPage() { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(String continuationToken) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setRequestContinuation(continuationToken); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(int preferredPageSize) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setMaxItemCount(preferredPageSize); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(String continuationToken, int preferredPageSize) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setRequestContinuation(continuationToken); cosmosPagedFluxOptions.setMaxItemCount(preferredPageSize); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } /** * Subscribe to consume all items of type {@code T} in the sequence respectively. This is recommended for most * common scenarios. This will seamlessly fetch next page when required and provide with a {@link Flux} of items. * * @param coreSubscriber The subscriber for this {@link CosmosPagedFlux} */ @Override public void subscribe(CoreSubscriber<? super T> coreSubscriber) { Flux<FeedResponse<T>> pagedResponse = this.byPage(); pagedResponse.flatMap(tFeedResponse -> { IterableStream<T> elements = tFeedResponse.getElements(); if (elements == null) { return Flux.empty(); } return Flux.fromIterable(elements); }).subscribe(coreSubscriber); } private Flux<FeedResponse<T>> byPage(CosmosPagedFluxOptions pagedFluxOptions, Context context) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); AtomicReference<Instant> startTime = new AtomicReference<>(); return this.optionsFluxFunction.apply(pagedFluxOptions).doOnSubscribe(ignoredValue -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { parentContext.set(pagedFluxOptions.getTracerProvider().startSpan(pagedFluxOptions.getTracerSpanName(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getServiceEndpoint(), context)); } startTime.set(Instant.now()); }).doOnComplete(() -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.complete(), HttpConstants.StatusCodes.OK); } }).doOnError(throwable -> { if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient())) && throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) throwable; if (pagedFluxOptions.getTracerProvider().isEnabled()) { ((Span) parentContext.get().getData(PARENT_SPAN_KEY).get()).makeCurrent(); try { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), cosmosException.getDiagnostics(), parentContext.get()); } catch (JsonProcessingException ex) { LOGGER.debug("Error while serializing diagnostics for tracer", ex); } } fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), 0, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) cosmosException.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); } if (pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.error(throwable), TracerProvider.ERROR_CODE); } startTime.set(Instant.now()); }).doOnNext(feedResponse -> { if (pagedFluxOptions.getTracerProvider().isEnabled()) { ((Span) parentContext.get().getData(PARENT_SPAN_KEY).get()).makeCurrent(); try { Duration threshold = pagedFluxOptions.getThresholdForDiagnosticsOnTracer(); if (threshold == null) { threshold = TracerProvider.QUERY_THRESHOLD_FOR_DIAGNOSTICS; } if (Duration.between(startTime.get(), Instant.now()).compareTo(threshold) > 0) { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), feedResponse.getCosmosDiagnostics(), parentContext.get()); } } catch (JsonProcessingException ex) { LOGGER.debug("Error while serializing diagnostics for tracer", ex); } } if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient()))) { fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), HttpConstants.StatusCodes.OK, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) feedResponse.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); startTime.set(Instant.now()); } }); } private void fillClientTelemetry(CosmosAsyncClient cosmosAsyncClient, int statusCode, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, float requestCharge, Duration latency) { ClientTelemetry telemetry = BridgeInternal.getContextClient(cosmosAsyncClient).getClientTelemetry(); ReportPayload reportPayloadLatency = createReportPayload(cosmosAsyncClient, statusCode, containerId, databaseId , operationType, resourceType, consistencyLevel, ClientTelemetry.REQUEST_LATENCY_NAME, ClientTelemetry.REQUEST_LATENCY_UNIT); ConcurrentDoubleHistogram latencyHistogram = telemetry.getClientTelemetryInfo().getOperationInfoMap().get(reportPayloadLatency); if (latencyHistogram != null) { ClientTelemetry.recordValue(latencyHistogram, latency.toNanos() / 1000); } else { if (statusCode == HttpConstants.StatusCodes.OK) { latencyHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_LATENCY_MAX_MICRO_SEC, ClientTelemetry.REQUEST_LATENCY_SUCCESS_PRECISION); } else { latencyHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_LATENCY_MAX_MICRO_SEC, ClientTelemetry.REQUEST_LATENCY_FAILURE_PRECISION); } latencyHistogram.setAutoResize(true); ClientTelemetry.recordValue(latencyHistogram, latency.toNanos() / 1000); telemetry.getClientTelemetryInfo().getOperationInfoMap().put(reportPayloadLatency, latencyHistogram); } ReportPayload reportPayloadRequestCharge = createReportPayload(cosmosAsyncClient, statusCode, containerId, databaseId , operationType, resourceType, consistencyLevel, ClientTelemetry.REQUEST_CHARGE_NAME, ClientTelemetry.REQUEST_CHARGE_UNIT); ConcurrentDoubleHistogram requestChargeHistogram = telemetry.getClientTelemetryInfo().getOperationInfoMap().get(reportPayloadRequestCharge); if (requestChargeHistogram != null) { ClientTelemetry.recordValue(requestChargeHistogram, requestCharge); } else { requestChargeHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_CHARGE_MAX, ClientTelemetry.REQUEST_CHARGE_PRECISION); requestChargeHistogram.setAutoResize(true); ClientTelemetry.recordValue(requestChargeHistogram, requestCharge); telemetry.getClientTelemetryInfo().getOperationInfoMap().put(reportPayloadRequestCharge, requestChargeHistogram); } } private ReportPayload createReportPayload(CosmosAsyncClient cosmosAsyncClient, int statusCode, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, String metricsName, String unitName) { ReportPayload reportPayload = new ReportPayload(metricsName, unitName); reportPayload.setConsistency(consistencyLevel == null ? BridgeInternal.getContextClient(cosmosAsyncClient).getConsistencyLevel() : consistencyLevel); reportPayload.setDatabaseName(databaseId); reportPayload.setContainerName(containerId); reportPayload.setOperation(operationType); reportPayload.setResource(resourceType); reportPayload.setStatusCode(statusCode); return reportPayload; } private void addDiagnosticsOnTracerEvent(TracerProvider tracerProvider, CosmosDiagnostics cosmosDiagnostics, Context parentContext) throws JsonProcessingException { if (cosmosDiagnostics == null) { return; } Map<String, Object> attributes = new HashMap<>(); QueryInfo.QueryPlanDiagnosticsContext queryPlanDiagnosticsContext = cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics) != null ? cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics).getQueryPlanDiagnosticsContext() : null; if (queryPlanDiagnosticsContext != null) { attributes.put("JSON", Utils.getSimpleObjectMapper().writeValueAsString(queryPlanDiagnosticsContext)); tracerProvider.addEvent("Query Plan Statistics", attributes, OffsetDateTime.ofInstant(queryPlanDiagnosticsContext.getStartTimeUTC(), ZoneOffset.UTC)); } FeedResponseDiagnostics feedResponseDiagnostics = cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics); if (feedResponseDiagnostics != null && feedResponseDiagnostics.getQueryMetricsMap() != null && feedResponseDiagnostics.getQueryMetricsMap().size() > 0) { for(Map.Entry<String, QueryMetrics> entry : feedResponseDiagnostics.getQueryMetricsMap().entrySet()) { attributes = new HashMap<>(); attributes.put("Query Metrics", entry.getValue().toString()); tracerProvider.addEvent("Query Metrics for PKRange " + entry.getKey(), attributes, OffsetDateTime.now()); } } int queryDiagnosticsCounter = 1; for (ClientSideRequestStatistics clientSideRequestStatistics : BridgeInternal.getClientSideRequestStatisticsList(cosmosDiagnostics)) { attributes = new HashMap<>(); int counter = 1; for (ClientSideRequestStatistics.StoreResponseStatistics statistics : clientSideRequestStatistics.getResponseStatisticsList()) { attributes.put("StoreResponse" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(statistics)); } counter = 1; for (ClientSideRequestStatistics.StoreResponseStatistics statistics : ClientSideRequestStatistics.getCappedSupplementalResponseStatisticsList(clientSideRequestStatistics.getSupplementalResponseStatisticsList())) { attributes.put("Supplemental StoreResponse" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(statistics)); } if (clientSideRequestStatistics.getRetryContext().getRetryStartTime() != null) { attributes.put("Retry Context", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getRetryContext())); } counter = 1; for (ClientSideRequestStatistics.AddressResolutionStatistics addressResolutionStatistics : clientSideRequestStatistics.getAddressResolutionStatistics().values()) { attributes.put("AddressResolutionStatistics" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(addressResolutionStatistics)); } if (clientSideRequestStatistics.getSerializationDiagnosticsContext().serializationDiagnosticsList != null) { counter = 1; for (SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics : clientSideRequestStatistics.getSerializationDiagnosticsContext().serializationDiagnosticsList) { attributes = new HashMap<>(); attributes.put("SerializationDiagnostics" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(serializationDiagnostics)); } } if(clientSideRequestStatistics.getGatewayStatistics() != null) { attributes.put("GatewayStatistics", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getGatewayStatistics())); } attributes.put("RegionContacted", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getRegionsContacted())); attributes.put("SystemInformation", Utils.getSimpleObjectMapper().writeValueAsString(ClientSideRequestStatistics.fetchSystemInformation())); attributes.put("ClientCfgs", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getDiagnosticsClientContext())); if (clientSideRequestStatistics.getResponseStatisticsList() != null && clientSideRequestStatistics.getResponseStatisticsList().size() > 0 && clientSideRequestStatistics.getResponseStatisticsList().get(0).getStoreResult() != null) { String eventName = "Diagnostics for PKRange " + clientSideRequestStatistics.getResponseStatisticsList().get(0).getStoreResult().partitionKeyRangeId; tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC)); } else if (clientSideRequestStatistics.getGatewayStatistics() != null) { String eventName = "Diagnostics for PKRange " + clientSideRequestStatistics.getGatewayStatistics().getPartitionKeyRangeId(); tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC)); } else { String eventName = "Diagnostics " + queryDiagnosticsCounter++; tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC)); } } } }
class CosmosPagedFlux<T> extends ContinuablePagedFlux<String, T, FeedResponse<T>> { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosPagedFlux.class); private final Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction; private final Consumer<FeedResponse<T>> feedResponseConsumer; private ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor cosmosDiagnosticsAccessor; CosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction) { this.optionsFluxFunction = optionsFluxFunction; this.feedResponseConsumer = null; this.cosmosDiagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); } CosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction, Consumer<FeedResponse<T>> feedResponseConsumer) { this.optionsFluxFunction = optionsFluxFunction; this.feedResponseConsumer = feedResponseConsumer; this.cosmosDiagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); } /** * Handle for invoking "side-effects" on each FeedResponse returned by CosmosPagedFlux * * @param newFeedResponseConsumer handler * @return CosmosPagedFlux instance with attached handler */ public CosmosPagedFlux<T> handle(Consumer<FeedResponse<T>> newFeedResponseConsumer) { if (this.feedResponseConsumer != null) { return new CosmosPagedFlux<T>( this.optionsFluxFunction, this.feedResponseConsumer.andThen(newFeedResponseConsumer)); } else { return new CosmosPagedFlux<T>(this.optionsFluxFunction, newFeedResponseConsumer); } } @Override public Flux<FeedResponse<T>> byPage() { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(String continuationToken) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setRequestContinuation(continuationToken); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(int preferredPageSize) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setMaxItemCount(preferredPageSize); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } @Override public Flux<FeedResponse<T>> byPage(String continuationToken, int preferredPageSize) { CosmosPagedFluxOptions cosmosPagedFluxOptions = new CosmosPagedFluxOptions(); cosmosPagedFluxOptions.setRequestContinuation(continuationToken); cosmosPagedFluxOptions.setMaxItemCount(preferredPageSize); return FluxUtil.fluxContext(context -> byPage(cosmosPagedFluxOptions, context)); } /** * Subscribe to consume all items of type {@code T} in the sequence respectively. This is recommended for most * common scenarios. This will seamlessly fetch next page when required and provide with a {@link Flux} of items. * * @param coreSubscriber The subscriber for this {@link CosmosPagedFlux} */ @Override public void subscribe(CoreSubscriber<? super T> coreSubscriber) { Flux<FeedResponse<T>> pagedResponse = this.byPage(); pagedResponse.flatMap(tFeedResponse -> { IterableStream<T> elements = tFeedResponse.getElements(); if (elements == null) { return Flux.empty(); } return Flux.fromIterable(elements); }).subscribe(coreSubscriber); } private Flux<FeedResponse<T>> byPage(CosmosPagedFluxOptions pagedFluxOptions, Context context) { final AtomicReference<Context> parentContext = new AtomicReference<>(Context.NONE); AtomicReference<Instant> startTime = new AtomicReference<>(); return this.optionsFluxFunction.apply(pagedFluxOptions).doOnSubscribe(ignoredValue -> { if (pagedFluxOptions.getTracerProvider() != null && pagedFluxOptions.getTracerProvider().isEnabled()) { parentContext.set(pagedFluxOptions.getTracerProvider().startSpan(pagedFluxOptions.getTracerSpanName(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getServiceEndpoint(), context)); } startTime.set(Instant.now()); }).doOnComplete(() -> { if (pagedFluxOptions.getTracerProvider() != null && pagedFluxOptions.getTracerProvider().isEnabled()) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.complete(), HttpConstants.StatusCodes.OK); } }).doOnError(throwable -> { if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient())) && throwable instanceof CosmosException) { CosmosException cosmosException = (CosmosException) throwable; if (isTracerEnabled(pagedFluxOptions) && this.cosmosDiagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(cosmosException.getDiagnostics()).compareAndSet(false, true)) { try { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), cosmosException.getDiagnostics(), parentContext.get()); } catch (JsonProcessingException ex) { LOGGER.warn("Error while serializing diagnostics for tracer", ex.getMessage()); } } if (this.cosmosDiagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(cosmosException.getDiagnostics()).compareAndSet(false, true)) { fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), 0, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) cosmosException.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); } } if (isTracerEnabled(pagedFluxOptions)) { pagedFluxOptions.getTracerProvider().endSpan(parentContext.get(), Signal.error(throwable), TracerProvider.ERROR_CODE); } startTime.set(Instant.now()); }).doOnNext(feedResponse -> { if (isTracerEnabled(pagedFluxOptions) && this.cosmosDiagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(feedResponse.getCosmosDiagnostics()).compareAndSet(false, true)) { try { Duration threshold = pagedFluxOptions.getThresholdForDiagnosticsOnTracer(); if (threshold == null) { threshold = pagedFluxOptions.getTracerProvider().QUERY_THRESHOLD_FOR_DIAGNOSTICS; } if (Duration.between(startTime.get(), Instant.now()).compareTo(threshold) > 0) { addDiagnosticsOnTracerEvent(pagedFluxOptions.getTracerProvider(), feedResponse.getCosmosDiagnostics(), parentContext.get()); } } catch (JsonProcessingException ex) { LOGGER.warn("Error while serializing diagnostics for tracer", ex.getMessage()); } } if (pagedFluxOptions.getCosmosAsyncClient() != null && Configs.isClientTelemetryEnabled(BridgeInternal.isClientTelemetryEnabled(pagedFluxOptions.getCosmosAsyncClient()))) { if (this.cosmosDiagnosticsAccessor.isDiagnosticsCapturedInPagedFlux(feedResponse.getCosmosDiagnostics()).compareAndSet(false, true)) { fillClientTelemetry(pagedFluxOptions.getCosmosAsyncClient(), HttpConstants.StatusCodes.OK, pagedFluxOptions.getContainerId(), pagedFluxOptions.getDatabaseId(), pagedFluxOptions.getOperationType(), pagedFluxOptions.getResourceType(), BridgeInternal.getContextClient(pagedFluxOptions.getCosmosAsyncClient()).getConsistencyLevel(), (float) feedResponse.getRequestCharge(), Duration.between(startTime.get(), Instant.now())); startTime.set(Instant.now()); }; } }); } private void fillClientTelemetry(CosmosAsyncClient cosmosAsyncClient, int statusCode, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, float requestCharge, Duration latency) { ClientTelemetry telemetry = BridgeInternal.getContextClient(cosmosAsyncClient).getClientTelemetry(); ReportPayload reportPayloadLatency = createReportPayload(cosmosAsyncClient, statusCode, containerId, databaseId , operationType, resourceType, consistencyLevel, ClientTelemetry.REQUEST_LATENCY_NAME, ClientTelemetry.REQUEST_LATENCY_UNIT); ConcurrentDoubleHistogram latencyHistogram = telemetry.getClientTelemetryInfo().getOperationInfoMap().get(reportPayloadLatency); if (latencyHistogram != null) { ClientTelemetry.recordValue(latencyHistogram, latency.toNanos() / 1000); } else { if (statusCode == HttpConstants.StatusCodes.OK) { latencyHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_LATENCY_MAX_MICRO_SEC, ClientTelemetry.REQUEST_LATENCY_SUCCESS_PRECISION); } else { latencyHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_LATENCY_MAX_MICRO_SEC, ClientTelemetry.REQUEST_LATENCY_FAILURE_PRECISION); } latencyHistogram.setAutoResize(true); ClientTelemetry.recordValue(latencyHistogram, latency.toNanos() / 1000); telemetry.getClientTelemetryInfo().getOperationInfoMap().put(reportPayloadLatency, latencyHistogram); } ReportPayload reportPayloadRequestCharge = createReportPayload(cosmosAsyncClient, statusCode, containerId, databaseId , operationType, resourceType, consistencyLevel, ClientTelemetry.REQUEST_CHARGE_NAME, ClientTelemetry.REQUEST_CHARGE_UNIT); ConcurrentDoubleHistogram requestChargeHistogram = telemetry.getClientTelemetryInfo().getOperationInfoMap().get(reportPayloadRequestCharge); if (requestChargeHistogram != null) { ClientTelemetry.recordValue(requestChargeHistogram, requestCharge); } else { requestChargeHistogram = new ConcurrentDoubleHistogram(ClientTelemetry.REQUEST_CHARGE_MAX, ClientTelemetry.REQUEST_CHARGE_PRECISION); requestChargeHistogram.setAutoResize(true); ClientTelemetry.recordValue(requestChargeHistogram, requestCharge); telemetry.getClientTelemetryInfo().getOperationInfoMap().put(reportPayloadRequestCharge, requestChargeHistogram); } } static { ImplementationBridgeHelpers.CosmosPageFluxHelper.setCosmosPageFluxAccessor( new ImplementationBridgeHelpers.CosmosPageFluxHelper.CosmosPageFluxAccessor() { @Override public <T> CosmosPagedFlux<T> getCosmosPagedFlux(Function<CosmosPagedFluxOptions, Flux<FeedResponse<T>>> optionsFluxFunction) { return new CosmosPagedFlux<>(optionsFluxFunction); } }); } private ReportPayload createReportPayload(CosmosAsyncClient cosmosAsyncClient, int statusCode, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, String metricsName, String unitName) { ReportPayload reportPayload = new ReportPayload(metricsName, unitName); reportPayload.setConsistency(consistencyLevel == null ? BridgeInternal.getContextClient(cosmosAsyncClient).getConsistencyLevel() : consistencyLevel); reportPayload.setDatabaseName(databaseId); reportPayload.setContainerName(containerId); reportPayload.setOperation(operationType); reportPayload.setResource(resourceType); reportPayload.setStatusCode(statusCode); return reportPayload; } private void addDiagnosticsOnTracerEvent(TracerProvider tracerProvider, CosmosDiagnostics cosmosDiagnostics, Context parentContext) throws JsonProcessingException { if (cosmosDiagnostics == null) { return; } Map<String, Object> attributes = new HashMap<>(); QueryInfo.QueryPlanDiagnosticsContext queryPlanDiagnosticsContext = cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics) != null ? cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics).getQueryPlanDiagnosticsContext() : null; if (queryPlanDiagnosticsContext != null) { attributes.put("JSON", Utils.getSimpleObjectMapper().writeValueAsString(queryPlanDiagnosticsContext)); tracerProvider.addEvent("Query Plan Statistics", attributes, OffsetDateTime.ofInstant(queryPlanDiagnosticsContext.getStartTimeUTC(), ZoneOffset.UTC), parentContext); } FeedResponseDiagnostics feedResponseDiagnostics = cosmosDiagnosticsAccessor.getFeedResponseDiagnostics(cosmosDiagnostics); if (feedResponseDiagnostics != null && feedResponseDiagnostics.getQueryMetricsMap() != null && feedResponseDiagnostics.getQueryMetricsMap().size() > 0) { for(Map.Entry<String, QueryMetrics> entry : feedResponseDiagnostics.getQueryMetricsMap().entrySet()) { attributes = new HashMap<>(); attributes.put("Query Metrics", entry.getValue().toString()); tracerProvider.addEvent("Query Metrics for PKRange " + entry.getKey(), attributes, OffsetDateTime.now(), parentContext); } } int queryDiagnosticsCounter = 1; for (ClientSideRequestStatistics clientSideRequestStatistics : BridgeInternal.getClientSideRequestStatisticsList(cosmosDiagnostics)) { attributes = new HashMap<>(); int counter = 1; for (ClientSideRequestStatistics.StoreResponseStatistics statistics : clientSideRequestStatistics.getResponseStatisticsList()) { attributes.put("StoreResponse" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(statistics)); } counter = 1; for (ClientSideRequestStatistics.StoreResponseStatistics statistics : ClientSideRequestStatistics.getCappedSupplementalResponseStatisticsList(clientSideRequestStatistics.getSupplementalResponseStatisticsList())) { attributes.put("Supplemental StoreResponse" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(statistics)); } if (clientSideRequestStatistics.getRetryContext().getRetryStartTime() != null) { attributes.put("Retry Context", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getRetryContext())); } counter = 1; for (ClientSideRequestStatistics.AddressResolutionStatistics addressResolutionStatistics : clientSideRequestStatistics.getAddressResolutionStatistics().values()) { attributes.put("AddressResolutionStatistics" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(addressResolutionStatistics)); } if (clientSideRequestStatistics.getSerializationDiagnosticsContext().serializationDiagnosticsList != null) { counter = 1; for (SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics : clientSideRequestStatistics.getSerializationDiagnosticsContext().serializationDiagnosticsList) { attributes = new HashMap<>(); attributes.put("SerializationDiagnostics" + counter++, Utils.getSimpleObjectMapper().writeValueAsString(serializationDiagnostics)); } } if(clientSideRequestStatistics.getGatewayStatistics() != null) { attributes.put("GatewayStatistics", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getGatewayStatistics())); } attributes.put("RegionContacted", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getRegionsContacted())); attributes.put("SystemInformation", Utils.getSimpleObjectMapper().writeValueAsString(ClientSideRequestStatistics.fetchSystemInformation())); attributes.put("ClientCfgs", Utils.getSimpleObjectMapper().writeValueAsString(clientSideRequestStatistics.getDiagnosticsClientContext())); if (clientSideRequestStatistics.getResponseStatisticsList() != null && clientSideRequestStatistics.getResponseStatisticsList().size() > 0 && clientSideRequestStatistics.getResponseStatisticsList().get(0).getStoreResult() != null) { String eventName = "Diagnostics for PKRange " + clientSideRequestStatistics.getResponseStatisticsList().get(0).getStoreResult().partitionKeyRangeId; tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC), parentContext); } else if (clientSideRequestStatistics.getGatewayStatistics() != null) { String eventName = "Diagnostics for PKRange " + clientSideRequestStatistics.getGatewayStatistics().getPartitionKeyRangeId(); tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC), parentContext); } else { String eventName = "Diagnostics " + queryDiagnosticsCounter++; tracerProvider.addEvent(eventName, attributes, OffsetDateTime.ofInstant(clientSideRequestStatistics.getRequestStartTimeUTC(), ZoneOffset.UTC), parentContext); } } } private boolean isTracerEnabled(CosmosPagedFluxOptions pagedFluxOptions) { return pagedFluxOptions.getTracerProvider() != null && pagedFluxOptions.getTracerProvider().isEnabled(); } }
We need both feedrange and rangeId in query metric key , it will be easier to diagnose issue for On call, discussed with @mbhaskar please check this comment #22202 (comment)
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); if (StringUtils.isEmpty(pkrId)) { pkrId = "0"; } String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } }
pkrId = "0";
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } }
We need both feedrange and rangeId in query metric key , it will be easier to diagnose issue for On call, discussed with @mbhaskar please check this comment #22202 (comment)
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); if (StringUtils.isEmpty(pkrId)) { pkrId = "0"; } String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } }
String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID);
void populatePartitionedQueryMetrics() { String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { queryMetricsDelimitedString += String.format(Locale.ROOT, ";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); ImmutablePair<String, SchedulingTimeSpan> schedulingTimeSpanMap = new ImmutablePair<>(feedRange.getRange().toString(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, pageResult.getRequestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) ), pageResult.getActivityId()); String pkrId = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID); String queryMetricKey = feedRange.getRange().toString() + ",pkrId:" + pkrId; BridgeInternal.putQueryMetricsIntoMap(pageResult, queryMetricKey, qm); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } }
class DocumentProducerFeedResponse { FeedResponse<T> pageResult; FeedRangeEpkImpl sourceFeedRange; DocumentProducerFeedResponse(FeedResponse<T> pageResult) { this.pageResult = pageResult; this.sourceFeedRange = DocumentProducer.this.feedRange; populatePartitionedQueryMetrics(); } DocumentProducerFeedResponse(FeedResponse<T> pageResult, FeedRange feedRange) { this.pageResult = pageResult; this.sourceFeedRange = (FeedRangeEpkImpl) feedRange; populatePartitionedQueryMetrics(); } }
How much data does this buffer at a time? Just chunkSize?
public Mono<Response<PathInfo>> uploadWithResponse(FileParallelUploadOptions options) { try { StorageImplUtils.assertNotNull("options", options); DataLakeRequestConditions validatedRequestConditions = options.getRequestConditions() == null ? new DataLakeRequestConditions() : options.getRequestConditions(); /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions validatedParallelTransferOptions = ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions()); long fileOffset = 0; Function<Flux<ByteBuffer>, Mono<Response<PathInfo>>> uploadInChunksFunction = (stream) -> uploadInChunks(stream, fileOffset, validatedParallelTransferOptions, options.getHeaders(), validatedUploadRequestConditions); BiFunction<Flux<ByteBuffer>, Long, Mono<Response<PathInfo>>> uploadFullMethod = (stream, length) -> uploadWithResponse(ProgressReporter .addProgressReporting(stream, validatedParallelTransferOptions.getProgressReceiver()), fileOffset, length, options.getHeaders(), validatedUploadRequestConditions); Flux<ByteBuffer> data = options.getDataFlux(); if (data == null && options.getLength() == -1) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize); } else if (data == null) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = Utility.convertStreamToByteBuffer( options.getDataStream(), options.getLength(), chunkSize, false); } return createWithResponse(options.getPermissions(), options.getUmask(), options.getHeaders(), options.getMetadata(), validatedRequestConditions) .then(UploadUtils.uploadFullOrChunked(data, validatedParallelTransferOptions, uploadInChunksFunction, uploadFullMethod)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize);
new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return overwriteCheck .then(uploadWithResponse(data, parallelTransferOptions, null, null, requestConditions)) .flatMap(FluxUtil::toMono); } /** * Creates a new file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions
class DataLakeFileAsyncClient extends DataLakePathAsyncClient { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ static final long MAX_APPEND_FILE_BYTES = 4000L * Constants.MB; private final ClientLogger logger = new ClientLogger(DataLakeFileAsyncClient.class); /** * Package-private constructor for use by {@link DataLakePathClientBuilder}. * * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param fileSystemName The file system name. * @param fileName The file name. * @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient} */ DataLakeFileAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion, String accountName, String fileSystemName, String fileName, BlockBlobAsyncClient blockBlobAsyncClient) { super(pipeline, url, serviceVersion, accountName, fileSystemName, fileName, PathResourceType.FILE, blockBlobAsyncClient); } DataLakeFileAsyncClient(DataLakePathAsyncClient pathAsyncClient) { super(pathAsyncClient.getHttpPipeline(), pathAsyncClient.getAccountUrl(), pathAsyncClient.getServiceVersion(), pathAsyncClient.getAccountName(), pathAsyncClient.getFileSystemName(), Utility.urlEncode(pathAsyncClient.pathName), PathResourceType.FILE, pathAsyncClient.getBlockBlobAsyncClient()); } /** * Gets the URL of the file represented by this client on the Data Lake service. * * @return the URL. */ public String getFileUrl() { return getPathUrl(); } /** * Gets the path of this file, not including the name of the resource itself. * * @return The path of the file. */ public String getFilePath() { return getObjectPath(); } /** * Gets the name of this file, not including its full path. * * @return The name of the file. */ public String getFileName() { return getObjectName(); } /** * Deletes a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.delete} * * <p>For more information see the * <a href="https: * Docs</a></p> * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { try { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.deleteWithResponse * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param requestConditions {@link DataLakeRequestConditions} * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse(DataLakeRequestConditions requestConditions) { try { return withContext(context -> deleteWithResponse(null /* recursive */, requestConditions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file and uploads content. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.upload * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions) { return upload(data, parallelTransferOptions, false); } /** * Creates a new file and uploads content. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.upload * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @param overwrite Whether or not to overwrite, should the file already exist. * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, boolean overwrite) { Mono<Void> overwriteCheck; DataLakeRequestConditions requestConditions; if (overwrite) { overwriteCheck = Mono.empty(); requestConditions = null; } else { overwriteCheck = exists().flatMap(exists -> exists ? monoError(logger, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS)) : Mono.empty()); requestConditions = . * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * <p><strong>Using Progress Reporting</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> uploadWithResponse(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { try { return uploadWithResponse(new FileParallelUploadOptions(data) .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) .setRequestConditions(requestConditions)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * <p><strong>Using Progress Reporting</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * @param options {@link FileParallelUploadOptions} * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> uploadWithResponse(FileParallelUploadOptions options) { try { StorageImplUtils.assertNotNull("options", options); DataLakeRequestConditions validatedRequestConditions = options.getRequestConditions() == null ? new DataLakeRequestConditions() : options.getRequestConditions(); /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions validatedParallelTransferOptions = ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions()); long fileOffset = 0; Function<Flux<ByteBuffer>, Mono<Response<PathInfo>>> uploadInChunksFunction = (stream) -> uploadInChunks(stream, fileOffset, validatedParallelTransferOptions, options.getHeaders(), validatedUploadRequestConditions); BiFunction<Flux<ByteBuffer>, Long, Mono<Response<PathInfo>>> uploadFullMethod = (stream, length) -> uploadWithResponse(ProgressReporter .addProgressReporting(stream, validatedParallelTransferOptions.getProgressReceiver()), fileOffset, length, options.getHeaders(), validatedUploadRequestConditions); Flux<ByteBuffer> data = options.getDataFlux(); if (data == null && options.getLength() == -1) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize); } else if (data == null) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = Utility.convertStreamToByteBuffer( options.getDataStream(), options.getLength(), chunkSize, false); } return createWithResponse(options.getPermissions(), options.getUmask(), options.getHeaders(), options.getMetadata(), validatedRequestConditions) .then(UploadUtils.uploadFullOrChunked(data, validatedParallelTransferOptions, uploadInChunksFunction, uploadFullMethod)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Mono<Response<PathInfo>> uploadInChunks(Flux<ByteBuffer> data, long fileOffset, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { AtomicLong totalProgress = new AtomicLong(); Lock progressLock = new ReentrantLock(); BufferStagingArea stagingArea = new BufferStagingArea(parallelTransferOptions.getBlockSizeLong(), MAX_APPEND_FILE_BYTES); Flux<ByteBuffer> chunkedSource = UploadUtils.chunkSource(data, parallelTransferOptions); /* Write to the stagingArea and upload the output. maxConcurrency = 1 when writing means only 1 BufferAggregator will be accumulating at a time. parallelTransferOptions.getMaxConcurrency() appends will be happening at once, so we guarantee buffering of only concurrency + 1 chunks at a time. */ return chunkedSource.flatMapSequential(stagingArea::write, 1) .concatWith(Flux.defer(stagingArea::flush)) /* Map the data to a tuple 3, of buffer, buffer length, buffer offset */ .map(bufferAggregator -> Tuples.of(bufferAggregator, bufferAggregator.length(), 0L)) /* Scan reduces a flux with an accumulator while emitting the intermediate results. */ /* As an example, data consists of ByteBuffers of length 10-10-5. In the map above we transform the initial ByteBuffer to a tuple3 of buff, 10, 0. Scan will emit that as is, then accumulate the tuple for the next emission. On the second iteration, the middle ByteBuffer gets transformed to buff, 10, 10+0 (from previous emission). Scan emits that, and on the last iteration, the last ByteBuffer gets transformed to buff, 5, 10+10 (from previous emission). */ .scan((result, source) -> { BufferAggregator bufferAggregator = source.getT1(); long currentBufferLength = bufferAggregator.length(); long lastBytesWritten = result.getT2(); long lastOffset = result.getT3(); return Tuples.of(bufferAggregator, currentBufferLength, lastBytesWritten + lastOffset); }) .flatMapSequential(tuple3 -> { BufferAggregator bufferAggregator = tuple3.getT1(); long currentBufferLength = bufferAggregator.length(); long currentOffset = tuple3.getT3() + fileOffset; Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting( bufferAggregator.asFlux(), parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); final long offset = currentBufferLength + currentOffset; return appendWithResponse(progressData, currentOffset, currentBufferLength, null, requestConditions.getLeaseId()) .map(resp -> offset) /* End of file after append to pass to flush. */ .flux(); }, parallelTransferOptions.getMaxConcurrency()) .last() .flatMap(length -> flushWithResponse(length, false, false, httpHeaders, requestConditions)); } private Mono<Response<PathInfo>> uploadWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { return appendWithResponse(data, fileOffset, length, null, requestConditions.getLeaseId()) .flatMap(resp -> flushWithResponse(fileOffset + length, false, false, httpHeaders, requestConditions)); } /** * Creates a new file, with the content of the specified file. By default this method will not overwrite an * existing file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath) { try { return uploadFromFile(filePath, false); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file, with the content of the specified file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @param overwrite Whether or not to overwrite, should the file already exist. * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath, boolean overwrite) { try { Mono<Void> overwriteCheck = Mono.empty(); DataLakeRequestConditions requestConditions = null; if (!overwrite) { if (UploadUtils.shouldUploadInChunks(filePath, DataLakeFileAsyncClient.MAX_APPEND_FILE_BYTES, logger)) { overwriteCheck = exists().flatMap(exists -> exists ? monoError(logger, new IllegalArgumentException(Constants.FILE_ALREADY_EXISTS)) : Mono.empty()); } requestConditions = new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return overwriteCheck.then(uploadFromFile(filePath, null, null, null, requestConditions)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file, with the content of the specified file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @param parallelTransferOptions {@link ParallelTransferOptions} to use to upload from file. Number of parallel * transfers parameter is ignored. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { Long originalBlockSize = (parallelTransferOptions == null) ? null : parallelTransferOptions.getBlockSizeLong(); DataLakeRequestConditions validatedRequestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so e remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions finalParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); long fileOffset = 0; try { return Mono.using(() -> UploadUtils.uploadFileResourceSupplier(filePath, logger), channel -> { try { long fileSize = channel.size(); if (fileSize == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Size of the file must be " + "greater than 0.")); } if (UploadUtils.shouldUploadInChunks(filePath, finalParallelTransferOptions.getMaxSingleUploadSizeLong(), logger)) { return createWithResponse(null, null, headers, metadata, validatedRequestConditions) .then(uploadFileChunks(fileOffset, fileSize, finalParallelTransferOptions, originalBlockSize, headers, validatedUploadRequestConditions, channel)); } else { return createWithResponse(null, null, headers, metadata, validatedRequestConditions) .then(uploadWithResponse(FluxUtil.readFile(channel), fileOffset, fileSize, headers, validatedUploadRequestConditions)) .then(); } } catch (IOException ex) { return Mono.error(ex); } }, channel -> UploadUtils.uploadFileCleanup(channel, logger)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Mono<Void> uploadFileChunks(long fileOffset, long fileSize, ParallelTransferOptions parallelTransferOptions, Long originalBlockSize, PathHttpHeaders headers, DataLakeRequestConditions requestConditions, AsynchronousFileChannel channel) { AtomicLong totalProgress = new AtomicLong(); Lock progressLock = new ReentrantLock(); return Flux.fromIterable(sliceFile(fileSize, originalBlockSize, parallelTransferOptions.getBlockSizeLong())) .flatMap(chunk -> { Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting( FluxUtil.readFile(channel, chunk.getOffset(), chunk.getCount()), parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); return appendWithResponse(progressData, fileOffset + chunk.getOffset(), chunk.getCount(), null, requestConditions.getLeaseId()); }, parallelTransferOptions.getMaxConcurrency()) .then(Mono.defer(() -> flushWithResponse(fileSize, false, false, headers, requestConditions))) .then(); } private List<FileRange> sliceFile(long fileSize, Long originalBlockSize, long blockSize) { List<FileRange> ranges = new ArrayList<>(); if (fileSize > 100 * Constants.MB && originalBlockSize == null) { blockSize = BlobAsyncClient.BLOB_DEFAULT_HTBB_UPLOAD_BLOCK_SIZE; } for (long pos = 0; pos < fileSize; pos += blockSize) { long count = blockSize; if (pos + count > fileSize) { count = fileSize - pos; } ranges.add(new FileRange(pos, count)); } return ranges; } /** * Appends data to the specified resource to later be flushed (written) by a call to flush * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.append * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param data The data to write to the file. * @param fileOffset The position where the data is to be appended. * @param length The exact length of the data. It is important that this value match precisely the length of the * data emitted by the {@code Flux}. * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> append(Flux<ByteBuffer> data, long fileOffset, long length) { try { return appendWithResponse(data, fileOffset, length, null, null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Appends data to the specified resource to later be flushed (written) by a call to flush * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.appendWithResponse * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param data The data to write to the file. * @param fileOffset The position where the data is to be appended. * @param length The exact length of the data. It is important that this value match precisely the length of the * data emitted by the {@code Flux}. * @param contentMd5 An MD5 hash of the content of the data. If specified, the service will calculate the MD5 of the * received data and fail the request if it does not match the provided MD5. * @param leaseId By setting lease id, requests will fail if the provided lease does not match the active lease on * the file. * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> appendWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, byte[] contentMd5, String leaseId) { try { return withContext(context -> appendWithResponse(data, fileOffset, length, contentMd5, leaseId, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> appendWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, byte[] contentMd5, String leaseId, Context context) { LeaseAccessConditions leaseAccessConditions = new LeaseAccessConditions().setLeaseId(leaseId); PathHttpHeaders headers = new PathHttpHeaders().setTransactionalContentHash(contentMd5); return this.dataLakeStorage.getPaths().appendDataWithResponseAsync(data, fileOffset, null, length, null, null, headers, leaseAccessConditions, context).map(response -> new SimpleResponse<>(response, null)); } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * <p>By default this method will not overwrite existing data.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flush * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> flush(long position) { try { return flush(position, false); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flush * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * @param overwrite Whether or not to overwrite, should data exist on the file. * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> flush(long position, boolean overwrite) { try { DataLakeRequestConditions requestConditions = null; if (!overwrite) { requestConditions = new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return flushWithResponse(position, false, false, null, requestConditions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flushWithResponse * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * @param retainUncommittedData Whether or not uncommitted data is to be retained after the operation. * @param close Whether or not a file changed event raised indicates completion (true) or modification (false). * @param httpHeaders {@link PathHttpHeaders httpHeaders} * @param requestConditions {@link DataLakeRequestConditions requestConditions} * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> flushWithResponse(long position, boolean retainUncommittedData, boolean close, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { try { return withContext(context -> flushWithResponse(position, retainUncommittedData, close, httpHeaders, requestConditions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<PathInfo>> flushWithResponse(long position, boolean retainUncommittedData, boolean close, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions, Context context) { httpHeaders = httpHeaders == null ? new PathHttpHeaders() : httpHeaders; requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().flushDataWithResponseAsync(null, position, retainUncommittedData, close, (long) 0, null, httpHeaders, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathInfo(response.getDeserializedHeaders().getETag(), response.getDeserializedHeaders().getLastModified()))); } /** * Reads the entire file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.read} * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the file data. */ public Flux<ByteBuffer> read() { try { return readWithResponse(null, null, null, false) .flatMapMany(FileReadAsyncResponse::getValue); } catch (RuntimeException ex) { return fluxError(logger, ex); } } /** * Reads a range of bytes from a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readWithResponse * * <p>For more information, see the * <a href="https: * * @param range {@link FileRange} * @param options {@link DownloadRetryOptions} * @param requestConditions {@link DataLakeRequestConditions} * @param getRangeContentMd5 Whether the contentMD5 for the specified file range should be returned. * @return A reactive response containing the file data. */ public Mono<FileReadAsyncResponse> readWithResponse(FileRange range, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean getRangeContentMd5) { try { return blockBlobAsyncClient.downloadWithResponse(Transforms.toBlobRange(range), Transforms.toBlobDownloadRetryOptions(options), Transforms.toBlobRequestConditions(requestConditions), getRangeContentMd5).map(Transforms::toFileReadAsyncResponse) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Reads the entire file into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @return A reactive response containing the file properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> readToFile(String filePath) { return readToFile(filePath, false); } /** * Reads the entire file into a file specified by the path. * * <p>If overwrite is set to false, the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param overwrite Whether or not to overwrite the file, should the file exist. * @return A reactive response containing the file properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> readToFile(String filePath, boolean overwrite) { Set<OpenOption> openOptions = null; if (overwrite) { openOptions = new HashSet<>(); openOptions.add(StandardOpenOption.CREATE); openOptions.add(StandardOpenOption.TRUNCATE_EXISTING); openOptions.add(StandardOpenOption.READ); openOptions.add(StandardOpenOption.WRITE); } return readToFileWithResponse(filePath, null, null, null, null, false, openOptions) .flatMap(FluxUtil::toMono); } /** * Reads the entire file into a file specified by the path. * * <p>By default the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate * {@link OpenOption OpenOptions} </p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param range {@link FileRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param options {@link DownloadRetryOptions} * @param requestConditions {@link DataLakeRequestConditions} * @param rangeGetContentMd5 Whether the contentMD5 for the specified file range should be returned. * @param openOptions {@link OpenOption OpenOptions} to use to configure how to open or create the file. * @return A reactive response containing the file properties and metadata. * @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathProperties>> readToFileWithResponse(String filePath, FileRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean rangeGetContentMd5, Set<OpenOption> openOptions) { return blockBlobAsyncClient.downloadToFileWithResponse(new BlobDownloadToFileOptions(filePath) .setRange(Transforms.toBlobRange(range)).setParallelTransferOptions(parallelTransferOptions) .setDownloadRetryOptions(Transforms.toBlobDownloadRetryOptions(options)) .setRequestConditions(Transforms.toBlobRequestConditions(requestConditions)) .setRetrieveContentRangeMd5(rangeGetContentMd5).setOpenOptions(openOptions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException) .map(response -> new SimpleResponse<>(response, Transforms.toPathProperties(response.getValue()))); } /** * Moves the file to another location within the file system. * For more information see the * <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.rename * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath Relative path from the file system to rename the file to, excludes the file system name. * For example if you want to move a file with fileSystem = "myfilesystem", path = "mydir/hello.txt" to another path * in myfilesystem (ex: newdir/hi.txt) then set the destinationPath = "newdir/hi.txt" * @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the new file created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DataLakeFileAsyncClient> rename(String destinationFileSystem, String destinationPath) { try { return renameWithResponse(destinationFileSystem, destinationPath, null, null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Moves the file to another location within the file system. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.renameWithResponse * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath Relative path from the file system to rename the file to, excludes the file system name. * For example if you want to move a file with fileSystem = "myfilesystem", path = "mydir/hello.txt" to another path * in myfilesystem (ex: newdir/hi.txt) then set the destinationPath = "newdir/hi.txt" * @param sourceRequestConditions {@link DataLakeRequestConditions} against the source. * @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DataLakeFileAsyncClient} used to interact with the file created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DataLakeFileAsyncClient>> renameWithResponse(String destinationFileSystem, String destinationPath, DataLakeRequestConditions sourceRequestConditions, DataLakeRequestConditions destinationRequestConditions) { try { return withContext(context -> renameWithResponse(destinationFileSystem, destinationPath, sourceRequestConditions, destinationRequestConditions, context)) .map(response -> new SimpleResponse<>(response, new DataLakeFileAsyncClient(response.getValue()))); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Queries the entire file. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.query * * @param expression The query expression. * @return A reactive response containing the queried data. */ public Flux<ByteBuffer> query(String expression) { return queryWithResponse(new FileQueryOptions(expression)) .flatMapMany(FileQueryAsyncResponse::getValue); } /** * Queries the entire file. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.queryWithResponse * * @param queryOptions {@link FileQueryOptions The query options} * @return A reactive response containing the queried data. */ public Mono<FileQueryAsyncResponse> queryWithResponse(FileQueryOptions queryOptions) { return blockBlobAsyncClient.queryWithResponse(Transforms.toBlobQueryOptions(queryOptions)) .map(Transforms::toFileQueryAsyncResponse) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Schedules the file for deletion. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.scheduleDeletion * * @param options Schedule deletion parameters. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> scheduleDeletion(FileScheduleDeletionOptions options) { return scheduleDeletionWithResponse(options).flatMap(FluxUtil::toMono); } /** * Schedules the file for deletion. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.scheduleDeletionWithResponse * * @param options Schedule deletion parameters. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> scheduleDeletionWithResponse(FileScheduleDeletionOptions options) { try { return withContext(context -> scheduleDeletionWithResponse(options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> scheduleDeletionWithResponse(FileScheduleDeletionOptions options, Context context) { PathExpiryOptions pathExpiryOptions; context = context == null ? Context.NONE : context; String expiresOn = null; if (options != null && options.getExpiresOn() != null) { pathExpiryOptions = PathExpiryOptions.ABSOLUTE; expiresOn = new DateTimeRfc1123(options.getExpiresOn()).toString(); } else if (options != null && options.getTimeToExpire() != null) { if (options.getExpiryRelativeTo() == FileExpirationOffset.CREATION_TIME) { pathExpiryOptions = PathExpiryOptions.RELATIVE_TO_CREATION; } else { pathExpiryOptions = PathExpiryOptions.RELATIVE_TO_NOW; } expiresOn = Long.toString(options.getTimeToExpire().toMillis()); } else { pathExpiryOptions = PathExpiryOptions.NEVER_EXPIRE; } return this.blobDataLakeStorage.getPaths().setExpiryWithResponseAsync( pathExpiryOptions, null, null, expiresOn, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, null)); } }
class DataLakeFileAsyncClient extends DataLakePathAsyncClient { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ static final long MAX_APPEND_FILE_BYTES = 4000L * Constants.MB; private final ClientLogger logger = new ClientLogger(DataLakeFileAsyncClient.class); /** * Package-private constructor for use by {@link DataLakePathClientBuilder}. * * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param fileSystemName The file system name. * @param fileName The file name. * @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient} */ DataLakeFileAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion, String accountName, String fileSystemName, String fileName, BlockBlobAsyncClient blockBlobAsyncClient) { super(pipeline, url, serviceVersion, accountName, fileSystemName, fileName, PathResourceType.FILE, blockBlobAsyncClient); } DataLakeFileAsyncClient(DataLakePathAsyncClient pathAsyncClient) { super(pathAsyncClient.getHttpPipeline(), pathAsyncClient.getAccountUrl(), pathAsyncClient.getServiceVersion(), pathAsyncClient.getAccountName(), pathAsyncClient.getFileSystemName(), Utility.urlEncode(pathAsyncClient.pathName), PathResourceType.FILE, pathAsyncClient.getBlockBlobAsyncClient()); } /** * Gets the URL of the file represented by this client on the Data Lake service. * * @return the URL. */ public String getFileUrl() { return getPathUrl(); } /** * Gets the path of this file, not including the name of the resource itself. * * @return The path of the file. */ public String getFilePath() { return getObjectPath(); } /** * Gets the name of this file, not including its full path. * * @return The name of the file. */ public String getFileName() { return getObjectName(); } /** * Deletes a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.delete} * * <p>For more information see the * <a href="https: * Docs</a></p> * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { try { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.deleteWithResponse * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param requestConditions {@link DataLakeRequestConditions} * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse(DataLakeRequestConditions requestConditions) { try { return withContext(context -> deleteWithResponse(null /* recursive */, requestConditions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file and uploads content. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.upload * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions) { return upload(data, parallelTransferOptions, false); } /** * Creates a new file and uploads content. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.upload * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @param overwrite Whether or not to overwrite, should the file already exist. * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, boolean overwrite) { Mono<Void> overwriteCheck; DataLakeRequestConditions requestConditions; if (overwrite) { overwriteCheck = Mono.empty(); requestConditions = null; } else { overwriteCheck = exists().flatMap(exists -> exists ? monoError(logger, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS)) : Mono.empty()); requestConditions = . * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * <p><strong>Using Progress Reporting</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> uploadWithResponse(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { try { return uploadWithResponse(new FileParallelUploadOptions(data) .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) .setRequestConditions(requestConditions)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * <p><strong>Using Progress Reporting</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * @param options {@link FileParallelUploadOptions} * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> uploadWithResponse(FileParallelUploadOptions options) { try { StorageImplUtils.assertNotNull("options", options); DataLakeRequestConditions validatedRequestConditions = options.getRequestConditions() == null ? new DataLakeRequestConditions() : options.getRequestConditions(); /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions validatedParallelTransferOptions = ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions()); long fileOffset = 0; Function<Flux<ByteBuffer>, Mono<Response<PathInfo>>> uploadInChunksFunction = (stream) -> uploadInChunks(stream, fileOffset, validatedParallelTransferOptions, options.getHeaders(), validatedUploadRequestConditions); BiFunction<Flux<ByteBuffer>, Long, Mono<Response<PathInfo>>> uploadFullMethod = (stream, length) -> uploadWithResponse(ProgressReporter .addProgressReporting(stream, validatedParallelTransferOptions.getProgressReceiver()), fileOffset, length, options.getHeaders(), validatedUploadRequestConditions); Flux<ByteBuffer> data = options.getDataFlux(); if (data == null && options.getOptionalLength() == null) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize); } else if (data == null) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = Utility.convertStreamToByteBuffer( options.getDataStream(), options.getOptionalLength(), chunkSize, false); } return createWithResponse(options.getPermissions(), options.getUmask(), options.getHeaders(), options.getMetadata(), validatedRequestConditions) .then(UploadUtils.uploadFullOrChunked(data, validatedParallelTransferOptions, uploadInChunksFunction, uploadFullMethod)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Mono<Response<PathInfo>> uploadInChunks(Flux<ByteBuffer> data, long fileOffset, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { AtomicLong totalProgress = new AtomicLong(); Lock progressLock = new ReentrantLock(); BufferStagingArea stagingArea = new BufferStagingArea(parallelTransferOptions.getBlockSizeLong(), MAX_APPEND_FILE_BYTES); Flux<ByteBuffer> chunkedSource = UploadUtils.chunkSource(data, parallelTransferOptions); /* Write to the stagingArea and upload the output. maxConcurrency = 1 when writing means only 1 BufferAggregator will be accumulating at a time. parallelTransferOptions.getMaxConcurrency() appends will be happening at once, so we guarantee buffering of only concurrency + 1 chunks at a time. */ return chunkedSource.flatMapSequential(stagingArea::write, 1) .concatWith(Flux.defer(stagingArea::flush)) /* Map the data to a tuple 3, of buffer, buffer length, buffer offset */ .map(bufferAggregator -> Tuples.of(bufferAggregator, bufferAggregator.length(), 0L)) /* Scan reduces a flux with an accumulator while emitting the intermediate results. */ /* As an example, data consists of ByteBuffers of length 10-10-5. In the map above we transform the initial ByteBuffer to a tuple3 of buff, 10, 0. Scan will emit that as is, then accumulate the tuple for the next emission. On the second iteration, the middle ByteBuffer gets transformed to buff, 10, 10+0 (from previous emission). Scan emits that, and on the last iteration, the last ByteBuffer gets transformed to buff, 5, 10+10 (from previous emission). */ .scan((result, source) -> { BufferAggregator bufferAggregator = source.getT1(); long currentBufferLength = bufferAggregator.length(); long lastBytesWritten = result.getT2(); long lastOffset = result.getT3(); return Tuples.of(bufferAggregator, currentBufferLength, lastBytesWritten + lastOffset); }) .flatMapSequential(tuple3 -> { BufferAggregator bufferAggregator = tuple3.getT1(); long currentBufferLength = bufferAggregator.length(); long currentOffset = tuple3.getT3() + fileOffset; Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting( bufferAggregator.asFlux(), parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); final long offset = currentBufferLength + currentOffset; return appendWithResponse(progressData, currentOffset, currentBufferLength, null, requestConditions.getLeaseId()) .map(resp -> offset) /* End of file after append to pass to flush. */ .flux(); }, parallelTransferOptions.getMaxConcurrency()) .last() .flatMap(length -> flushWithResponse(length, false, false, httpHeaders, requestConditions)); } private Mono<Response<PathInfo>> uploadWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { return appendWithResponse(data, fileOffset, length, null, requestConditions.getLeaseId()) .flatMap(resp -> flushWithResponse(fileOffset + length, false, false, httpHeaders, requestConditions)); } /** * Creates a new file, with the content of the specified file. By default this method will not overwrite an * existing file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath) { try { return uploadFromFile(filePath, false); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file, with the content of the specified file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @param overwrite Whether or not to overwrite, should the file already exist. * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath, boolean overwrite) { try { Mono<Void> overwriteCheck = Mono.empty(); DataLakeRequestConditions requestConditions = null; if (!overwrite) { if (UploadUtils.shouldUploadInChunks(filePath, DataLakeFileAsyncClient.MAX_APPEND_FILE_BYTES, logger)) { overwriteCheck = exists().flatMap(exists -> exists ? monoError(logger, new IllegalArgumentException(Constants.FILE_ALREADY_EXISTS)) : Mono.empty()); } requestConditions = new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return overwriteCheck.then(uploadFromFile(filePath, null, null, null, requestConditions)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file, with the content of the specified file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @param parallelTransferOptions {@link ParallelTransferOptions} to use to upload from file. Number of parallel * transfers parameter is ignored. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { Long originalBlockSize = (parallelTransferOptions == null) ? null : parallelTransferOptions.getBlockSizeLong(); DataLakeRequestConditions validatedRequestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so e remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions finalParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); long fileOffset = 0; try { return Mono.using(() -> UploadUtils.uploadFileResourceSupplier(filePath, logger), channel -> { try { long fileSize = channel.size(); if (fileSize == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Size of the file must be " + "greater than 0.")); } if (UploadUtils.shouldUploadInChunks(filePath, finalParallelTransferOptions.getMaxSingleUploadSizeLong(), logger)) { return createWithResponse(null, null, headers, metadata, validatedRequestConditions) .then(uploadFileChunks(fileOffset, fileSize, finalParallelTransferOptions, originalBlockSize, headers, validatedUploadRequestConditions, channel)); } else { return createWithResponse(null, null, headers, metadata, validatedRequestConditions) .then(uploadWithResponse(FluxUtil.readFile(channel), fileOffset, fileSize, headers, validatedUploadRequestConditions)) .then(); } } catch (IOException ex) { return Mono.error(ex); } }, channel -> UploadUtils.uploadFileCleanup(channel, logger)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Mono<Void> uploadFileChunks(long fileOffset, long fileSize, ParallelTransferOptions parallelTransferOptions, Long originalBlockSize, PathHttpHeaders headers, DataLakeRequestConditions requestConditions, AsynchronousFileChannel channel) { AtomicLong totalProgress = new AtomicLong(); Lock progressLock = new ReentrantLock(); return Flux.fromIterable(sliceFile(fileSize, originalBlockSize, parallelTransferOptions.getBlockSizeLong())) .flatMap(chunk -> { Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting( FluxUtil.readFile(channel, chunk.getOffset(), chunk.getCount()), parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); return appendWithResponse(progressData, fileOffset + chunk.getOffset(), chunk.getCount(), null, requestConditions.getLeaseId()); }, parallelTransferOptions.getMaxConcurrency()) .then(Mono.defer(() -> flushWithResponse(fileSize, false, false, headers, requestConditions))) .then(); } private List<FileRange> sliceFile(long fileSize, Long originalBlockSize, long blockSize) { List<FileRange> ranges = new ArrayList<>(); if (fileSize > 100 * Constants.MB && originalBlockSize == null) { blockSize = BlobAsyncClient.BLOB_DEFAULT_HTBB_UPLOAD_BLOCK_SIZE; } for (long pos = 0; pos < fileSize; pos += blockSize) { long count = blockSize; if (pos + count > fileSize) { count = fileSize - pos; } ranges.add(new FileRange(pos, count)); } return ranges; } /** * Appends data to the specified resource to later be flushed (written) by a call to flush * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.append * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param data The data to write to the file. * @param fileOffset The position where the data is to be appended. * @param length The exact length of the data. It is important that this value match precisely the length of the * data emitted by the {@code Flux}. * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> append(Flux<ByteBuffer> data, long fileOffset, long length) { try { return appendWithResponse(data, fileOffset, length, null, null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Appends data to the specified resource to later be flushed (written) by a call to flush * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.appendWithResponse * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param data The data to write to the file. * @param fileOffset The position where the data is to be appended. * @param length The exact length of the data. It is important that this value match precisely the length of the * data emitted by the {@code Flux}. * @param contentMd5 An MD5 hash of the content of the data. If specified, the service will calculate the MD5 of the * received data and fail the request if it does not match the provided MD5. * @param leaseId By setting lease id, requests will fail if the provided lease does not match the active lease on * the file. * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> appendWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, byte[] contentMd5, String leaseId) { try { return withContext(context -> appendWithResponse(data, fileOffset, length, contentMd5, leaseId, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> appendWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, byte[] contentMd5, String leaseId, Context context) { LeaseAccessConditions leaseAccessConditions = new LeaseAccessConditions().setLeaseId(leaseId); PathHttpHeaders headers = new PathHttpHeaders().setTransactionalContentHash(contentMd5); return this.dataLakeStorage.getPaths().appendDataWithResponseAsync(data, fileOffset, null, length, null, null, headers, leaseAccessConditions, context).map(response -> new SimpleResponse<>(response, null)); } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * <p>By default this method will not overwrite existing data.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flush * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> flush(long position) { try { return flush(position, false); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flush * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * @param overwrite Whether or not to overwrite, should data exist on the file. * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> flush(long position, boolean overwrite) { try { DataLakeRequestConditions requestConditions = null; if (!overwrite) { requestConditions = new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return flushWithResponse(position, false, false, null, requestConditions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flushWithResponse * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * @param retainUncommittedData Whether or not uncommitted data is to be retained after the operation. * @param close Whether or not a file changed event raised indicates completion (true) or modification (false). * @param httpHeaders {@link PathHttpHeaders httpHeaders} * @param requestConditions {@link DataLakeRequestConditions requestConditions} * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> flushWithResponse(long position, boolean retainUncommittedData, boolean close, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { try { return withContext(context -> flushWithResponse(position, retainUncommittedData, close, httpHeaders, requestConditions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<PathInfo>> flushWithResponse(long position, boolean retainUncommittedData, boolean close, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions, Context context) { httpHeaders = httpHeaders == null ? new PathHttpHeaders() : httpHeaders; requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().flushDataWithResponseAsync(null, position, retainUncommittedData, close, (long) 0, null, httpHeaders, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathInfo(response.getDeserializedHeaders().getETag(), response.getDeserializedHeaders().getLastModified()))); } /** * Reads the entire file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.read} * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the file data. */ public Flux<ByteBuffer> read() { try { return readWithResponse(null, null, null, false) .flatMapMany(FileReadAsyncResponse::getValue); } catch (RuntimeException ex) { return fluxError(logger, ex); } } /** * Reads a range of bytes from a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readWithResponse * * <p>For more information, see the * <a href="https: * * @param range {@link FileRange} * @param options {@link DownloadRetryOptions} * @param requestConditions {@link DataLakeRequestConditions} * @param getRangeContentMd5 Whether the contentMD5 for the specified file range should be returned. * @return A reactive response containing the file data. */ public Mono<FileReadAsyncResponse> readWithResponse(FileRange range, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean getRangeContentMd5) { try { return blockBlobAsyncClient.downloadWithResponse(Transforms.toBlobRange(range), Transforms.toBlobDownloadRetryOptions(options), Transforms.toBlobRequestConditions(requestConditions), getRangeContentMd5).map(Transforms::toFileReadAsyncResponse) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Reads the entire file into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @return A reactive response containing the file properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> readToFile(String filePath) { return readToFile(filePath, false); } /** * Reads the entire file into a file specified by the path. * * <p>If overwrite is set to false, the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param overwrite Whether or not to overwrite the file, should the file exist. * @return A reactive response containing the file properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> readToFile(String filePath, boolean overwrite) { Set<OpenOption> openOptions = null; if (overwrite) { openOptions = new HashSet<>(); openOptions.add(StandardOpenOption.CREATE); openOptions.add(StandardOpenOption.TRUNCATE_EXISTING); openOptions.add(StandardOpenOption.READ); openOptions.add(StandardOpenOption.WRITE); } return readToFileWithResponse(filePath, null, null, null, null, false, openOptions) .flatMap(FluxUtil::toMono); } /** * Reads the entire file into a file specified by the path. * * <p>By default the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate * {@link OpenOption OpenOptions} </p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param range {@link FileRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param options {@link DownloadRetryOptions} * @param requestConditions {@link DataLakeRequestConditions} * @param rangeGetContentMd5 Whether the contentMD5 for the specified file range should be returned. * @param openOptions {@link OpenOption OpenOptions} to use to configure how to open or create the file. * @return A reactive response containing the file properties and metadata. * @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathProperties>> readToFileWithResponse(String filePath, FileRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean rangeGetContentMd5, Set<OpenOption> openOptions) { return blockBlobAsyncClient.downloadToFileWithResponse(new BlobDownloadToFileOptions(filePath) .setRange(Transforms.toBlobRange(range)).setParallelTransferOptions(parallelTransferOptions) .setDownloadRetryOptions(Transforms.toBlobDownloadRetryOptions(options)) .setRequestConditions(Transforms.toBlobRequestConditions(requestConditions)) .setRetrieveContentRangeMd5(rangeGetContentMd5).setOpenOptions(openOptions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException) .map(response -> new SimpleResponse<>(response, Transforms.toPathProperties(response.getValue()))); } /** * Moves the file to another location within the file system. * For more information see the * <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.rename * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath Relative path from the file system to rename the file to, excludes the file system name. * For example if you want to move a file with fileSystem = "myfilesystem", path = "mydir/hello.txt" to another path * in myfilesystem (ex: newdir/hi.txt) then set the destinationPath = "newdir/hi.txt" * @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the new file created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DataLakeFileAsyncClient> rename(String destinationFileSystem, String destinationPath) { try { return renameWithResponse(destinationFileSystem, destinationPath, null, null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Moves the file to another location within the file system. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.renameWithResponse * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath Relative path from the file system to rename the file to, excludes the file system name. * For example if you want to move a file with fileSystem = "myfilesystem", path = "mydir/hello.txt" to another path * in myfilesystem (ex: newdir/hi.txt) then set the destinationPath = "newdir/hi.txt" * @param sourceRequestConditions {@link DataLakeRequestConditions} against the source. * @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DataLakeFileAsyncClient} used to interact with the file created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DataLakeFileAsyncClient>> renameWithResponse(String destinationFileSystem, String destinationPath, DataLakeRequestConditions sourceRequestConditions, DataLakeRequestConditions destinationRequestConditions) { try { return withContext(context -> renameWithResponse(destinationFileSystem, destinationPath, sourceRequestConditions, destinationRequestConditions, context)) .map(response -> new SimpleResponse<>(response, new DataLakeFileAsyncClient(response.getValue()))); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Queries the entire file. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.query * * @param expression The query expression. * @return A reactive response containing the queried data. */ public Flux<ByteBuffer> query(String expression) { return queryWithResponse(new FileQueryOptions(expression)) .flatMapMany(FileQueryAsyncResponse::getValue); } /** * Queries the entire file. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.queryWithResponse * * @param queryOptions {@link FileQueryOptions The query options} * @return A reactive response containing the queried data. */ public Mono<FileQueryAsyncResponse> queryWithResponse(FileQueryOptions queryOptions) { return blockBlobAsyncClient.queryWithResponse(Transforms.toBlobQueryOptions(queryOptions)) .map(Transforms::toFileQueryAsyncResponse) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Schedules the file for deletion. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.scheduleDeletion * * @param options Schedule deletion parameters. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> scheduleDeletion(FileScheduleDeletionOptions options) { return scheduleDeletionWithResponse(options).flatMap(FluxUtil::toMono); } /** * Schedules the file for deletion. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.scheduleDeletionWithResponse * * @param options Schedule deletion parameters. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> scheduleDeletionWithResponse(FileScheduleDeletionOptions options) { try { return withContext(context -> scheduleDeletionWithResponse(options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> scheduleDeletionWithResponse(FileScheduleDeletionOptions options, Context context) { PathExpiryOptions pathExpiryOptions; context = context == null ? Context.NONE : context; String expiresOn = null; if (options != null && options.getExpiresOn() != null) { pathExpiryOptions = PathExpiryOptions.ABSOLUTE; expiresOn = new DateTimeRfc1123(options.getExpiresOn()).toString(); } else if (options != null && options.getTimeToExpire() != null) { if (options.getExpiryRelativeTo() == FileExpirationOffset.CREATION_TIME) { pathExpiryOptions = PathExpiryOptions.RELATIVE_TO_CREATION; } else { pathExpiryOptions = PathExpiryOptions.RELATIVE_TO_NOW; } expiresOn = Long.toString(options.getTimeToExpire().toMillis()); } else { pathExpiryOptions = PathExpiryOptions.NEVER_EXPIRE; } return this.blobDataLakeStorage.getPaths().setExpiryWithResponseAsync( pathExpiryOptions, null, null, expiresOn, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, null)); } }
each bytebuffer will be chunkSize. It already was, I just pulled it into a variable.
public Mono<Response<PathInfo>> uploadWithResponse(FileParallelUploadOptions options) { try { StorageImplUtils.assertNotNull("options", options); DataLakeRequestConditions validatedRequestConditions = options.getRequestConditions() == null ? new DataLakeRequestConditions() : options.getRequestConditions(); /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions validatedParallelTransferOptions = ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions()); long fileOffset = 0; Function<Flux<ByteBuffer>, Mono<Response<PathInfo>>> uploadInChunksFunction = (stream) -> uploadInChunks(stream, fileOffset, validatedParallelTransferOptions, options.getHeaders(), validatedUploadRequestConditions); BiFunction<Flux<ByteBuffer>, Long, Mono<Response<PathInfo>>> uploadFullMethod = (stream, length) -> uploadWithResponse(ProgressReporter .addProgressReporting(stream, validatedParallelTransferOptions.getProgressReceiver()), fileOffset, length, options.getHeaders(), validatedUploadRequestConditions); Flux<ByteBuffer> data = options.getDataFlux(); if (data == null && options.getLength() == -1) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize); } else if (data == null) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = Utility.convertStreamToByteBuffer( options.getDataStream(), options.getLength(), chunkSize, false); } return createWithResponse(options.getPermissions(), options.getUmask(), options.getHeaders(), options.getMetadata(), validatedRequestConditions) .then(UploadUtils.uploadFullOrChunked(data, validatedParallelTransferOptions, uploadInChunksFunction, uploadFullMethod)); } catch (RuntimeException ex) { return monoError(logger, ex); } }
data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize);
new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return overwriteCheck .then(uploadWithResponse(data, parallelTransferOptions, null, null, requestConditions)) .flatMap(FluxUtil::toMono); } /** * Creates a new file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions
class DataLakeFileAsyncClient extends DataLakePathAsyncClient { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ static final long MAX_APPEND_FILE_BYTES = 4000L * Constants.MB; private final ClientLogger logger = new ClientLogger(DataLakeFileAsyncClient.class); /** * Package-private constructor for use by {@link DataLakePathClientBuilder}. * * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param fileSystemName The file system name. * @param fileName The file name. * @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient} */ DataLakeFileAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion, String accountName, String fileSystemName, String fileName, BlockBlobAsyncClient blockBlobAsyncClient) { super(pipeline, url, serviceVersion, accountName, fileSystemName, fileName, PathResourceType.FILE, blockBlobAsyncClient); } DataLakeFileAsyncClient(DataLakePathAsyncClient pathAsyncClient) { super(pathAsyncClient.getHttpPipeline(), pathAsyncClient.getAccountUrl(), pathAsyncClient.getServiceVersion(), pathAsyncClient.getAccountName(), pathAsyncClient.getFileSystemName(), Utility.urlEncode(pathAsyncClient.pathName), PathResourceType.FILE, pathAsyncClient.getBlockBlobAsyncClient()); } /** * Gets the URL of the file represented by this client on the Data Lake service. * * @return the URL. */ public String getFileUrl() { return getPathUrl(); } /** * Gets the path of this file, not including the name of the resource itself. * * @return The path of the file. */ public String getFilePath() { return getObjectPath(); } /** * Gets the name of this file, not including its full path. * * @return The name of the file. */ public String getFileName() { return getObjectName(); } /** * Deletes a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.delete} * * <p>For more information see the * <a href="https: * Docs</a></p> * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { try { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.deleteWithResponse * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param requestConditions {@link DataLakeRequestConditions} * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse(DataLakeRequestConditions requestConditions) { try { return withContext(context -> deleteWithResponse(null /* recursive */, requestConditions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file and uploads content. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.upload * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions) { return upload(data, parallelTransferOptions, false); } /** * Creates a new file and uploads content. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.upload * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @param overwrite Whether or not to overwrite, should the file already exist. * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, boolean overwrite) { Mono<Void> overwriteCheck; DataLakeRequestConditions requestConditions; if (overwrite) { overwriteCheck = Mono.empty(); requestConditions = null; } else { overwriteCheck = exists().flatMap(exists -> exists ? monoError(logger, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS)) : Mono.empty()); requestConditions = . * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * <p><strong>Using Progress Reporting</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> uploadWithResponse(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { try { return uploadWithResponse(new FileParallelUploadOptions(data) .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) .setRequestConditions(requestConditions)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * <p><strong>Using Progress Reporting</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * @param options {@link FileParallelUploadOptions} * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> uploadWithResponse(FileParallelUploadOptions options) { try { StorageImplUtils.assertNotNull("options", options); DataLakeRequestConditions validatedRequestConditions = options.getRequestConditions() == null ? new DataLakeRequestConditions() : options.getRequestConditions(); /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions validatedParallelTransferOptions = ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions()); long fileOffset = 0; Function<Flux<ByteBuffer>, Mono<Response<PathInfo>>> uploadInChunksFunction = (stream) -> uploadInChunks(stream, fileOffset, validatedParallelTransferOptions, options.getHeaders(), validatedUploadRequestConditions); BiFunction<Flux<ByteBuffer>, Long, Mono<Response<PathInfo>>> uploadFullMethod = (stream, length) -> uploadWithResponse(ProgressReporter .addProgressReporting(stream, validatedParallelTransferOptions.getProgressReceiver()), fileOffset, length, options.getHeaders(), validatedUploadRequestConditions); Flux<ByteBuffer> data = options.getDataFlux(); if (data == null && options.getLength() == -1) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize); } else if (data == null) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = Utility.convertStreamToByteBuffer( options.getDataStream(), options.getLength(), chunkSize, false); } return createWithResponse(options.getPermissions(), options.getUmask(), options.getHeaders(), options.getMetadata(), validatedRequestConditions) .then(UploadUtils.uploadFullOrChunked(data, validatedParallelTransferOptions, uploadInChunksFunction, uploadFullMethod)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Mono<Response<PathInfo>> uploadInChunks(Flux<ByteBuffer> data, long fileOffset, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { AtomicLong totalProgress = new AtomicLong(); Lock progressLock = new ReentrantLock(); BufferStagingArea stagingArea = new BufferStagingArea(parallelTransferOptions.getBlockSizeLong(), MAX_APPEND_FILE_BYTES); Flux<ByteBuffer> chunkedSource = UploadUtils.chunkSource(data, parallelTransferOptions); /* Write to the stagingArea and upload the output. maxConcurrency = 1 when writing means only 1 BufferAggregator will be accumulating at a time. parallelTransferOptions.getMaxConcurrency() appends will be happening at once, so we guarantee buffering of only concurrency + 1 chunks at a time. */ return chunkedSource.flatMapSequential(stagingArea::write, 1) .concatWith(Flux.defer(stagingArea::flush)) /* Map the data to a tuple 3, of buffer, buffer length, buffer offset */ .map(bufferAggregator -> Tuples.of(bufferAggregator, bufferAggregator.length(), 0L)) /* Scan reduces a flux with an accumulator while emitting the intermediate results. */ /* As an example, data consists of ByteBuffers of length 10-10-5. In the map above we transform the initial ByteBuffer to a tuple3 of buff, 10, 0. Scan will emit that as is, then accumulate the tuple for the next emission. On the second iteration, the middle ByteBuffer gets transformed to buff, 10, 10+0 (from previous emission). Scan emits that, and on the last iteration, the last ByteBuffer gets transformed to buff, 5, 10+10 (from previous emission). */ .scan((result, source) -> { BufferAggregator bufferAggregator = source.getT1(); long currentBufferLength = bufferAggregator.length(); long lastBytesWritten = result.getT2(); long lastOffset = result.getT3(); return Tuples.of(bufferAggregator, currentBufferLength, lastBytesWritten + lastOffset); }) .flatMapSequential(tuple3 -> { BufferAggregator bufferAggregator = tuple3.getT1(); long currentBufferLength = bufferAggregator.length(); long currentOffset = tuple3.getT3() + fileOffset; Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting( bufferAggregator.asFlux(), parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); final long offset = currentBufferLength + currentOffset; return appendWithResponse(progressData, currentOffset, currentBufferLength, null, requestConditions.getLeaseId()) .map(resp -> offset) /* End of file after append to pass to flush. */ .flux(); }, parallelTransferOptions.getMaxConcurrency()) .last() .flatMap(length -> flushWithResponse(length, false, false, httpHeaders, requestConditions)); } private Mono<Response<PathInfo>> uploadWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { return appendWithResponse(data, fileOffset, length, null, requestConditions.getLeaseId()) .flatMap(resp -> flushWithResponse(fileOffset + length, false, false, httpHeaders, requestConditions)); } /** * Creates a new file, with the content of the specified file. By default this method will not overwrite an * existing file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath) { try { return uploadFromFile(filePath, false); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file, with the content of the specified file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @param overwrite Whether or not to overwrite, should the file already exist. * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath, boolean overwrite) { try { Mono<Void> overwriteCheck = Mono.empty(); DataLakeRequestConditions requestConditions = null; if (!overwrite) { if (UploadUtils.shouldUploadInChunks(filePath, DataLakeFileAsyncClient.MAX_APPEND_FILE_BYTES, logger)) { overwriteCheck = exists().flatMap(exists -> exists ? monoError(logger, new IllegalArgumentException(Constants.FILE_ALREADY_EXISTS)) : Mono.empty()); } requestConditions = new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return overwriteCheck.then(uploadFromFile(filePath, null, null, null, requestConditions)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file, with the content of the specified file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @param parallelTransferOptions {@link ParallelTransferOptions} to use to upload from file. Number of parallel * transfers parameter is ignored. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { Long originalBlockSize = (parallelTransferOptions == null) ? null : parallelTransferOptions.getBlockSizeLong(); DataLakeRequestConditions validatedRequestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so e remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions finalParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); long fileOffset = 0; try { return Mono.using(() -> UploadUtils.uploadFileResourceSupplier(filePath, logger), channel -> { try { long fileSize = channel.size(); if (fileSize == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Size of the file must be " + "greater than 0.")); } if (UploadUtils.shouldUploadInChunks(filePath, finalParallelTransferOptions.getMaxSingleUploadSizeLong(), logger)) { return createWithResponse(null, null, headers, metadata, validatedRequestConditions) .then(uploadFileChunks(fileOffset, fileSize, finalParallelTransferOptions, originalBlockSize, headers, validatedUploadRequestConditions, channel)); } else { return createWithResponse(null, null, headers, metadata, validatedRequestConditions) .then(uploadWithResponse(FluxUtil.readFile(channel), fileOffset, fileSize, headers, validatedUploadRequestConditions)) .then(); } } catch (IOException ex) { return Mono.error(ex); } }, channel -> UploadUtils.uploadFileCleanup(channel, logger)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Mono<Void> uploadFileChunks(long fileOffset, long fileSize, ParallelTransferOptions parallelTransferOptions, Long originalBlockSize, PathHttpHeaders headers, DataLakeRequestConditions requestConditions, AsynchronousFileChannel channel) { AtomicLong totalProgress = new AtomicLong(); Lock progressLock = new ReentrantLock(); return Flux.fromIterable(sliceFile(fileSize, originalBlockSize, parallelTransferOptions.getBlockSizeLong())) .flatMap(chunk -> { Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting( FluxUtil.readFile(channel, chunk.getOffset(), chunk.getCount()), parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); return appendWithResponse(progressData, fileOffset + chunk.getOffset(), chunk.getCount(), null, requestConditions.getLeaseId()); }, parallelTransferOptions.getMaxConcurrency()) .then(Mono.defer(() -> flushWithResponse(fileSize, false, false, headers, requestConditions))) .then(); } private List<FileRange> sliceFile(long fileSize, Long originalBlockSize, long blockSize) { List<FileRange> ranges = new ArrayList<>(); if (fileSize > 100 * Constants.MB && originalBlockSize == null) { blockSize = BlobAsyncClient.BLOB_DEFAULT_HTBB_UPLOAD_BLOCK_SIZE; } for (long pos = 0; pos < fileSize; pos += blockSize) { long count = blockSize; if (pos + count > fileSize) { count = fileSize - pos; } ranges.add(new FileRange(pos, count)); } return ranges; } /** * Appends data to the specified resource to later be flushed (written) by a call to flush * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.append * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param data The data to write to the file. * @param fileOffset The position where the data is to be appended. * @param length The exact length of the data. It is important that this value match precisely the length of the * data emitted by the {@code Flux}. * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> append(Flux<ByteBuffer> data, long fileOffset, long length) { try { return appendWithResponse(data, fileOffset, length, null, null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Appends data to the specified resource to later be flushed (written) by a call to flush * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.appendWithResponse * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param data The data to write to the file. * @param fileOffset The position where the data is to be appended. * @param length The exact length of the data. It is important that this value match precisely the length of the * data emitted by the {@code Flux}. * @param contentMd5 An MD5 hash of the content of the data. If specified, the service will calculate the MD5 of the * received data and fail the request if it does not match the provided MD5. * @param leaseId By setting lease id, requests will fail if the provided lease does not match the active lease on * the file. * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> appendWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, byte[] contentMd5, String leaseId) { try { return withContext(context -> appendWithResponse(data, fileOffset, length, contentMd5, leaseId, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> appendWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, byte[] contentMd5, String leaseId, Context context) { LeaseAccessConditions leaseAccessConditions = new LeaseAccessConditions().setLeaseId(leaseId); PathHttpHeaders headers = new PathHttpHeaders().setTransactionalContentHash(contentMd5); return this.dataLakeStorage.getPaths().appendDataWithResponseAsync(data, fileOffset, null, length, null, null, headers, leaseAccessConditions, context).map(response -> new SimpleResponse<>(response, null)); } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * <p>By default this method will not overwrite existing data.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flush * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> flush(long position) { try { return flush(position, false); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flush * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * @param overwrite Whether or not to overwrite, should data exist on the file. * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> flush(long position, boolean overwrite) { try { DataLakeRequestConditions requestConditions = null; if (!overwrite) { requestConditions = new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return flushWithResponse(position, false, false, null, requestConditions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flushWithResponse * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * @param retainUncommittedData Whether or not uncommitted data is to be retained after the operation. * @param close Whether or not a file changed event raised indicates completion (true) or modification (false). * @param httpHeaders {@link PathHttpHeaders httpHeaders} * @param requestConditions {@link DataLakeRequestConditions requestConditions} * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> flushWithResponse(long position, boolean retainUncommittedData, boolean close, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { try { return withContext(context -> flushWithResponse(position, retainUncommittedData, close, httpHeaders, requestConditions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<PathInfo>> flushWithResponse(long position, boolean retainUncommittedData, boolean close, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions, Context context) { httpHeaders = httpHeaders == null ? new PathHttpHeaders() : httpHeaders; requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().flushDataWithResponseAsync(null, position, retainUncommittedData, close, (long) 0, null, httpHeaders, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathInfo(response.getDeserializedHeaders().getETag(), response.getDeserializedHeaders().getLastModified()))); } /** * Reads the entire file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.read} * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the file data. */ public Flux<ByteBuffer> read() { try { return readWithResponse(null, null, null, false) .flatMapMany(FileReadAsyncResponse::getValue); } catch (RuntimeException ex) { return fluxError(logger, ex); } } /** * Reads a range of bytes from a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readWithResponse * * <p>For more information, see the * <a href="https: * * @param range {@link FileRange} * @param options {@link DownloadRetryOptions} * @param requestConditions {@link DataLakeRequestConditions} * @param getRangeContentMd5 Whether the contentMD5 for the specified file range should be returned. * @return A reactive response containing the file data. */ public Mono<FileReadAsyncResponse> readWithResponse(FileRange range, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean getRangeContentMd5) { try { return blockBlobAsyncClient.downloadWithResponse(Transforms.toBlobRange(range), Transforms.toBlobDownloadRetryOptions(options), Transforms.toBlobRequestConditions(requestConditions), getRangeContentMd5).map(Transforms::toFileReadAsyncResponse) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Reads the entire file into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @return A reactive response containing the file properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> readToFile(String filePath) { return readToFile(filePath, false); } /** * Reads the entire file into a file specified by the path. * * <p>If overwrite is set to false, the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param overwrite Whether or not to overwrite the file, should the file exist. * @return A reactive response containing the file properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> readToFile(String filePath, boolean overwrite) { Set<OpenOption> openOptions = null; if (overwrite) { openOptions = new HashSet<>(); openOptions.add(StandardOpenOption.CREATE); openOptions.add(StandardOpenOption.TRUNCATE_EXISTING); openOptions.add(StandardOpenOption.READ); openOptions.add(StandardOpenOption.WRITE); } return readToFileWithResponse(filePath, null, null, null, null, false, openOptions) .flatMap(FluxUtil::toMono); } /** * Reads the entire file into a file specified by the path. * * <p>By default the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate * {@link OpenOption OpenOptions} </p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param range {@link FileRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param options {@link DownloadRetryOptions} * @param requestConditions {@link DataLakeRequestConditions} * @param rangeGetContentMd5 Whether the contentMD5 for the specified file range should be returned. * @param openOptions {@link OpenOption OpenOptions} to use to configure how to open or create the file. * @return A reactive response containing the file properties and metadata. * @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathProperties>> readToFileWithResponse(String filePath, FileRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean rangeGetContentMd5, Set<OpenOption> openOptions) { return blockBlobAsyncClient.downloadToFileWithResponse(new BlobDownloadToFileOptions(filePath) .setRange(Transforms.toBlobRange(range)).setParallelTransferOptions(parallelTransferOptions) .setDownloadRetryOptions(Transforms.toBlobDownloadRetryOptions(options)) .setRequestConditions(Transforms.toBlobRequestConditions(requestConditions)) .setRetrieveContentRangeMd5(rangeGetContentMd5).setOpenOptions(openOptions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException) .map(response -> new SimpleResponse<>(response, Transforms.toPathProperties(response.getValue()))); } /** * Moves the file to another location within the file system. * For more information see the * <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.rename * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath Relative path from the file system to rename the file to, excludes the file system name. * For example if you want to move a file with fileSystem = "myfilesystem", path = "mydir/hello.txt" to another path * in myfilesystem (ex: newdir/hi.txt) then set the destinationPath = "newdir/hi.txt" * @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the new file created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DataLakeFileAsyncClient> rename(String destinationFileSystem, String destinationPath) { try { return renameWithResponse(destinationFileSystem, destinationPath, null, null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Moves the file to another location within the file system. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.renameWithResponse * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath Relative path from the file system to rename the file to, excludes the file system name. * For example if you want to move a file with fileSystem = "myfilesystem", path = "mydir/hello.txt" to another path * in myfilesystem (ex: newdir/hi.txt) then set the destinationPath = "newdir/hi.txt" * @param sourceRequestConditions {@link DataLakeRequestConditions} against the source. * @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DataLakeFileAsyncClient} used to interact with the file created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DataLakeFileAsyncClient>> renameWithResponse(String destinationFileSystem, String destinationPath, DataLakeRequestConditions sourceRequestConditions, DataLakeRequestConditions destinationRequestConditions) { try { return withContext(context -> renameWithResponse(destinationFileSystem, destinationPath, sourceRequestConditions, destinationRequestConditions, context)) .map(response -> new SimpleResponse<>(response, new DataLakeFileAsyncClient(response.getValue()))); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Queries the entire file. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.query * * @param expression The query expression. * @return A reactive response containing the queried data. */ public Flux<ByteBuffer> query(String expression) { return queryWithResponse(new FileQueryOptions(expression)) .flatMapMany(FileQueryAsyncResponse::getValue); } /** * Queries the entire file. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.queryWithResponse * * @param queryOptions {@link FileQueryOptions The query options} * @return A reactive response containing the queried data. */ public Mono<FileQueryAsyncResponse> queryWithResponse(FileQueryOptions queryOptions) { return blockBlobAsyncClient.queryWithResponse(Transforms.toBlobQueryOptions(queryOptions)) .map(Transforms::toFileQueryAsyncResponse) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Schedules the file for deletion. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.scheduleDeletion * * @param options Schedule deletion parameters. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> scheduleDeletion(FileScheduleDeletionOptions options) { return scheduleDeletionWithResponse(options).flatMap(FluxUtil::toMono); } /** * Schedules the file for deletion. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.scheduleDeletionWithResponse * * @param options Schedule deletion parameters. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> scheduleDeletionWithResponse(FileScheduleDeletionOptions options) { try { return withContext(context -> scheduleDeletionWithResponse(options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> scheduleDeletionWithResponse(FileScheduleDeletionOptions options, Context context) { PathExpiryOptions pathExpiryOptions; context = context == null ? Context.NONE : context; String expiresOn = null; if (options != null && options.getExpiresOn() != null) { pathExpiryOptions = PathExpiryOptions.ABSOLUTE; expiresOn = new DateTimeRfc1123(options.getExpiresOn()).toString(); } else if (options != null && options.getTimeToExpire() != null) { if (options.getExpiryRelativeTo() == FileExpirationOffset.CREATION_TIME) { pathExpiryOptions = PathExpiryOptions.RELATIVE_TO_CREATION; } else { pathExpiryOptions = PathExpiryOptions.RELATIVE_TO_NOW; } expiresOn = Long.toString(options.getTimeToExpire().toMillis()); } else { pathExpiryOptions = PathExpiryOptions.NEVER_EXPIRE; } return this.blobDataLakeStorage.getPaths().setExpiryWithResponseAsync( pathExpiryOptions, null, null, expiresOn, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, null)); } }
class DataLakeFileAsyncClient extends DataLakePathAsyncClient { /** * Indicates the maximum number of bytes that can be sent in a call to upload. */ static final long MAX_APPEND_FILE_BYTES = 4000L * Constants.MB; private final ClientLogger logger = new ClientLogger(DataLakeFileAsyncClient.class); /** * Package-private constructor for use by {@link DataLakePathClientBuilder}. * * @param pipeline The pipeline used to send and receive service requests. * @param url The endpoint where to send service requests. * @param serviceVersion The version of the service to receive requests. * @param accountName The storage account name. * @param fileSystemName The file system name. * @param fileName The file name. * @param blockBlobAsyncClient The underlying {@link BlobContainerAsyncClient} */ DataLakeFileAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion, String accountName, String fileSystemName, String fileName, BlockBlobAsyncClient blockBlobAsyncClient) { super(pipeline, url, serviceVersion, accountName, fileSystemName, fileName, PathResourceType.FILE, blockBlobAsyncClient); } DataLakeFileAsyncClient(DataLakePathAsyncClient pathAsyncClient) { super(pathAsyncClient.getHttpPipeline(), pathAsyncClient.getAccountUrl(), pathAsyncClient.getServiceVersion(), pathAsyncClient.getAccountName(), pathAsyncClient.getFileSystemName(), Utility.urlEncode(pathAsyncClient.pathName), PathResourceType.FILE, pathAsyncClient.getBlockBlobAsyncClient()); } /** * Gets the URL of the file represented by this client on the Data Lake service. * * @return the URL. */ public String getFileUrl() { return getPathUrl(); } /** * Gets the path of this file, not including the name of the resource itself. * * @return The path of the file. */ public String getFilePath() { return getObjectPath(); } /** * Gets the name of this file, not including its full path. * * @return The name of the file. */ public String getFileName() { return getObjectName(); } /** * Deletes a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.delete} * * <p>For more information see the * <a href="https: * Docs</a></p> * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete() { try { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.deleteWithResponse * * <p>For more information see the * <a href="https: * Docs</a></p> * * @param requestConditions {@link DataLakeRequestConditions} * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> deleteWithResponse(DataLakeRequestConditions requestConditions) { try { return withContext(context -> deleteWithResponse(null /* recursive */, requestConditions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file and uploads content. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.upload * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions) { return upload(data, parallelTransferOptions, false); } /** * Creates a new file and uploads content. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.upload * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @param overwrite Whether or not to overwrite, should the file already exist. * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> upload(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, boolean overwrite) { Mono<Void> overwriteCheck; DataLakeRequestConditions requestConditions; if (overwrite) { overwriteCheck = Mono.empty(); requestConditions = null; } else { overwriteCheck = exists().flatMap(exists -> exists ? monoError(logger, new IllegalArgumentException(Constants.BLOB_ALREADY_EXISTS)) : Mono.empty()); requestConditions = . * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * <p><strong>Using Progress Reporting</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * @param data The data to write to the file. Unlike other upload methods, this method does not require that the * {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not expected * to produce the same values across subscriptions. * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> uploadWithResponse(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { try { return uploadWithResponse(new FileParallelUploadOptions(data) .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) .setRequestConditions(requestConditions)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * <p><strong>Using Progress Reporting</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadWithResponse * * @param options {@link FileParallelUploadOptions} * @return A reactive response containing the information of the uploaded file. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> uploadWithResponse(FileParallelUploadOptions options) { try { StorageImplUtils.assertNotNull("options", options); DataLakeRequestConditions validatedRequestConditions = options.getRequestConditions() == null ? new DataLakeRequestConditions() : options.getRequestConditions(); /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions validatedParallelTransferOptions = ModelHelper.populateAndApplyDefaults(options.getParallelTransferOptions()); long fileOffset = 0; Function<Flux<ByteBuffer>, Mono<Response<PathInfo>>> uploadInChunksFunction = (stream) -> uploadInChunks(stream, fileOffset, validatedParallelTransferOptions, options.getHeaders(), validatedUploadRequestConditions); BiFunction<Flux<ByteBuffer>, Long, Mono<Response<PathInfo>>> uploadFullMethod = (stream, length) -> uploadWithResponse(ProgressReporter .addProgressReporting(stream, validatedParallelTransferOptions.getProgressReceiver()), fileOffset, length, options.getHeaders(), validatedUploadRequestConditions); Flux<ByteBuffer> data = options.getDataFlux(); if (data == null && options.getOptionalLength() == null) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = FluxUtil.toFluxByteBuffer(options.getDataStream(), chunkSize); } else if (data == null) { int chunkSize = (int) Math.min(Integer.MAX_VALUE, validatedParallelTransferOptions.getBlockSizeLong()); data = Utility.convertStreamToByteBuffer( options.getDataStream(), options.getOptionalLength(), chunkSize, false); } return createWithResponse(options.getPermissions(), options.getUmask(), options.getHeaders(), options.getMetadata(), validatedRequestConditions) .then(UploadUtils.uploadFullOrChunked(data, validatedParallelTransferOptions, uploadInChunksFunction, uploadFullMethod)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Mono<Response<PathInfo>> uploadInChunks(Flux<ByteBuffer> data, long fileOffset, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { AtomicLong totalProgress = new AtomicLong(); Lock progressLock = new ReentrantLock(); BufferStagingArea stagingArea = new BufferStagingArea(parallelTransferOptions.getBlockSizeLong(), MAX_APPEND_FILE_BYTES); Flux<ByteBuffer> chunkedSource = UploadUtils.chunkSource(data, parallelTransferOptions); /* Write to the stagingArea and upload the output. maxConcurrency = 1 when writing means only 1 BufferAggregator will be accumulating at a time. parallelTransferOptions.getMaxConcurrency() appends will be happening at once, so we guarantee buffering of only concurrency + 1 chunks at a time. */ return chunkedSource.flatMapSequential(stagingArea::write, 1) .concatWith(Flux.defer(stagingArea::flush)) /* Map the data to a tuple 3, of buffer, buffer length, buffer offset */ .map(bufferAggregator -> Tuples.of(bufferAggregator, bufferAggregator.length(), 0L)) /* Scan reduces a flux with an accumulator while emitting the intermediate results. */ /* As an example, data consists of ByteBuffers of length 10-10-5. In the map above we transform the initial ByteBuffer to a tuple3 of buff, 10, 0. Scan will emit that as is, then accumulate the tuple for the next emission. On the second iteration, the middle ByteBuffer gets transformed to buff, 10, 10+0 (from previous emission). Scan emits that, and on the last iteration, the last ByteBuffer gets transformed to buff, 5, 10+10 (from previous emission). */ .scan((result, source) -> { BufferAggregator bufferAggregator = source.getT1(); long currentBufferLength = bufferAggregator.length(); long lastBytesWritten = result.getT2(); long lastOffset = result.getT3(); return Tuples.of(bufferAggregator, currentBufferLength, lastBytesWritten + lastOffset); }) .flatMapSequential(tuple3 -> { BufferAggregator bufferAggregator = tuple3.getT1(); long currentBufferLength = bufferAggregator.length(); long currentOffset = tuple3.getT3() + fileOffset; Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting( bufferAggregator.asFlux(), parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); final long offset = currentBufferLength + currentOffset; return appendWithResponse(progressData, currentOffset, currentBufferLength, null, requestConditions.getLeaseId()) .map(resp -> offset) /* End of file after append to pass to flush. */ .flux(); }, parallelTransferOptions.getMaxConcurrency()) .last() .flatMap(length -> flushWithResponse(length, false, false, httpHeaders, requestConditions)); } private Mono<Response<PathInfo>> uploadWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { return appendWithResponse(data, fileOffset, length, null, requestConditions.getLeaseId()) .flatMap(resp -> flushWithResponse(fileOffset + length, false, false, httpHeaders, requestConditions)); } /** * Creates a new file, with the content of the specified file. By default this method will not overwrite an * existing file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath) { try { return uploadFromFile(filePath, false); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file, with the content of the specified file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @param overwrite Whether or not to overwrite, should the file already exist. * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath, boolean overwrite) { try { Mono<Void> overwriteCheck = Mono.empty(); DataLakeRequestConditions requestConditions = null; if (!overwrite) { if (UploadUtils.shouldUploadInChunks(filePath, DataLakeFileAsyncClient.MAX_APPEND_FILE_BYTES, logger)) { overwriteCheck = exists().flatMap(exists -> exists ? monoError(logger, new IllegalArgumentException(Constants.FILE_ALREADY_EXISTS)) : Mono.empty()); } requestConditions = new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return overwriteCheck.then(uploadFromFile(filePath, null, null, null, requestConditions)); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new file, with the content of the specified file. * <p> * To avoid overwriting, pass "*" to {@link DataLakeRequestConditions * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.uploadFromFile * * @param filePath Path to the upload file * @param parallelTransferOptions {@link ParallelTransferOptions} to use to upload from file. Number of parallel * transfers parameter is ignored. * @param headers {@link PathHttpHeaders} * @param metadata Metadata to associate with the resource. If there is leading or trailing whitespace in any * metadata key or value, it must be removed or encoded. * @param requestConditions {@link DataLakeRequestConditions} * @return An empty response * @throws UncheckedIOException If an I/O error occurs */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> uploadFromFile(String filePath, ParallelTransferOptions parallelTransferOptions, PathHttpHeaders headers, Map<String, String> metadata, DataLakeRequestConditions requestConditions) { Long originalBlockSize = (parallelTransferOptions == null) ? null : parallelTransferOptions.getBlockSizeLong(); DataLakeRequestConditions validatedRequestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; /* Since we are creating a file with the request conditions, everything but lease id becomes invalid after creation, so e remove them for the append/flush calls. */ DataLakeRequestConditions validatedUploadRequestConditions = new DataLakeRequestConditions() .setLeaseId(validatedRequestConditions.getLeaseId()); final ParallelTransferOptions finalParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); long fileOffset = 0; try { return Mono.using(() -> UploadUtils.uploadFileResourceSupplier(filePath, logger), channel -> { try { long fileSize = channel.size(); if (fileSize == 0) { throw logger.logExceptionAsError(new IllegalArgumentException("Size of the file must be " + "greater than 0.")); } if (UploadUtils.shouldUploadInChunks(filePath, finalParallelTransferOptions.getMaxSingleUploadSizeLong(), logger)) { return createWithResponse(null, null, headers, metadata, validatedRequestConditions) .then(uploadFileChunks(fileOffset, fileSize, finalParallelTransferOptions, originalBlockSize, headers, validatedUploadRequestConditions, channel)); } else { return createWithResponse(null, null, headers, metadata, validatedRequestConditions) .then(uploadWithResponse(FluxUtil.readFile(channel), fileOffset, fileSize, headers, validatedUploadRequestConditions)) .then(); } } catch (IOException ex) { return Mono.error(ex); } }, channel -> UploadUtils.uploadFileCleanup(channel, logger)); } catch (RuntimeException ex) { return monoError(logger, ex); } } private Mono<Void> uploadFileChunks(long fileOffset, long fileSize, ParallelTransferOptions parallelTransferOptions, Long originalBlockSize, PathHttpHeaders headers, DataLakeRequestConditions requestConditions, AsynchronousFileChannel channel) { AtomicLong totalProgress = new AtomicLong(); Lock progressLock = new ReentrantLock(); return Flux.fromIterable(sliceFile(fileSize, originalBlockSize, parallelTransferOptions.getBlockSizeLong())) .flatMap(chunk -> { Flux<ByteBuffer> progressData = ProgressReporter.addParallelProgressReporting( FluxUtil.readFile(channel, chunk.getOffset(), chunk.getCount()), parallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); return appendWithResponse(progressData, fileOffset + chunk.getOffset(), chunk.getCount(), null, requestConditions.getLeaseId()); }, parallelTransferOptions.getMaxConcurrency()) .then(Mono.defer(() -> flushWithResponse(fileSize, false, false, headers, requestConditions))) .then(); } private List<FileRange> sliceFile(long fileSize, Long originalBlockSize, long blockSize) { List<FileRange> ranges = new ArrayList<>(); if (fileSize > 100 * Constants.MB && originalBlockSize == null) { blockSize = BlobAsyncClient.BLOB_DEFAULT_HTBB_UPLOAD_BLOCK_SIZE; } for (long pos = 0; pos < fileSize; pos += blockSize) { long count = blockSize; if (pos + count > fileSize) { count = fileSize - pos; } ranges.add(new FileRange(pos, count)); } return ranges; } /** * Appends data to the specified resource to later be flushed (written) by a call to flush * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.append * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param data The data to write to the file. * @param fileOffset The position where the data is to be appended. * @param length The exact length of the data. It is important that this value match precisely the length of the * data emitted by the {@code Flux}. * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> append(Flux<ByteBuffer> data, long fileOffset, long length) { try { return appendWithResponse(data, fileOffset, length, null, null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Appends data to the specified resource to later be flushed (written) by a call to flush * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.appendWithResponse * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param data The data to write to the file. * @param fileOffset The position where the data is to be appended. * @param length The exact length of the data. It is important that this value match precisely the length of the * data emitted by the {@code Flux}. * @param contentMd5 An MD5 hash of the content of the data. If specified, the service will calculate the MD5 of the * received data and fail the request if it does not match the provided MD5. * @param leaseId By setting lease id, requests will fail if the provided lease does not match the active lease on * the file. * * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> appendWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, byte[] contentMd5, String leaseId) { try { return withContext(context -> appendWithResponse(data, fileOffset, length, contentMd5, leaseId, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> appendWithResponse(Flux<ByteBuffer> data, long fileOffset, long length, byte[] contentMd5, String leaseId, Context context) { LeaseAccessConditions leaseAccessConditions = new LeaseAccessConditions().setLeaseId(leaseId); PathHttpHeaders headers = new PathHttpHeaders().setTransactionalContentHash(contentMd5); return this.dataLakeStorage.getPaths().appendDataWithResponseAsync(data, fileOffset, null, length, null, null, headers, leaseAccessConditions, context).map(response -> new SimpleResponse<>(response, null)); } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * <p>By default this method will not overwrite existing data.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flush * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> flush(long position) { try { return flush(position, false); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flush * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * @param overwrite Whether or not to overwrite, should data exist on the file. * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathInfo> flush(long position, boolean overwrite) { try { DataLakeRequestConditions requestConditions = null; if (!overwrite) { requestConditions = new DataLakeRequestConditions() .setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return flushWithResponse(position, false, false, null, requestConditions).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Flushes (writes) data previously appended to the file through a call to append. * The previously uploaded data must be contiguous. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.flushWithResponse * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param position The length of the file after all data has been written. * @param retainUncommittedData Whether or not uncommitted data is to be retained after the operation. * @param close Whether or not a file changed event raised indicates completion (true) or modification (false). * @param httpHeaders {@link PathHttpHeaders httpHeaders} * @param requestConditions {@link DataLakeRequestConditions requestConditions} * * @return A reactive response containing the information of the created resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathInfo>> flushWithResponse(long position, boolean retainUncommittedData, boolean close, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions) { try { return withContext(context -> flushWithResponse(position, retainUncommittedData, close, httpHeaders, requestConditions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<PathInfo>> flushWithResponse(long position, boolean retainUncommittedData, boolean close, PathHttpHeaders httpHeaders, DataLakeRequestConditions requestConditions, Context context) { httpHeaders = httpHeaders == null ? new PathHttpHeaders() : httpHeaders; requestConditions = requestConditions == null ? new DataLakeRequestConditions() : requestConditions; LeaseAccessConditions lac = new LeaseAccessConditions().setLeaseId(requestConditions.getLeaseId()); ModifiedAccessConditions mac = new ModifiedAccessConditions() .setIfMatch(requestConditions.getIfMatch()) .setIfNoneMatch(requestConditions.getIfNoneMatch()) .setIfModifiedSince(requestConditions.getIfModifiedSince()) .setIfUnmodifiedSince(requestConditions.getIfUnmodifiedSince()); context = context == null ? Context.NONE : context; return this.dataLakeStorage.getPaths().flushDataWithResponseAsync(null, position, retainUncommittedData, close, (long) 0, null, httpHeaders, lac, mac, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(response -> new SimpleResponse<>(response, new PathInfo(response.getDeserializedHeaders().getETag(), response.getDeserializedHeaders().getLastModified()))); } /** * Reads the entire file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.read} * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the file data. */ public Flux<ByteBuffer> read() { try { return readWithResponse(null, null, null, false) .flatMapMany(FileReadAsyncResponse::getValue); } catch (RuntimeException ex) { return fluxError(logger, ex); } } /** * Reads a range of bytes from a file. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readWithResponse * * <p>For more information, see the * <a href="https: * * @param range {@link FileRange} * @param options {@link DownloadRetryOptions} * @param requestConditions {@link DataLakeRequestConditions} * @param getRangeContentMd5 Whether the contentMD5 for the specified file range should be returned. * @return A reactive response containing the file data. */ public Mono<FileReadAsyncResponse> readWithResponse(FileRange range, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean getRangeContentMd5) { try { return blockBlobAsyncClient.downloadWithResponse(Transforms.toBlobRange(range), Transforms.toBlobDownloadRetryOptions(options), Transforms.toBlobRequestConditions(requestConditions), getRangeContentMd5).map(Transforms::toFileReadAsyncResponse) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Reads the entire file into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @return A reactive response containing the file properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> readToFile(String filePath) { return readToFile(filePath, false); } /** * Reads the entire file into a file specified by the path. * * <p>If overwrite is set to false, the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFile * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param overwrite Whether or not to overwrite the file, should the file exist. * @return A reactive response containing the file properties and metadata. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PathProperties> readToFile(String filePath, boolean overwrite) { Set<OpenOption> openOptions = null; if (overwrite) { openOptions = new HashSet<>(); openOptions.add(StandardOpenOption.CREATE); openOptions.add(StandardOpenOption.TRUNCATE_EXISTING); openOptions.add(StandardOpenOption.READ); openOptions.add(StandardOpenOption.WRITE); } return readToFileWithResponse(filePath, null, null, null, null, false, openOptions) .flatMap(FluxUtil::toMono); } /** * Reads the entire file into a file specified by the path. * * <p>By default the file will be created and must not exist, if the file already exists a * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate * {@link OpenOption OpenOptions} </p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.readToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A {@link String} representing the filePath where the downloaded data will be written. * @param range {@link FileRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param options {@link DownloadRetryOptions} * @param requestConditions {@link DataLakeRequestConditions} * @param rangeGetContentMd5 Whether the contentMD5 for the specified file range should be returned. * @param openOptions {@link OpenOption OpenOptions} to use to configure how to open or create the file. * @return A reactive response containing the file properties and metadata. * @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB. * @throws UncheckedIOException If an I/O error occurs. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<PathProperties>> readToFileWithResponse(String filePath, FileRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions options, DataLakeRequestConditions requestConditions, boolean rangeGetContentMd5, Set<OpenOption> openOptions) { return blockBlobAsyncClient.downloadToFileWithResponse(new BlobDownloadToFileOptions(filePath) .setRange(Transforms.toBlobRange(range)).setParallelTransferOptions(parallelTransferOptions) .setDownloadRetryOptions(Transforms.toBlobDownloadRetryOptions(options)) .setRequestConditions(Transforms.toBlobRequestConditions(requestConditions)) .setRetrieveContentRangeMd5(rangeGetContentMd5).setOpenOptions(openOptions)) .onErrorMap(DataLakeImplUtils::transformBlobStorageException) .map(response -> new SimpleResponse<>(response, Transforms.toPathProperties(response.getValue()))); } /** * Moves the file to another location within the file system. * For more information see the * <a href="https: * Docs</a>. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.rename * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath Relative path from the file system to rename the file to, excludes the file system name. * For example if you want to move a file with fileSystem = "myfilesystem", path = "mydir/hello.txt" to another path * in myfilesystem (ex: newdir/hi.txt) then set the destinationPath = "newdir/hi.txt" * @return A {@link Mono} containing a {@link DataLakeFileAsyncClient} used to interact with the new file created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<DataLakeFileAsyncClient> rename(String destinationFileSystem, String destinationPath) { try { return renameWithResponse(destinationFileSystem, destinationPath, null, null).flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Moves the file to another location within the file system. For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.renameWithResponse * * @param destinationFileSystem The file system of the destination within the account. * {@code null} for the current file system. * @param destinationPath Relative path from the file system to rename the file to, excludes the file system name. * For example if you want to move a file with fileSystem = "myfilesystem", path = "mydir/hello.txt" to another path * in myfilesystem (ex: newdir/hi.txt) then set the destinationPath = "newdir/hi.txt" * @param sourceRequestConditions {@link DataLakeRequestConditions} against the source. * @param destinationRequestConditions {@link DataLakeRequestConditions} against the destination. * @return A {@link Mono} containing a {@link Response} whose {@link Response * DataLakeFileAsyncClient} used to interact with the file created. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<DataLakeFileAsyncClient>> renameWithResponse(String destinationFileSystem, String destinationPath, DataLakeRequestConditions sourceRequestConditions, DataLakeRequestConditions destinationRequestConditions) { try { return withContext(context -> renameWithResponse(destinationFileSystem, destinationPath, sourceRequestConditions, destinationRequestConditions, context)) .map(response -> new SimpleResponse<>(response, new DataLakeFileAsyncClient(response.getValue()))); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Queries the entire file. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.query * * @param expression The query expression. * @return A reactive response containing the queried data. */ public Flux<ByteBuffer> query(String expression) { return queryWithResponse(new FileQueryOptions(expression)) .flatMapMany(FileQueryAsyncResponse::getValue); } /** * Queries the entire file. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.queryWithResponse * * @param queryOptions {@link FileQueryOptions The query options} * @return A reactive response containing the queried data. */ public Mono<FileQueryAsyncResponse> queryWithResponse(FileQueryOptions queryOptions) { return blockBlobAsyncClient.queryWithResponse(Transforms.toBlobQueryOptions(queryOptions)) .map(Transforms::toFileQueryAsyncResponse) .onErrorMap(DataLakeImplUtils::transformBlobStorageException); } /** * Schedules the file for deletion. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.scheduleDeletion * * @param options Schedule deletion parameters. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> scheduleDeletion(FileScheduleDeletionOptions options) { return scheduleDeletionWithResponse(options).flatMap(FluxUtil::toMono); } /** * Schedules the file for deletion. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.file.datalake.DataLakeFileAsyncClient.scheduleDeletionWithResponse * * @param options Schedule deletion parameters. * @return A reactive response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> scheduleDeletionWithResponse(FileScheduleDeletionOptions options) { try { return withContext(context -> scheduleDeletionWithResponse(options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> scheduleDeletionWithResponse(FileScheduleDeletionOptions options, Context context) { PathExpiryOptions pathExpiryOptions; context = context == null ? Context.NONE : context; String expiresOn = null; if (options != null && options.getExpiresOn() != null) { pathExpiryOptions = PathExpiryOptions.ABSOLUTE; expiresOn = new DateTimeRfc1123(options.getExpiresOn()).toString(); } else if (options != null && options.getTimeToExpire() != null) { if (options.getExpiryRelativeTo() == FileExpirationOffset.CREATION_TIME) { pathExpiryOptions = PathExpiryOptions.RELATIVE_TO_CREATION; } else { pathExpiryOptions = PathExpiryOptions.RELATIVE_TO_NOW; } expiresOn = Long.toString(options.getTimeToExpire().toMillis()); } else { pathExpiryOptions = PathExpiryOptions.NEVER_EXPIRE; } return this.blobDataLakeStorage.getPaths().setExpiryWithResponseAsync( pathExpiryOptions, null, null, expiresOn, context.addData(AZ_TRACING_NAMESPACE_KEY, STORAGE_TRACING_NAMESPACE_VALUE)) .map(rb -> new SimpleResponse<>(rb, null)); } }
is it worth saving the customer of a NPE here?
public long getLength() { return length; }
return length;
public long getLength() { return length; }
class BlobParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final Long length; private ParallelTransferOptions parallelTransferOptions; private BlobHttpHeaders headers; private Map<String, String> metadata; private Map<String, String> tags; private AccessTier tier; private BlobRequestConditions requestConditions; private boolean computeMd5; private Duration timeout; /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataFlux The data to write to the blob. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public BlobParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; } /** * Constructs a new {@link BlobParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public BlobParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataStream The data to write to the blob. */ public BlobParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } /** * Common constructor for building options from InputStream. * * @param dataStream The data to write to the blob. * @param length Optional known length of the data, affects reactive behavior for backwards compatibility. */ private BlobParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.dataFlux = null; this.length = length; } /** * Constructs a new {@code BlobParallelUploadOptions}. * * @param data The data to write to the blob. */ public BlobParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data", data); this.dataFlux = Flux.just(data.toByteBuffer()); this.dataStream = null; this.length = null; } /** * Gets the data source. * * @return The data to write to the blob. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the blob. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public BlobParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link BlobHttpHeaders}. * * @return {@link BlobHttpHeaders} */ public BlobHttpHeaders getHeaders() { return headers; } /** * Sets the {@link BlobHttpHeaders}. * * @param headers {@link BlobHttpHeaders} * @return The updated options */ public BlobParallelUploadOptions setHeaders(BlobHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the blob. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Get the tags. * * @return The tags to associate with the blob. */ public Map<String, String> getTags() { return tags; } /** * Set the tags. * * @param tags The tags to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Gets the {@link AccessTier}. * * @return {@link AccessTier} */ public AccessTier getTier() { return tier; } /** * Sets the {@link AccessTier}. * * @param tier {@link AccessTier} * @return The updated options. */ public BlobParallelUploadOptions setTier(AccessTier tier) { this.tier = tier; return this; } /** * Gets the {@link BlobRequestConditions}. * * @return {@link BlobRequestConditions} */ public BlobRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link BlobRequestConditions}. * * @param requestConditions {@link BlobRequestConditions} * @return The updated options. */ public BlobParallelUploadOptions setRequestConditions(BlobRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return Whether or not the library should calculate the md5 and send it for the service to verify. */ public boolean isComputeMd5() { return computeMd5; } /** * Sets the computeMd5 property. * * @param computeMd5 Whether or not the library should calculate the md5 and send it for the service to * verify. * @return The updated options. */ public BlobParallelUploadOptions setComputeMd5(boolean computeMd5) { this.computeMd5 = computeMd5; return this; } /** * Gets the timeout. * * @return An optional timeout value beyond which a {@link RuntimeException} will be raised. * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public Duration getTimeout() { return this.timeout; } /** * Sets the timeout. * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @return The updated options * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public BlobParallelUploadOptions setTimeout(Duration timeout) { this.timeout = timeout; return this; } }
class BlobParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final Long length; private ParallelTransferOptions parallelTransferOptions; private BlobHttpHeaders headers; private Map<String, String> metadata; private Map<String, String> tags; private AccessTier tier; private BlobRequestConditions requestConditions; private boolean computeMd5; private Duration timeout; /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataFlux The data to write to the blob. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public BlobParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; } /** * Constructs a new {@link BlobParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public BlobParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataStream The data to write to the blob. */ public BlobParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } /** * Common constructor for building options from InputStream. * * @param dataStream The data to write to the blob. * @param length Optional known length of the data, affects reactive behavior for backwards compatibility. */ private BlobParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.dataFlux = null; this.length = length; } /** * Constructs a new {@code BlobParallelUploadOptions}. * * @param data The data to write to the blob. */ public BlobParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data", data); this.dataFlux = Flux.just(data.toByteBuffer()); this.dataStream = null; this.length = null; } /** * Gets the data source. * * @return The data to write to the blob. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the blob. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public BlobParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link BlobHttpHeaders}. * * @return {@link BlobHttpHeaders} */ public BlobHttpHeaders getHeaders() { return headers; } /** * Sets the {@link BlobHttpHeaders}. * * @param headers {@link BlobHttpHeaders} * @return The updated options */ public BlobParallelUploadOptions setHeaders(BlobHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the blob. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Get the tags. * * @return The tags to associate with the blob. */ public Map<String, String> getTags() { return tags; } /** * Set the tags. * * @param tags The tags to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Gets the {@link AccessTier}. * * @return {@link AccessTier} */ public AccessTier getTier() { return tier; } /** * Sets the {@link AccessTier}. * * @param tier {@link AccessTier} * @return The updated options. */ public BlobParallelUploadOptions setTier(AccessTier tier) { this.tier = tier; return this; } /** * Gets the {@link BlobRequestConditions}. * * @return {@link BlobRequestConditions} */ public BlobRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link BlobRequestConditions}. * * @param requestConditions {@link BlobRequestConditions} * @return The updated options. */ public BlobParallelUploadOptions setRequestConditions(BlobRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return Whether or not the library should calculate the md5 and send it for the service to verify. */ public boolean isComputeMd5() { return computeMd5; } /** * Sets the computeMd5 property. * * @param computeMd5 Whether or not the library should calculate the md5 and send it for the service to * verify. * @return The updated options. */ public BlobParallelUploadOptions setComputeMd5(boolean computeMd5) { this.computeMd5 = computeMd5; return this; } /** * Gets the timeout. * * @return An optional timeout value beyond which a {@link RuntimeException} will be raised. * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public Duration getTimeout() { return this.timeout; } /** * Sets the timeout. * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @return The updated options * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public BlobParallelUploadOptions setTimeout(Duration timeout) { this.timeout = timeout; return this; } }
Or if length is null should we throw a meaningful error?
public long getLength() { return length; }
return length;
public long getLength() { return length; }
class BlobParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final Long length; private ParallelTransferOptions parallelTransferOptions; private BlobHttpHeaders headers; private Map<String, String> metadata; private Map<String, String> tags; private AccessTier tier; private BlobRequestConditions requestConditions; private boolean computeMd5; private Duration timeout; /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataFlux The data to write to the blob. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public BlobParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; } /** * Constructs a new {@link BlobParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public BlobParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataStream The data to write to the blob. */ public BlobParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } /** * Common constructor for building options from InputStream. * * @param dataStream The data to write to the blob. * @param length Optional known length of the data, affects reactive behavior for backwards compatibility. */ private BlobParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.dataFlux = null; this.length = length; } /** * Constructs a new {@code BlobParallelUploadOptions}. * * @param data The data to write to the blob. */ public BlobParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data", data); this.dataFlux = Flux.just(data.toByteBuffer()); this.dataStream = null; this.length = null; } /** * Gets the data source. * * @return The data to write to the blob. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the blob. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public BlobParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link BlobHttpHeaders}. * * @return {@link BlobHttpHeaders} */ public BlobHttpHeaders getHeaders() { return headers; } /** * Sets the {@link BlobHttpHeaders}. * * @param headers {@link BlobHttpHeaders} * @return The updated options */ public BlobParallelUploadOptions setHeaders(BlobHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the blob. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Get the tags. * * @return The tags to associate with the blob. */ public Map<String, String> getTags() { return tags; } /** * Set the tags. * * @param tags The tags to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Gets the {@link AccessTier}. * * @return {@link AccessTier} */ public AccessTier getTier() { return tier; } /** * Sets the {@link AccessTier}. * * @param tier {@link AccessTier} * @return The updated options. */ public BlobParallelUploadOptions setTier(AccessTier tier) { this.tier = tier; return this; } /** * Gets the {@link BlobRequestConditions}. * * @return {@link BlobRequestConditions} */ public BlobRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link BlobRequestConditions}. * * @param requestConditions {@link BlobRequestConditions} * @return The updated options. */ public BlobParallelUploadOptions setRequestConditions(BlobRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return Whether or not the library should calculate the md5 and send it for the service to verify. */ public boolean isComputeMd5() { return computeMd5; } /** * Sets the computeMd5 property. * * @param computeMd5 Whether or not the library should calculate the md5 and send it for the service to * verify. * @return The updated options. */ public BlobParallelUploadOptions setComputeMd5(boolean computeMd5) { this.computeMd5 = computeMd5; return this; } /** * Gets the timeout. * * @return An optional timeout value beyond which a {@link RuntimeException} will be raised. * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public Duration getTimeout() { return this.timeout; } /** * Sets the timeout. * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @return The updated options * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public BlobParallelUploadOptions setTimeout(Duration timeout) { this.timeout = timeout; return this; } }
class BlobParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final Long length; private ParallelTransferOptions parallelTransferOptions; private BlobHttpHeaders headers; private Map<String, String> metadata; private Map<String, String> tags; private AccessTier tier; private BlobRequestConditions requestConditions; private boolean computeMd5; private Duration timeout; /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataFlux The data to write to the blob. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public BlobParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; } /** * Constructs a new {@link BlobParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public BlobParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataStream The data to write to the blob. */ public BlobParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } /** * Common constructor for building options from InputStream. * * @param dataStream The data to write to the blob. * @param length Optional known length of the data, affects reactive behavior for backwards compatibility. */ private BlobParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.dataFlux = null; this.length = length; } /** * Constructs a new {@code BlobParallelUploadOptions}. * * @param data The data to write to the blob. */ public BlobParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data", data); this.dataFlux = Flux.just(data.toByteBuffer()); this.dataStream = null; this.length = null; } /** * Gets the data source. * * @return The data to write to the blob. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the blob. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public BlobParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link BlobHttpHeaders}. * * @return {@link BlobHttpHeaders} */ public BlobHttpHeaders getHeaders() { return headers; } /** * Sets the {@link BlobHttpHeaders}. * * @param headers {@link BlobHttpHeaders} * @return The updated options */ public BlobParallelUploadOptions setHeaders(BlobHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the blob. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Get the tags. * * @return The tags to associate with the blob. */ public Map<String, String> getTags() { return tags; } /** * Set the tags. * * @param tags The tags to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Gets the {@link AccessTier}. * * @return {@link AccessTier} */ public AccessTier getTier() { return tier; } /** * Sets the {@link AccessTier}. * * @param tier {@link AccessTier} * @return The updated options. */ public BlobParallelUploadOptions setTier(AccessTier tier) { this.tier = tier; return this; } /** * Gets the {@link BlobRequestConditions}. * * @return {@link BlobRequestConditions} */ public BlobRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link BlobRequestConditions}. * * @param requestConditions {@link BlobRequestConditions} * @return The updated options. */ public BlobParallelUploadOptions setRequestConditions(BlobRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return Whether or not the library should calculate the md5 and send it for the service to verify. */ public boolean isComputeMd5() { return computeMd5; } /** * Sets the computeMd5 property. * * @param computeMd5 Whether or not the library should calculate the md5 and send it for the service to * verify. * @return The updated options. */ public BlobParallelUploadOptions setComputeMd5(boolean computeMd5) { this.computeMd5 = computeMd5; return this; } /** * Gets the timeout. * * @return An optional timeout value beyond which a {@link RuntimeException} will be raised. * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public Duration getTimeout() { return this.timeout; } /** * Sets the timeout. * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @return The updated options * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public BlobParallelUploadOptions setTimeout(Duration timeout) { this.timeout = timeout; return this; } }
I think this is fine, it won't throw if they haven't switched to new code path.
public long getLength() { return length; }
return length;
public long getLength() { return length; }
class BlobParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final Long length; private ParallelTransferOptions parallelTransferOptions; private BlobHttpHeaders headers; private Map<String, String> metadata; private Map<String, String> tags; private AccessTier tier; private BlobRequestConditions requestConditions; private boolean computeMd5; private Duration timeout; /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataFlux The data to write to the blob. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public BlobParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; } /** * Constructs a new {@link BlobParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public BlobParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataStream The data to write to the blob. */ public BlobParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } /** * Common constructor for building options from InputStream. * * @param dataStream The data to write to the blob. * @param length Optional known length of the data, affects reactive behavior for backwards compatibility. */ private BlobParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.dataFlux = null; this.length = length; } /** * Constructs a new {@code BlobParallelUploadOptions}. * * @param data The data to write to the blob. */ public BlobParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data", data); this.dataFlux = Flux.just(data.toByteBuffer()); this.dataStream = null; this.length = null; } /** * Gets the data source. * * @return The data to write to the blob. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the blob. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public BlobParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link BlobHttpHeaders}. * * @return {@link BlobHttpHeaders} */ public BlobHttpHeaders getHeaders() { return headers; } /** * Sets the {@link BlobHttpHeaders}. * * @param headers {@link BlobHttpHeaders} * @return The updated options */ public BlobParallelUploadOptions setHeaders(BlobHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the blob. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Get the tags. * * @return The tags to associate with the blob. */ public Map<String, String> getTags() { return tags; } /** * Set the tags. * * @param tags The tags to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Gets the {@link AccessTier}. * * @return {@link AccessTier} */ public AccessTier getTier() { return tier; } /** * Sets the {@link AccessTier}. * * @param tier {@link AccessTier} * @return The updated options. */ public BlobParallelUploadOptions setTier(AccessTier tier) { this.tier = tier; return this; } /** * Gets the {@link BlobRequestConditions}. * * @return {@link BlobRequestConditions} */ public BlobRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link BlobRequestConditions}. * * @param requestConditions {@link BlobRequestConditions} * @return The updated options. */ public BlobParallelUploadOptions setRequestConditions(BlobRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return Whether or not the library should calculate the md5 and send it for the service to verify. */ public boolean isComputeMd5() { return computeMd5; } /** * Sets the computeMd5 property. * * @param computeMd5 Whether or not the library should calculate the md5 and send it for the service to * verify. * @return The updated options. */ public BlobParallelUploadOptions setComputeMd5(boolean computeMd5) { this.computeMd5 = computeMd5; return this; } /** * Gets the timeout. * * @return An optional timeout value beyond which a {@link RuntimeException} will be raised. * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public Duration getTimeout() { return this.timeout; } /** * Sets the timeout. * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @return The updated options * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public BlobParallelUploadOptions setTimeout(Duration timeout) { this.timeout = timeout; return this; } }
class BlobParallelUploadOptions { private final Flux<ByteBuffer> dataFlux; private final InputStream dataStream; private final Long length; private ParallelTransferOptions parallelTransferOptions; private BlobHttpHeaders headers; private Map<String, String> metadata; private Map<String, String> tags; private AccessTier tier; private BlobRequestConditions requestConditions; private boolean computeMd5; private Duration timeout; /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataFlux The data to write to the blob. Unlike other upload methods, this method does not require that * the {@code Flux} be replayable. In other words, it does not have to support multiple subscribers and is not * expected to produce the same values across subscriptions. */ public BlobParallelUploadOptions(Flux<ByteBuffer> dataFlux) { StorageImplUtils.assertNotNull("dataFlux", dataFlux); this.dataFlux = dataFlux; this.dataStream = null; this.length = null; } /** * Constructs a new {@link BlobParallelUploadOptions}. * * Use {@link * length beforehand. * * @param dataStream The data to write to the blob. * @param length The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated length is no longer necessary; use {@link */ @Deprecated public BlobParallelUploadOptions(InputStream dataStream, long length) { this(dataStream, Long.valueOf(length)); } /** * Constructs a new {@link BlobParallelUploadOptions}. * * @param dataStream The data to write to the blob. */ public BlobParallelUploadOptions(InputStream dataStream) { this(dataStream, null); } /** * Common constructor for building options from InputStream. * * @param dataStream The data to write to the blob. * @param length Optional known length of the data, affects reactive behavior for backwards compatibility. */ private BlobParallelUploadOptions(InputStream dataStream, Long length) { StorageImplUtils.assertNotNull("dataStream", dataStream); if (length != null) { StorageImplUtils.assertInBounds("length", length, 0, Long.MAX_VALUE); } this.dataStream = dataStream; this.dataFlux = null; this.length = length; } /** * Constructs a new {@code BlobParallelUploadOptions}. * * @param data The data to write to the blob. */ public BlobParallelUploadOptions(BinaryData data) { StorageImplUtils.assertNotNull("data", data); this.dataFlux = Flux.just(data.toByteBuffer()); this.dataStream = null; this.length = null; } /** * Gets the data source. * * @return The data to write to the blob. */ public Flux<ByteBuffer> getDataFlux() { return this.dataFlux; } /** * Gets the data source. * * @return The data to write to the blob. */ public InputStream getDataStream() { return this.dataStream; } /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. * @deprecated use {@link */ @Deprecated /** * Gets the length of the data. * * @return The exact length of the data. It is important that this value match precisely the length of the * data provided in the {@link InputStream}. */ public Long getOptionalLength() { return length; } /** * Gets the {@link ParallelTransferOptions}. * * @return {@link ParallelTransferOptions} */ public ParallelTransferOptions getParallelTransferOptions() { return parallelTransferOptions; } /** * Sets the {@link ParallelTransferOptions}. * * @param parallelTransferOptions {@link ParallelTransferOptions} * @return The updated options. */ public BlobParallelUploadOptions setParallelTransferOptions(ParallelTransferOptions parallelTransferOptions) { this.parallelTransferOptions = parallelTransferOptions; return this; } /** * Gets the {@link BlobHttpHeaders}. * * @return {@link BlobHttpHeaders} */ public BlobHttpHeaders getHeaders() { return headers; } /** * Sets the {@link BlobHttpHeaders}. * * @param headers {@link BlobHttpHeaders} * @return The updated options */ public BlobParallelUploadOptions setHeaders(BlobHttpHeaders headers) { this.headers = headers; return this; } /** * Gets the metadata. * * @return The metadata to associate with the blob. */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata The metadata to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Get the tags. * * @return The tags to associate with the blob. */ public Map<String, String> getTags() { return tags; } /** * Set the tags. * * @param tags The tags to associate with the blob. * @return The updated options. */ public BlobParallelUploadOptions setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Gets the {@link AccessTier}. * * @return {@link AccessTier} */ public AccessTier getTier() { return tier; } /** * Sets the {@link AccessTier}. * * @param tier {@link AccessTier} * @return The updated options. */ public BlobParallelUploadOptions setTier(AccessTier tier) { this.tier = tier; return this; } /** * Gets the {@link BlobRequestConditions}. * * @return {@link BlobRequestConditions} */ public BlobRequestConditions getRequestConditions() { return requestConditions; } /** * Sets the {@link BlobRequestConditions}. * * @param requestConditions {@link BlobRequestConditions} * @return The updated options. */ public BlobParallelUploadOptions setRequestConditions(BlobRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return Whether or not the library should calculate the md5 and send it for the service to verify. */ public boolean isComputeMd5() { return computeMd5; } /** * Sets the computeMd5 property. * * @param computeMd5 Whether or not the library should calculate the md5 and send it for the service to * verify. * @return The updated options. */ public BlobParallelUploadOptions setComputeMd5(boolean computeMd5) { this.computeMd5 = computeMd5; return this; } /** * Gets the timeout. * * @return An optional timeout value beyond which a {@link RuntimeException} will be raised. * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public Duration getTimeout() { return this.timeout; } /** * Sets the timeout. * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @return The updated options * * @deprecated Use {@link BlobClient * specify timeout. */ @Deprecated public BlobParallelUploadOptions setTimeout(Duration timeout) { this.timeout = timeout; return this; } }
I think we should not set anything if the user has not configured the pool size. This number could change with later releases of OkHttp.
public HttpClient createInstance(HttpClientOptions clientOptions) { OkHttpAsyncHttpClientBuilder builder = new OkHttpAsyncHttpClientBuilder(); if (clientOptions != null) { builder = builder.proxy(clientOptions.getProxyOptions()) .configuration(clientOptions.getConfiguration()) .writeTimeout(clientOptions.getWriteTimeout()) .readTimeout(clientOptions.getReadTimeout()); int maximumConnectionPoolSize = (clientOptions.getMaximumConnectionPoolSize() == 0) ? 5 : clientOptions.getMaximumConnectionPoolSize(); ConnectionPool connectionPool = new ConnectionPool(maximumConnectionPoolSize, clientOptions.getConnectionIdleTimeout().toMillis(), TimeUnit.MILLISECONDS); builder = builder.connectionPool(connectionPool); } return builder.build(); }
? 5
public HttpClient createInstance(HttpClientOptions clientOptions) { OkHttpAsyncHttpClientBuilder builder = new OkHttpAsyncHttpClientBuilder(); if (clientOptions != null) { builder = builder.proxy(clientOptions.getProxyOptions()) .configuration(clientOptions.getConfiguration()) .writeTimeout(clientOptions.getWriteTimeout()) .readTimeout(clientOptions.getReadTimeout()); int maximumConnectionPoolSize = (clientOptions.getMaximumConnectionPoolSize() == 0) ? 5 : clientOptions.getMaximumConnectionPoolSize(); ConnectionPool connectionPool = new ConnectionPool(maximumConnectionPoolSize, clientOptions.getConnectionIdleTimeout().toMillis(), TimeUnit.MILLISECONDS); builder = builder.connectionPool(connectionPool); } return builder.build(); }
class OkHttpAsyncClientProvider implements HttpClientProvider { @Override public HttpClient createInstance() { return new OkHttpAsyncHttpClientBuilder().build(); } @Override }
class OkHttpAsyncClientProvider implements HttpClientProvider { @Override public HttpClient createInstance() { return new OkHttpAsyncHttpClientBuilder().build(); } @Override }
It is a required parameter in the constructor, I'll check if they (OkHttp) have it as a constant anywhere.
public HttpClient createInstance(HttpClientOptions clientOptions) { OkHttpAsyncHttpClientBuilder builder = new OkHttpAsyncHttpClientBuilder(); if (clientOptions != null) { builder = builder.proxy(clientOptions.getProxyOptions()) .configuration(clientOptions.getConfiguration()) .writeTimeout(clientOptions.getWriteTimeout()) .readTimeout(clientOptions.getReadTimeout()); int maximumConnectionPoolSize = (clientOptions.getMaximumConnectionPoolSize() == 0) ? 5 : clientOptions.getMaximumConnectionPoolSize(); ConnectionPool connectionPool = new ConnectionPool(maximumConnectionPoolSize, clientOptions.getConnectionIdleTimeout().toMillis(), TimeUnit.MILLISECONDS); builder = builder.connectionPool(connectionPool); } return builder.build(); }
? 5
public HttpClient createInstance(HttpClientOptions clientOptions) { OkHttpAsyncHttpClientBuilder builder = new OkHttpAsyncHttpClientBuilder(); if (clientOptions != null) { builder = builder.proxy(clientOptions.getProxyOptions()) .configuration(clientOptions.getConfiguration()) .writeTimeout(clientOptions.getWriteTimeout()) .readTimeout(clientOptions.getReadTimeout()); int maximumConnectionPoolSize = (clientOptions.getMaximumConnectionPoolSize() == 0) ? 5 : clientOptions.getMaximumConnectionPoolSize(); ConnectionPool connectionPool = new ConnectionPool(maximumConnectionPoolSize, clientOptions.getConnectionIdleTimeout().toMillis(), TimeUnit.MILLISECONDS); builder = builder.connectionPool(connectionPool); } return builder.build(); }
class OkHttpAsyncClientProvider implements HttpClientProvider { @Override public HttpClient createInstance() { return new OkHttpAsyncHttpClientBuilder().build(); } @Override }
class OkHttpAsyncClientProvider implements HttpClientProvider { @Override public HttpClient createInstance() { return new OkHttpAsyncHttpClientBuilder().build(); } @Override }
So now are we going to support all service versions in BlobServiceVersion?
private String stringToSign(final UserDelegationKey key, String canonicalName) { String versionSegment = this.snapshotId == null ? this.versionId : this.snapshotId; if (VERSION.compareTo(BlobServiceVersion.V2019_12_12.getVersion()) <= 0) { return String.join("\n", this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, key.getSignedObjectId() == null ? "" : key.getSignedObjectId(), key.getSignedTenantId() == null ? "" : key.getSignedTenantId(), key.getSignedStart() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedStart()), key.getSignedExpiry() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedExpiry()), key.getSignedService() == null ? "" : key.getSignedService(), key.getSignedVersion() == null ? "" : key.getSignedVersion(), this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } else { return String.join("\n", this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, key.getSignedObjectId() == null ? "" : key.getSignedObjectId(), key.getSignedTenantId() == null ? "" : key.getSignedTenantId(), key.getSignedStart() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedStart()), key.getSignedExpiry() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedExpiry()), key.getSignedService() == null ? "" : key.getSignedService(), key.getSignedVersion() == null ? "" : key.getSignedVersion(), this.authorizedAadObjectId == null ? "" : this.authorizedAadObjectId, "", /* suoid - empty since this applies to HNS only accounts. */ this.correlationId == null ? "" : this.correlationId, this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } }
if (VERSION.compareTo(BlobServiceVersion.V2019_12_12.getVersion()) <= 0) {
private String stringToSign(final UserDelegationKey key, String canonicalName) { String versionSegment = this.snapshotId == null ? this.versionId : this.snapshotId; if (VERSION.compareTo(BlobServiceVersion.V2019_12_12.getVersion()) <= 0) { return String.join("\n", this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, key.getSignedObjectId() == null ? "" : key.getSignedObjectId(), key.getSignedTenantId() == null ? "" : key.getSignedTenantId(), key.getSignedStart() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedStart()), key.getSignedExpiry() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedExpiry()), key.getSignedService() == null ? "" : key.getSignedService(), key.getSignedVersion() == null ? "" : key.getSignedVersion(), this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } else { return String.join("\n", this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, key.getSignedObjectId() == null ? "" : key.getSignedObjectId(), key.getSignedTenantId() == null ? "" : key.getSignedTenantId(), key.getSignedStart() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedStart()), key.getSignedExpiry() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedExpiry()), key.getSignedService() == null ? "" : key.getSignedService(), key.getSignedVersion() == null ? "" : key.getSignedVersion(), this.authorizedAadObjectId == null ? "" : this.authorizedAadObjectId, "", /* suoid - empty since this applies to HNS only accounts. */ this.correlationId == null ? "" : this.correlationId, this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } }
class BlobSasImplUtil { /** * The SAS blob constant. */ private static final String SAS_BLOB_CONSTANT = "b"; /** * The SAS blob snapshot constant. */ private static final String SAS_BLOB_SNAPSHOT_CONSTANT = "bs"; /** * The SAS blob version constant. */ private static final String SAS_BLOB_VERSION_CONSTANT = "bv"; /** * The SAS blob container constant. */ private static final String SAS_CONTAINER_CONSTANT = "c"; private static final ClientLogger LOGGER = new ClientLogger(BlobSasImplUtil.class); private static final String VERSION = Configuration.getGlobalConfiguration() .get(Constants.PROPERTY_AZURE_STORAGE_SAS_SERVICE_VERSION, BlobServiceVersion.getLatest().getVersion()); private SasProtocol protocol; private OffsetDateTime startTime; private OffsetDateTime expiryTime; private String permissions; private SasIpRange sasIpRange; private String containerName; private String blobName; private String resource; private String snapshotId; private String versionId; private String identifier; private String cacheControl; private String contentDisposition; private String contentEncoding; private String contentLanguage; private String contentType; private String authorizedAadObjectId; private String correlationId; /** * Creates a new {@link BlobSasImplUtil} with the specified parameters * * @param sasValues {@link BlobServiceSasSignatureValues} * @param containerName The container name */ public BlobSasImplUtil(BlobServiceSasSignatureValues sasValues, String containerName) { this(sasValues, containerName, null, null, null); } /** * Creates a new {@link BlobSasImplUtil} with the specified parameters * * @param sasValues {@link BlobServiceSasSignatureValues} * @param containerName The container name * @param blobName The blob name * @param snapshotId The snapshot id * @param versionId The version id */ public BlobSasImplUtil(BlobServiceSasSignatureValues sasValues, String containerName, String blobName, String snapshotId, String versionId) { Objects.requireNonNull(sasValues); if (snapshotId != null && versionId != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'snapshot' and 'versionId' cannot be used at the same time.")); } this.protocol = sasValues.getProtocol(); this.startTime = sasValues.getStartTime(); this.expiryTime = sasValues.getExpiryTime(); this.permissions = sasValues.getPermissions(); this.sasIpRange = sasValues.getSasIpRange(); this.containerName = containerName; this.blobName = blobName; this.snapshotId = snapshotId; this.versionId = versionId; this.identifier = sasValues.getIdentifier(); this.cacheControl = sasValues.getCacheControl(); this.contentDisposition = sasValues.getContentDisposition(); this.contentEncoding = sasValues.getContentEncoding(); this.contentLanguage = sasValues.getContentLanguage(); this.contentType = sasValues.getContentType(); this.authorizedAadObjectId = sasValues.getPreauthorizedAgentObjectId(); this.correlationId = sasValues.getCorrelationId(); } /** * Generates a Sas signed with a {@link StorageSharedKeyCredential} * * @param storageSharedKeyCredentials {@link StorageSharedKeyCredential} * @param context Additional context that is passed through the code when generating a SAS. * @return A String representing the Sas */ public String generateSas(StorageSharedKeyCredential storageSharedKeyCredentials, Context context) { StorageImplUtils.assertNotNull("storageSharedKeyCredentials", storageSharedKeyCredentials); ensureState(); final String canonicalName = getCanonicalName(storageSharedKeyCredentials.getAccountName()); final String stringToSign = stringToSign(canonicalName); StorageImplUtils.logStringToSign(LOGGER, stringToSign, context); final String signature = storageSharedKeyCredentials.computeHmac256(stringToSign); return encode(null /* userDelegationKey */, signature); } /** * Generates a Sas signed with a {@link UserDelegationKey} * * @param delegationKey {@link UserDelegationKey} * @param accountName The account name * @param context Additional context that is passed through the code when generating a SAS. * @return A String representing the Sas */ public String generateUserDelegationSas(UserDelegationKey delegationKey, String accountName, Context context) { StorageImplUtils.assertNotNull("delegationKey", delegationKey); StorageImplUtils.assertNotNull("accountName", accountName); ensureState(); final String canonicalName = getCanonicalName(accountName); final String stringToSign = stringToSign(delegationKey, canonicalName); StorageImplUtils.logStringToSign(LOGGER, stringToSign, context); String signature = StorageImplUtils.computeHMac256(delegationKey.getValue(), stringToSign); return encode(delegationKey, signature); } /** * Encodes a Sas from the values in this type. * @param userDelegationKey {@link UserDelegationKey} * @param signature The signature of the Sas. * @return A String representing the Sas. */ private String encode(UserDelegationKey userDelegationKey, String signature) { /* We should be url-encoding each key and each value, but because we know all the keys and values will encode to themselves, we cheat except for the signature value. */ StringBuilder sb = new StringBuilder(); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SERVICE_VERSION, VERSION); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PROTOCOL, this.protocol); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_START_TIME, formatQueryParameterDate(this.startTime)); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_EXPIRY_TIME, formatQueryParameterDate(this.expiryTime)); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_IP_RANGE, this.sasIpRange); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_IDENTIFIER, this.identifier); if (userDelegationKey != null) { tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_OBJECT_ID, userDelegationKey.getSignedObjectId()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_TENANT_ID, userDelegationKey.getSignedTenantId()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_START, formatQueryParameterDate(userDelegationKey.getSignedStart())); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_EXPIRY, formatQueryParameterDate(userDelegationKey.getSignedExpiry())); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_SERVICE, userDelegationKey.getSignedService()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_VERSION, userDelegationKey.getSignedVersion()); /* Only parameters relevant for user delegation SAS. */ tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PREAUTHORIZED_AGENT_OBJECT_ID, this.authorizedAadObjectId); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CORRELATION_ID, this.correlationId); } tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_RESOURCE, this.resource); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_PERMISSIONS, this.permissions); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNATURE, signature); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CACHE_CONTROL, this.cacheControl); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_DISPOSITION, this.contentDisposition); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_ENCODING, this.contentEncoding); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_LANGUAGE, this.contentLanguage); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_TYPE, this.contentType); return sb.toString(); } /** * Ensures that the builder's properties are in a consistent state. * 1. If there is no version, use latest. * 2. If there is no identifier set, ensure expiryTime and permissions are set. * 3. Resource name is chosen by: * a. If "BlobName" is _not_ set, it is a container resource. * b. Otherwise, if "SnapshotId" is set, it is a blob snapshot resource. * c. Otherwise, if "VersionId" is set, it is a blob version resource. * d. Otherwise, it is a blob resource. * 4. Reparse permissions depending on what the resource is. If it is an unrecognized resource, do nothing. * * Taken from: * https: * https: */ private void ensureState() { if (identifier == null) { if (expiryTime == null || permissions == null) { throw LOGGER.logExceptionAsError(new IllegalStateException("If identifier is not set, expiry time " + "and permissions must be set")); } } if (CoreUtils.isNullOrEmpty(blobName)) { resource = SAS_CONTAINER_CONSTANT; } else if (snapshotId != null) { resource = SAS_BLOB_SNAPSHOT_CONSTANT; } else if (versionId != null) { resource = SAS_BLOB_VERSION_CONSTANT; } else { resource = SAS_BLOB_CONSTANT; } if (permissions != null) { switch (resource) { case SAS_BLOB_CONSTANT: case SAS_BLOB_SNAPSHOT_CONSTANT: case SAS_BLOB_VERSION_CONSTANT: permissions = BlobSasPermission.parse(permissions).toString(); break; case SAS_CONTAINER_CONSTANT: permissions = BlobContainerSasPermission.parse(permissions).toString(); break; default: LOGGER.info("Not re-parsing permissions. Resource type '{}' is unknown.", resource); break; } } } /** * Computes the canonical name for a container or blob resource for SAS signing. */ private String getCanonicalName(String account) { return CoreUtils.isNullOrEmpty(blobName) ? String.format("/blob/%s/%s", account, containerName) : String.format("/blob/%s/%s/%s", account, containerName, blobName.replace("\\", "/")); } private String stringToSign(String canonicalName) { String versionSegment = this.snapshotId == null ? this.versionId : this.snapshotId; return String.join("\n", this.permissions == null ? "" : permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, this.identifier == null ? "" : this.identifier, this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } }
class BlobSasImplUtil { /** * The SAS blob constant. */ private static final String SAS_BLOB_CONSTANT = "b"; /** * The SAS blob snapshot constant. */ private static final String SAS_BLOB_SNAPSHOT_CONSTANT = "bs"; /** * The SAS blob version constant. */ private static final String SAS_BLOB_VERSION_CONSTANT = "bv"; /** * The SAS blob container constant. */ private static final String SAS_CONTAINER_CONSTANT = "c"; private static final ClientLogger LOGGER = new ClientLogger(BlobSasImplUtil.class); private static final String VERSION = Configuration.getGlobalConfiguration() .get(Constants.PROPERTY_AZURE_STORAGE_SAS_SERVICE_VERSION, BlobServiceVersion.getLatest().getVersion()); private SasProtocol protocol; private OffsetDateTime startTime; private OffsetDateTime expiryTime; private String permissions; private SasIpRange sasIpRange; private String containerName; private String blobName; private String resource; private String snapshotId; private String versionId; private String identifier; private String cacheControl; private String contentDisposition; private String contentEncoding; private String contentLanguage; private String contentType; private String authorizedAadObjectId; private String correlationId; /** * Creates a new {@link BlobSasImplUtil} with the specified parameters * * @param sasValues {@link BlobServiceSasSignatureValues} * @param containerName The container name */ public BlobSasImplUtil(BlobServiceSasSignatureValues sasValues, String containerName) { this(sasValues, containerName, null, null, null); } /** * Creates a new {@link BlobSasImplUtil} with the specified parameters * * @param sasValues {@link BlobServiceSasSignatureValues} * @param containerName The container name * @param blobName The blob name * @param snapshotId The snapshot id * @param versionId The version id */ public BlobSasImplUtil(BlobServiceSasSignatureValues sasValues, String containerName, String blobName, String snapshotId, String versionId) { Objects.requireNonNull(sasValues); if (snapshotId != null && versionId != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'snapshot' and 'versionId' cannot be used at the same time.")); } this.protocol = sasValues.getProtocol(); this.startTime = sasValues.getStartTime(); this.expiryTime = sasValues.getExpiryTime(); this.permissions = sasValues.getPermissions(); this.sasIpRange = sasValues.getSasIpRange(); this.containerName = containerName; this.blobName = blobName; this.snapshotId = snapshotId; this.versionId = versionId; this.identifier = sasValues.getIdentifier(); this.cacheControl = sasValues.getCacheControl(); this.contentDisposition = sasValues.getContentDisposition(); this.contentEncoding = sasValues.getContentEncoding(); this.contentLanguage = sasValues.getContentLanguage(); this.contentType = sasValues.getContentType(); this.authorizedAadObjectId = sasValues.getPreauthorizedAgentObjectId(); this.correlationId = sasValues.getCorrelationId(); } /** * Generates a Sas signed with a {@link StorageSharedKeyCredential} * * @param storageSharedKeyCredentials {@link StorageSharedKeyCredential} * @param context Additional context that is passed through the code when generating a SAS. * @return A String representing the Sas */ public String generateSas(StorageSharedKeyCredential storageSharedKeyCredentials, Context context) { StorageImplUtils.assertNotNull("storageSharedKeyCredentials", storageSharedKeyCredentials); ensureState(); final String canonicalName = getCanonicalName(storageSharedKeyCredentials.getAccountName()); final String stringToSign = stringToSign(canonicalName); StorageImplUtils.logStringToSign(LOGGER, stringToSign, context); final String signature = storageSharedKeyCredentials.computeHmac256(stringToSign); return encode(null /* userDelegationKey */, signature); } /** * Generates a Sas signed with a {@link UserDelegationKey} * * @param delegationKey {@link UserDelegationKey} * @param accountName The account name * @param context Additional context that is passed through the code when generating a SAS. * @return A String representing the Sas */ public String generateUserDelegationSas(UserDelegationKey delegationKey, String accountName, Context context) { StorageImplUtils.assertNotNull("delegationKey", delegationKey); StorageImplUtils.assertNotNull("accountName", accountName); ensureState(); final String canonicalName = getCanonicalName(accountName); final String stringToSign = stringToSign(delegationKey, canonicalName); StorageImplUtils.logStringToSign(LOGGER, stringToSign, context); String signature = StorageImplUtils.computeHMac256(delegationKey.getValue(), stringToSign); return encode(delegationKey, signature); } /** * Encodes a Sas from the values in this type. * @param userDelegationKey {@link UserDelegationKey} * @param signature The signature of the Sas. * @return A String representing the Sas. */ private String encode(UserDelegationKey userDelegationKey, String signature) { /* We should be url-encoding each key and each value, but because we know all the keys and values will encode to themselves, we cheat except for the signature value. */ StringBuilder sb = new StringBuilder(); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SERVICE_VERSION, VERSION); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PROTOCOL, this.protocol); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_START_TIME, formatQueryParameterDate(this.startTime)); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_EXPIRY_TIME, formatQueryParameterDate(this.expiryTime)); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_IP_RANGE, this.sasIpRange); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_IDENTIFIER, this.identifier); if (userDelegationKey != null) { tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_OBJECT_ID, userDelegationKey.getSignedObjectId()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_TENANT_ID, userDelegationKey.getSignedTenantId()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_START, formatQueryParameterDate(userDelegationKey.getSignedStart())); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_EXPIRY, formatQueryParameterDate(userDelegationKey.getSignedExpiry())); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_SERVICE, userDelegationKey.getSignedService()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_VERSION, userDelegationKey.getSignedVersion()); /* Only parameters relevant for user delegation SAS. */ tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PREAUTHORIZED_AGENT_OBJECT_ID, this.authorizedAadObjectId); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CORRELATION_ID, this.correlationId); } tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_RESOURCE, this.resource); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_PERMISSIONS, this.permissions); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNATURE, signature); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CACHE_CONTROL, this.cacheControl); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_DISPOSITION, this.contentDisposition); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_ENCODING, this.contentEncoding); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_LANGUAGE, this.contentLanguage); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_TYPE, this.contentType); return sb.toString(); } /** * Ensures that the builder's properties are in a consistent state. * 1. If there is no version, use latest. * 2. If there is no identifier set, ensure expiryTime and permissions are set. * 3. Resource name is chosen by: * a. If "BlobName" is _not_ set, it is a container resource. * b. Otherwise, if "SnapshotId" is set, it is a blob snapshot resource. * c. Otherwise, if "VersionId" is set, it is a blob version resource. * d. Otherwise, it is a blob resource. * 4. Reparse permissions depending on what the resource is. If it is an unrecognized resource, do nothing. * * Taken from: * https: * https: */ private void ensureState() { if (identifier == null) { if (expiryTime == null || permissions == null) { throw LOGGER.logExceptionAsError(new IllegalStateException("If identifier is not set, expiry time " + "and permissions must be set")); } } if (CoreUtils.isNullOrEmpty(blobName)) { resource = SAS_CONTAINER_CONSTANT; } else if (snapshotId != null) { resource = SAS_BLOB_SNAPSHOT_CONSTANT; } else if (versionId != null) { resource = SAS_BLOB_VERSION_CONSTANT; } else { resource = SAS_BLOB_CONSTANT; } if (permissions != null) { switch (resource) { case SAS_BLOB_CONSTANT: case SAS_BLOB_SNAPSHOT_CONSTANT: case SAS_BLOB_VERSION_CONSTANT: permissions = BlobSasPermission.parse(permissions).toString(); break; case SAS_CONTAINER_CONSTANT: permissions = BlobContainerSasPermission.parse(permissions).toString(); break; default: LOGGER.info("Not re-parsing permissions. Resource type '{}' is unknown.", resource); break; } } } /** * Computes the canonical name for a container or blob resource for SAS signing. */ private String getCanonicalName(String account) { return CoreUtils.isNullOrEmpty(blobName) ? String.format("/blob/%s/%s", account, containerName) : String.format("/blob/%s/%s/%s", account, containerName, blobName.replace("\\", "/")); } private String stringToSign(String canonicalName) { String versionSegment = this.snapshotId == null ? this.versionId : this.snapshotId; return String.join("\n", this.permissions == null ? "" : permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, this.identifier == null ? "" : this.identifier, this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } }
yes. If we're giving env/props switch for this we should. Fortunately string to sign doesn't have that many variants - so far just two for all the SV we added so far.
private String stringToSign(final UserDelegationKey key, String canonicalName) { String versionSegment = this.snapshotId == null ? this.versionId : this.snapshotId; if (VERSION.compareTo(BlobServiceVersion.V2019_12_12.getVersion()) <= 0) { return String.join("\n", this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, key.getSignedObjectId() == null ? "" : key.getSignedObjectId(), key.getSignedTenantId() == null ? "" : key.getSignedTenantId(), key.getSignedStart() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedStart()), key.getSignedExpiry() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedExpiry()), key.getSignedService() == null ? "" : key.getSignedService(), key.getSignedVersion() == null ? "" : key.getSignedVersion(), this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } else { return String.join("\n", this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, key.getSignedObjectId() == null ? "" : key.getSignedObjectId(), key.getSignedTenantId() == null ? "" : key.getSignedTenantId(), key.getSignedStart() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedStart()), key.getSignedExpiry() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedExpiry()), key.getSignedService() == null ? "" : key.getSignedService(), key.getSignedVersion() == null ? "" : key.getSignedVersion(), this.authorizedAadObjectId == null ? "" : this.authorizedAadObjectId, "", /* suoid - empty since this applies to HNS only accounts. */ this.correlationId == null ? "" : this.correlationId, this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } }
if (VERSION.compareTo(BlobServiceVersion.V2019_12_12.getVersion()) <= 0) {
private String stringToSign(final UserDelegationKey key, String canonicalName) { String versionSegment = this.snapshotId == null ? this.versionId : this.snapshotId; if (VERSION.compareTo(BlobServiceVersion.V2019_12_12.getVersion()) <= 0) { return String.join("\n", this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, key.getSignedObjectId() == null ? "" : key.getSignedObjectId(), key.getSignedTenantId() == null ? "" : key.getSignedTenantId(), key.getSignedStart() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedStart()), key.getSignedExpiry() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedExpiry()), key.getSignedService() == null ? "" : key.getSignedService(), key.getSignedVersion() == null ? "" : key.getSignedVersion(), this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } else { return String.join("\n", this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, key.getSignedObjectId() == null ? "" : key.getSignedObjectId(), key.getSignedTenantId() == null ? "" : key.getSignedTenantId(), key.getSignedStart() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedStart()), key.getSignedExpiry() == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(key.getSignedExpiry()), key.getSignedService() == null ? "" : key.getSignedService(), key.getSignedVersion() == null ? "" : key.getSignedVersion(), this.authorizedAadObjectId == null ? "" : this.authorizedAadObjectId, "", /* suoid - empty since this applies to HNS only accounts. */ this.correlationId == null ? "" : this.correlationId, this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } }
class BlobSasImplUtil { /** * The SAS blob constant. */ private static final String SAS_BLOB_CONSTANT = "b"; /** * The SAS blob snapshot constant. */ private static final String SAS_BLOB_SNAPSHOT_CONSTANT = "bs"; /** * The SAS blob version constant. */ private static final String SAS_BLOB_VERSION_CONSTANT = "bv"; /** * The SAS blob container constant. */ private static final String SAS_CONTAINER_CONSTANT = "c"; private static final ClientLogger LOGGER = new ClientLogger(BlobSasImplUtil.class); private static final String VERSION = Configuration.getGlobalConfiguration() .get(Constants.PROPERTY_AZURE_STORAGE_SAS_SERVICE_VERSION, BlobServiceVersion.getLatest().getVersion()); private SasProtocol protocol; private OffsetDateTime startTime; private OffsetDateTime expiryTime; private String permissions; private SasIpRange sasIpRange; private String containerName; private String blobName; private String resource; private String snapshotId; private String versionId; private String identifier; private String cacheControl; private String contentDisposition; private String contentEncoding; private String contentLanguage; private String contentType; private String authorizedAadObjectId; private String correlationId; /** * Creates a new {@link BlobSasImplUtil} with the specified parameters * * @param sasValues {@link BlobServiceSasSignatureValues} * @param containerName The container name */ public BlobSasImplUtil(BlobServiceSasSignatureValues sasValues, String containerName) { this(sasValues, containerName, null, null, null); } /** * Creates a new {@link BlobSasImplUtil} with the specified parameters * * @param sasValues {@link BlobServiceSasSignatureValues} * @param containerName The container name * @param blobName The blob name * @param snapshotId The snapshot id * @param versionId The version id */ public BlobSasImplUtil(BlobServiceSasSignatureValues sasValues, String containerName, String blobName, String snapshotId, String versionId) { Objects.requireNonNull(sasValues); if (snapshotId != null && versionId != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'snapshot' and 'versionId' cannot be used at the same time.")); } this.protocol = sasValues.getProtocol(); this.startTime = sasValues.getStartTime(); this.expiryTime = sasValues.getExpiryTime(); this.permissions = sasValues.getPermissions(); this.sasIpRange = sasValues.getSasIpRange(); this.containerName = containerName; this.blobName = blobName; this.snapshotId = snapshotId; this.versionId = versionId; this.identifier = sasValues.getIdentifier(); this.cacheControl = sasValues.getCacheControl(); this.contentDisposition = sasValues.getContentDisposition(); this.contentEncoding = sasValues.getContentEncoding(); this.contentLanguage = sasValues.getContentLanguage(); this.contentType = sasValues.getContentType(); this.authorizedAadObjectId = sasValues.getPreauthorizedAgentObjectId(); this.correlationId = sasValues.getCorrelationId(); } /** * Generates a Sas signed with a {@link StorageSharedKeyCredential} * * @param storageSharedKeyCredentials {@link StorageSharedKeyCredential} * @param context Additional context that is passed through the code when generating a SAS. * @return A String representing the Sas */ public String generateSas(StorageSharedKeyCredential storageSharedKeyCredentials, Context context) { StorageImplUtils.assertNotNull("storageSharedKeyCredentials", storageSharedKeyCredentials); ensureState(); final String canonicalName = getCanonicalName(storageSharedKeyCredentials.getAccountName()); final String stringToSign = stringToSign(canonicalName); StorageImplUtils.logStringToSign(LOGGER, stringToSign, context); final String signature = storageSharedKeyCredentials.computeHmac256(stringToSign); return encode(null /* userDelegationKey */, signature); } /** * Generates a Sas signed with a {@link UserDelegationKey} * * @param delegationKey {@link UserDelegationKey} * @param accountName The account name * @param context Additional context that is passed through the code when generating a SAS. * @return A String representing the Sas */ public String generateUserDelegationSas(UserDelegationKey delegationKey, String accountName, Context context) { StorageImplUtils.assertNotNull("delegationKey", delegationKey); StorageImplUtils.assertNotNull("accountName", accountName); ensureState(); final String canonicalName = getCanonicalName(accountName); final String stringToSign = stringToSign(delegationKey, canonicalName); StorageImplUtils.logStringToSign(LOGGER, stringToSign, context); String signature = StorageImplUtils.computeHMac256(delegationKey.getValue(), stringToSign); return encode(delegationKey, signature); } /** * Encodes a Sas from the values in this type. * @param userDelegationKey {@link UserDelegationKey} * @param signature The signature of the Sas. * @return A String representing the Sas. */ private String encode(UserDelegationKey userDelegationKey, String signature) { /* We should be url-encoding each key and each value, but because we know all the keys and values will encode to themselves, we cheat except for the signature value. */ StringBuilder sb = new StringBuilder(); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SERVICE_VERSION, VERSION); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PROTOCOL, this.protocol); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_START_TIME, formatQueryParameterDate(this.startTime)); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_EXPIRY_TIME, formatQueryParameterDate(this.expiryTime)); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_IP_RANGE, this.sasIpRange); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_IDENTIFIER, this.identifier); if (userDelegationKey != null) { tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_OBJECT_ID, userDelegationKey.getSignedObjectId()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_TENANT_ID, userDelegationKey.getSignedTenantId()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_START, formatQueryParameterDate(userDelegationKey.getSignedStart())); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_EXPIRY, formatQueryParameterDate(userDelegationKey.getSignedExpiry())); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_SERVICE, userDelegationKey.getSignedService()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_VERSION, userDelegationKey.getSignedVersion()); /* Only parameters relevant for user delegation SAS. */ tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PREAUTHORIZED_AGENT_OBJECT_ID, this.authorizedAadObjectId); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CORRELATION_ID, this.correlationId); } tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_RESOURCE, this.resource); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_PERMISSIONS, this.permissions); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNATURE, signature); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CACHE_CONTROL, this.cacheControl); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_DISPOSITION, this.contentDisposition); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_ENCODING, this.contentEncoding); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_LANGUAGE, this.contentLanguage); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_TYPE, this.contentType); return sb.toString(); } /** * Ensures that the builder's properties are in a consistent state. * 1. If there is no version, use latest. * 2. If there is no identifier set, ensure expiryTime and permissions are set. * 3. Resource name is chosen by: * a. If "BlobName" is _not_ set, it is a container resource. * b. Otherwise, if "SnapshotId" is set, it is a blob snapshot resource. * c. Otherwise, if "VersionId" is set, it is a blob version resource. * d. Otherwise, it is a blob resource. * 4. Reparse permissions depending on what the resource is. If it is an unrecognized resource, do nothing. * * Taken from: * https: * https: */ private void ensureState() { if (identifier == null) { if (expiryTime == null || permissions == null) { throw LOGGER.logExceptionAsError(new IllegalStateException("If identifier is not set, expiry time " + "and permissions must be set")); } } if (CoreUtils.isNullOrEmpty(blobName)) { resource = SAS_CONTAINER_CONSTANT; } else if (snapshotId != null) { resource = SAS_BLOB_SNAPSHOT_CONSTANT; } else if (versionId != null) { resource = SAS_BLOB_VERSION_CONSTANT; } else { resource = SAS_BLOB_CONSTANT; } if (permissions != null) { switch (resource) { case SAS_BLOB_CONSTANT: case SAS_BLOB_SNAPSHOT_CONSTANT: case SAS_BLOB_VERSION_CONSTANT: permissions = BlobSasPermission.parse(permissions).toString(); break; case SAS_CONTAINER_CONSTANT: permissions = BlobContainerSasPermission.parse(permissions).toString(); break; default: LOGGER.info("Not re-parsing permissions. Resource type '{}' is unknown.", resource); break; } } } /** * Computes the canonical name for a container or blob resource for SAS signing. */ private String getCanonicalName(String account) { return CoreUtils.isNullOrEmpty(blobName) ? String.format("/blob/%s/%s", account, containerName) : String.format("/blob/%s/%s/%s", account, containerName, blobName.replace("\\", "/")); } private String stringToSign(String canonicalName) { String versionSegment = this.snapshotId == null ? this.versionId : this.snapshotId; return String.join("\n", this.permissions == null ? "" : permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, this.identifier == null ? "" : this.identifier, this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } }
class BlobSasImplUtil { /** * The SAS blob constant. */ private static final String SAS_BLOB_CONSTANT = "b"; /** * The SAS blob snapshot constant. */ private static final String SAS_BLOB_SNAPSHOT_CONSTANT = "bs"; /** * The SAS blob version constant. */ private static final String SAS_BLOB_VERSION_CONSTANT = "bv"; /** * The SAS blob container constant. */ private static final String SAS_CONTAINER_CONSTANT = "c"; private static final ClientLogger LOGGER = new ClientLogger(BlobSasImplUtil.class); private static final String VERSION = Configuration.getGlobalConfiguration() .get(Constants.PROPERTY_AZURE_STORAGE_SAS_SERVICE_VERSION, BlobServiceVersion.getLatest().getVersion()); private SasProtocol protocol; private OffsetDateTime startTime; private OffsetDateTime expiryTime; private String permissions; private SasIpRange sasIpRange; private String containerName; private String blobName; private String resource; private String snapshotId; private String versionId; private String identifier; private String cacheControl; private String contentDisposition; private String contentEncoding; private String contentLanguage; private String contentType; private String authorizedAadObjectId; private String correlationId; /** * Creates a new {@link BlobSasImplUtil} with the specified parameters * * @param sasValues {@link BlobServiceSasSignatureValues} * @param containerName The container name */ public BlobSasImplUtil(BlobServiceSasSignatureValues sasValues, String containerName) { this(sasValues, containerName, null, null, null); } /** * Creates a new {@link BlobSasImplUtil} with the specified parameters * * @param sasValues {@link BlobServiceSasSignatureValues} * @param containerName The container name * @param blobName The blob name * @param snapshotId The snapshot id * @param versionId The version id */ public BlobSasImplUtil(BlobServiceSasSignatureValues sasValues, String containerName, String blobName, String snapshotId, String versionId) { Objects.requireNonNull(sasValues); if (snapshotId != null && versionId != null) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'snapshot' and 'versionId' cannot be used at the same time.")); } this.protocol = sasValues.getProtocol(); this.startTime = sasValues.getStartTime(); this.expiryTime = sasValues.getExpiryTime(); this.permissions = sasValues.getPermissions(); this.sasIpRange = sasValues.getSasIpRange(); this.containerName = containerName; this.blobName = blobName; this.snapshotId = snapshotId; this.versionId = versionId; this.identifier = sasValues.getIdentifier(); this.cacheControl = sasValues.getCacheControl(); this.contentDisposition = sasValues.getContentDisposition(); this.contentEncoding = sasValues.getContentEncoding(); this.contentLanguage = sasValues.getContentLanguage(); this.contentType = sasValues.getContentType(); this.authorizedAadObjectId = sasValues.getPreauthorizedAgentObjectId(); this.correlationId = sasValues.getCorrelationId(); } /** * Generates a Sas signed with a {@link StorageSharedKeyCredential} * * @param storageSharedKeyCredentials {@link StorageSharedKeyCredential} * @param context Additional context that is passed through the code when generating a SAS. * @return A String representing the Sas */ public String generateSas(StorageSharedKeyCredential storageSharedKeyCredentials, Context context) { StorageImplUtils.assertNotNull("storageSharedKeyCredentials", storageSharedKeyCredentials); ensureState(); final String canonicalName = getCanonicalName(storageSharedKeyCredentials.getAccountName()); final String stringToSign = stringToSign(canonicalName); StorageImplUtils.logStringToSign(LOGGER, stringToSign, context); final String signature = storageSharedKeyCredentials.computeHmac256(stringToSign); return encode(null /* userDelegationKey */, signature); } /** * Generates a Sas signed with a {@link UserDelegationKey} * * @param delegationKey {@link UserDelegationKey} * @param accountName The account name * @param context Additional context that is passed through the code when generating a SAS. * @return A String representing the Sas */ public String generateUserDelegationSas(UserDelegationKey delegationKey, String accountName, Context context) { StorageImplUtils.assertNotNull("delegationKey", delegationKey); StorageImplUtils.assertNotNull("accountName", accountName); ensureState(); final String canonicalName = getCanonicalName(accountName); final String stringToSign = stringToSign(delegationKey, canonicalName); StorageImplUtils.logStringToSign(LOGGER, stringToSign, context); String signature = StorageImplUtils.computeHMac256(delegationKey.getValue(), stringToSign); return encode(delegationKey, signature); } /** * Encodes a Sas from the values in this type. * @param userDelegationKey {@link UserDelegationKey} * @param signature The signature of the Sas. * @return A String representing the Sas. */ private String encode(UserDelegationKey userDelegationKey, String signature) { /* We should be url-encoding each key and each value, but because we know all the keys and values will encode to themselves, we cheat except for the signature value. */ StringBuilder sb = new StringBuilder(); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SERVICE_VERSION, VERSION); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PROTOCOL, this.protocol); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_START_TIME, formatQueryParameterDate(this.startTime)); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_EXPIRY_TIME, formatQueryParameterDate(this.expiryTime)); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_IP_RANGE, this.sasIpRange); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_IDENTIFIER, this.identifier); if (userDelegationKey != null) { tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_OBJECT_ID, userDelegationKey.getSignedObjectId()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_TENANT_ID, userDelegationKey.getSignedTenantId()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_START, formatQueryParameterDate(userDelegationKey.getSignedStart())); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_EXPIRY, formatQueryParameterDate(userDelegationKey.getSignedExpiry())); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_SERVICE, userDelegationKey.getSignedService()); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_KEY_VERSION, userDelegationKey.getSignedVersion()); /* Only parameters relevant for user delegation SAS. */ tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PREAUTHORIZED_AGENT_OBJECT_ID, this.authorizedAadObjectId); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CORRELATION_ID, this.correlationId); } tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_RESOURCE, this.resource); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_PERMISSIONS, this.permissions); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNATURE, signature); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CACHE_CONTROL, this.cacheControl); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_DISPOSITION, this.contentDisposition); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_ENCODING, this.contentEncoding); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_LANGUAGE, this.contentLanguage); tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_CONTENT_TYPE, this.contentType); return sb.toString(); } /** * Ensures that the builder's properties are in a consistent state. * 1. If there is no version, use latest. * 2. If there is no identifier set, ensure expiryTime and permissions are set. * 3. Resource name is chosen by: * a. If "BlobName" is _not_ set, it is a container resource. * b. Otherwise, if "SnapshotId" is set, it is a blob snapshot resource. * c. Otherwise, if "VersionId" is set, it is a blob version resource. * d. Otherwise, it is a blob resource. * 4. Reparse permissions depending on what the resource is. If it is an unrecognized resource, do nothing. * * Taken from: * https: * https: */ private void ensureState() { if (identifier == null) { if (expiryTime == null || permissions == null) { throw LOGGER.logExceptionAsError(new IllegalStateException("If identifier is not set, expiry time " + "and permissions must be set")); } } if (CoreUtils.isNullOrEmpty(blobName)) { resource = SAS_CONTAINER_CONSTANT; } else if (snapshotId != null) { resource = SAS_BLOB_SNAPSHOT_CONSTANT; } else if (versionId != null) { resource = SAS_BLOB_VERSION_CONSTANT; } else { resource = SAS_BLOB_CONSTANT; } if (permissions != null) { switch (resource) { case SAS_BLOB_CONSTANT: case SAS_BLOB_SNAPSHOT_CONSTANT: case SAS_BLOB_VERSION_CONSTANT: permissions = BlobSasPermission.parse(permissions).toString(); break; case SAS_CONTAINER_CONSTANT: permissions = BlobContainerSasPermission.parse(permissions).toString(); break; default: LOGGER.info("Not re-parsing permissions. Resource type '{}' is unknown.", resource); break; } } } /** * Computes the canonical name for a container or blob resource for SAS signing. */ private String getCanonicalName(String account) { return CoreUtils.isNullOrEmpty(blobName) ? String.format("/blob/%s/%s", account, containerName) : String.format("/blob/%s/%s/%s", account, containerName, blobName.replace("\\", "/")); } private String stringToSign(String canonicalName) { String versionSegment = this.snapshotId == null ? this.versionId : this.snapshotId; return String.join("\n", this.permissions == null ? "" : permissions, this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), canonicalName, this.identifier == null ? "" : this.identifier, this.sasIpRange == null ? "" : this.sasIpRange.toString(), this.protocol == null ? "" : this.protocol.toString(), VERSION, resource, versionSegment == null ? "" : versionSegment, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, this.contentEncoding == null ? "" : this.contentEncoding, this.contentLanguage == null ? "" : this.contentLanguage, this.contentType == null ? "" : this.contentType ); } }
I have a few questions: - does it mean we're now supporting `@JsonAnySetter` together with `@JsonFlatten` (and we didn't before)? - Do we also want it to work with additional properties (and does it work?)
private void handleFlatteningForField(AnnotatedField annotatedField, JsonNode jsonNode) { final JsonProperty jsonProperty = annotatedField.getAnnotation(JsonProperty.class); if (jsonProperty != null) { final String jsonPropValue = jsonProperty.value(); if (jsonNode.has(jsonPropValue)) { final String escapedJsonPropValue = jsonPropValue.replace(".", "\\."); ((ObjectNode) jsonNode).set(escapedJsonPropValue, jsonNode.get(jsonPropValue)); } if ((classHasJsonFlatten || annotatedField.hasAnnotation(JsonFlatten.class)) && IS_FLATTENED_PATTERN.matcher(jsonPropValue).matches()) { String[] jsonNodeKeys = Arrays.stream(SPLIT_KEY_PATTERN.split(jsonPropValue)) .map(FlatteningDeserializer::unescapeEscapedDots) .toArray(String[]::new); List<JsonNode> nodePath = new ArrayList<>(); nodePath.add(jsonNode); JsonNode nodeToAdd = jsonNode; for (String jsonNodeKey : jsonNodeKeys) { nodeToAdd = nodeToAdd.get(jsonNodeKey); if (nodeToAdd == null) { break; } nodePath.add(nodeToAdd); } if (nodePath.size() == 1) { ((ObjectNode) jsonNode).set(jsonPropValue, null); return; } if (!nodePath.get(nodePath.size() - 2).has(jsonNodeKeys[jsonNodeKeys.length - 1])) { ((ObjectNode) jsonNode).set(jsonPropValue, null); } else { ((ObjectNode) jsonNode).set(jsonPropValue, nodePath.get(nodePath.size() - 1)); } for (int i = nodePath.size() - 2; i >= 0; i--) { if (i == nodePath.size() - 2 && nodePath.size() - 1 != jsonNodeKeys.length && nodePath.get(i).get(jsonNodeKeys[i]).size() != 0) { break; } ((ObjectNode) nodePath.get(i)).remove(jsonNodeKeys[i]); if (nodePath.get(i).size() > 0) { break; } } } } }
private void handleFlatteningForField(AnnotatedField annotatedField, JsonNode jsonNode) { final JsonProperty jsonProperty = annotatedField.getAnnotation(JsonProperty.class); if (jsonProperty != null) { final String jsonPropValue = jsonProperty.value(); if (jsonNode.has(jsonPropValue)) { final String escapedJsonPropValue = jsonPropValue.replace(".", "\\."); ((ObjectNode) jsonNode).set(escapedJsonPropValue, jsonNode.get(jsonPropValue)); } if ((classHasJsonFlatten || annotatedField.hasAnnotation(JsonFlatten.class)) && IS_FLATTENED_PATTERN.matcher(jsonPropValue).matches()) { String[] jsonNodeKeys = Arrays.stream(SPLIT_KEY_PATTERN.split(jsonPropValue)) .map(FlatteningDeserializer::unescapeEscapedDots) .toArray(String[]::new); List<JsonNode> nodePath = new ArrayList<>(); nodePath.add(jsonNode); JsonNode nodeToAdd = jsonNode; for (String jsonNodeKey : jsonNodeKeys) { nodeToAdd = nodeToAdd.get(jsonNodeKey); if (nodeToAdd == null) { break; } nodePath.add(nodeToAdd); } if (nodePath.size() == 1) { ((ObjectNode) jsonNode).set(jsonPropValue, null); return; } if (!nodePath.get(nodePath.size() - 2).has(jsonNodeKeys[jsonNodeKeys.length - 1])) { ((ObjectNode) jsonNode).set(jsonPropValue, null); } else { ((ObjectNode) jsonNode).set(jsonPropValue, nodePath.get(nodePath.size() - 1)); } for (int i = nodePath.size() - 2; i >= 0; i--) { if (i == nodePath.size() - 2 && nodePath.size() - 1 != jsonNodeKeys.length && nodePath.get(i).get(jsonNodeKeys[i]).size() != 0) { break; } ((ObjectNode) nodePath.get(i)).remove(jsonNodeKeys[i]); if (nodePath.get(i).size() > 0) { break; } } } } }
class that field belongs to */
class that field belongs to */
Change the method name.
public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenant-id"); String clientId = System.getProperty("azure.keyvault.client-id"); String clientSecret = System.getProperty("azure.keyvault.client-secret"); String managedIdentity = System.getProperty("azure.keyvault.managed-identity"); if (clientId != null) { keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } else { keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity); } long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval")) .map(Long::valueOf) .orElse(0L); refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate")) .map(Boolean::parseBoolean) .orElse(false); jreCertificates = JreCertificates.getInstance(); wellKnowCertificates = SpecificPathCertificates.getFileSystemCertificates(wellKnowPath); customCertificates = SpecificPathCertificates.getFileSystemCertificates(customPath); keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient); classpathCertificates = new ClasspathCertificates(); allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates); }
customCertificates = SpecificPathCertificates.getFileSystemCertificates(customPath);
public KeyVaultKeyStore() { creationDate = new Date(); String keyVaultUri = System.getProperty("azure.keyvault.uri"); String tenantId = System.getProperty("azure.keyvault.tenant-id"); String clientId = System.getProperty("azure.keyvault.client-id"); String clientSecret = System.getProperty("azure.keyvault.client-secret"); String managedIdentity = System.getProperty("azure.keyvault.managed-identity"); if (clientId != null) { keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret); } else { keyVaultClient = new KeyVaultClient(keyVaultUri, managedIdentity); } long refreshInterval = Optional.ofNullable(System.getProperty("azure.keyvault.jca.certificates-refresh-interval")) .map(Long::valueOf) .orElse(0L); refreshCertificatesWhenHaveUnTrustCertificate = Optional.ofNullable(System.getProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate")) .map(Boolean::parseBoolean) .orElse(false); jreCertificates = JreCertificates.getInstance(); wellKnowCertificates = SpecificPathCertificates.getSpecificPathCertificates(wellKnowPath); customCertificates = SpecificPathCertificates.getSpecificPathCertificates(customPath); keyVaultCertificates = new KeyVaultCertificates(refreshInterval, keyVaultClient); classpathCertificates = new ClasspathCertificates(); allCertificates = Arrays.asList(jreCertificates, wellKnowCertificates, customCertificates, keyVaultCertificates, classpathCertificates); }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the key-store name. */ public static final String KEY_STORE_TYPE = "AzureKeyVault"; /** * Stores the algorithm name. */ public static final String ALGORITHM_NAME = KEY_STORE_TYPE; /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the Jre key store certificates. */ private final JreCertificates jreCertificates; /** * Store well Know certificates loaded from specific path. */ private final SpecificPathCertificates wellKnowCertificates; /** * Store custom certificates loaded from specific path. */ private final SpecificPathCertificates customCertificates; /** * Store certificates loaded from KeyVault. */ private final KeyVaultCertificates keyVaultCertificates; /** * Store certificates loaded from classpath. */ private final ClasspathCertificates classpathCertificates; /** * Stores all the certificates. */ private final List<AzureCertificates> allCertificates; /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVaultClient; private final boolean refreshCertificatesWhenHaveUnTrustCertificate; /** * Store the path where the well know certificate is placed */ final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known")) .orElse("/etc/certs/well-known/"); /** * Store the path where the custom certificate is placed */ final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom")) .orElse("/etc/certs/custom/"); /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, * <code>azure.keyvault.aadAuthenticationUrl</code>, * <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> and * <code>azure.keyvault.managedIdentity</code> to initialize the * Key Vault client. * </p> */ @Override public Enumeration<String> engineAliases() { return Collections.enumeration(getAllAliases()); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { allCertificates.forEach(a -> a.deleteEntry(alias)); } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate = allCertificates.stream() .map(AzureCertificates::getCertificates) .filter(a -> a.containsKey(alias)) .findFirst() .map(certificates -> certificates.get(alias)) .orElse(null); if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) { KeyVaultCertificates.updateLastForceRefreshTime(); certificate = keyVaultCertificates.getCertificates().get(alias); } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { List<String> aliasList = getAllAliases(); for (String candidateAlias : aliasList) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) { alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert); } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return new Date(creationDate.getTime()); } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { return allCertificates.stream() .map(AzureCertificates::getCertificateKeys) .filter(a -> a.containsKey(alias)) .findFirst() .map(certificateKeys -> certificateKeys.get(alias)) .orElse(null); } @Override public boolean engineIsCertificateEntry(String alias) { return getAllAliases().contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; if (parameter.getClientId() != null) { keyVaultClient = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } else if (parameter.getManagedIdentity() != null) { keyVaultClient = new KeyVaultClient( parameter.getUri(), parameter.getManagedIdentity() ); } else { keyVaultClient = new KeyVaultClient(parameter.getUri()); } keyVaultCertificates.setKeyVaultClient(keyVaultClient); } loadCertificates(); } @Override public void engineLoad(InputStream stream, char[] password) { loadCertificates(); } private void loadCertificates() { wellKnowCertificates.loadCertificatesFromFileSystem(); customCertificates.loadCertificatesFromFileSystem(); classpathCertificates.loadCertificatesFromClasspath(); } private List<String> getAllAliases() { List<String> allAliases = new ArrayList<>(); allAliases.addAll(jreCertificates.getAliases()); Map<String, List<String>> aliasLists = new HashMap<>(); aliasLists.put("well known certificates", wellKnowCertificates.getAliases()); aliasLists.put("custom certificates", customCertificates.getAliases()); aliasLists.put("key vault certificates", keyVaultCertificates.getAliases()); aliasLists.put("class path certificates", classpathCertificates.getAliases()); aliasLists.forEach((key, value) -> { value.forEach(a -> { if (allAliases.contains(a)) { LOGGER.log(FINE, String.format("The certificate with alias %s under %s already exists", a, key)); } else { allAliases.add(a); } }); }); return allAliases; } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (getAllAliases().contains(alias)) { LOGGER.log(WARNING, "Cannot overwrite own certificate"); return; } classpathCertificates.setCertificateEntry(alias, certificate); } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return getAllAliases().size(); } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } }
class KeyVaultKeyStore extends KeyStoreSpi { /** * Stores the key-store name. */ public static final String KEY_STORE_TYPE = "AzureKeyVault"; /** * Stores the algorithm name. */ public static final String ALGORITHM_NAME = KEY_STORE_TYPE; /** * Stores the logger. */ private static final Logger LOGGER = Logger.getLogger(KeyVaultKeyStore.class.getName()); /** * Stores the Jre key store certificates. */ private final JreCertificates jreCertificates; /** * Store well Know certificates loaded from specific path. */ private final SpecificPathCertificates wellKnowCertificates; /** * Store custom certificates loaded from specific path. */ private final SpecificPathCertificates customCertificates; /** * Store certificates loaded from KeyVault. */ private final KeyVaultCertificates keyVaultCertificates; /** * Store certificates loaded from classpath. */ private final ClasspathCertificates classpathCertificates; /** * Stores all the certificates. */ private final List<AzureCertificates> allCertificates; /** * Stores the creation date. */ private final Date creationDate; /** * Stores the key vault client. */ private KeyVaultClient keyVaultClient; private final boolean refreshCertificatesWhenHaveUnTrustCertificate; /** * Store the path where the well know certificate is placed */ final String wellKnowPath = Optional.ofNullable(System.getProperty("azure.cert-path.well-known")) .orElse("/etc/certs/well-known/"); /** * Store the path where the custom certificate is placed */ final String customPath = Optional.ofNullable(System.getProperty("azure.cert-path.custom")) .orElse("/etc/certs/custom/"); /** * Constructor. * * <p> * The constructor uses System.getProperty for * <code>azure.keyvault.uri</code>, * <code>azure.keyvault.aadAuthenticationUrl</code>, * <code>azure.keyvault.tenantId</code>, * <code>azure.keyvault.clientId</code>, * <code>azure.keyvault.clientSecret</code> and * <code>azure.keyvault.managedIdentity</code> to initialize the * Key Vault client. * </p> */ @Override public Enumeration<String> engineAliases() { return Collections.enumeration(getAllAliases()); } @Override public boolean engineContainsAlias(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineDeleteEntry(String alias) { allCertificates.forEach(a -> a.deleteEntry(alias)); } @Override public boolean engineEntryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass) { return super.engineEntryInstanceOf(alias, entryClass); } @Override public Certificate engineGetCertificate(String alias) { Certificate certificate = allCertificates.stream() .map(AzureCertificates::getCertificates) .filter(a -> a.containsKey(alias)) .findFirst() .map(certificates -> certificates.get(alias)) .orElse(null); if (refreshCertificatesWhenHaveUnTrustCertificate && certificate == null) { KeyVaultCertificates.updateLastForceRefreshTime(); certificate = keyVaultCertificates.getCertificates().get(alias); } return certificate; } @Override public String engineGetCertificateAlias(Certificate cert) { String alias = null; if (cert != null) { List<String> aliasList = getAllAliases(); for (String candidateAlias : aliasList) { Certificate certificate = engineGetCertificate(candidateAlias); if (certificate.equals(cert)) { alias = candidateAlias; break; } } } if (refreshCertificatesWhenHaveUnTrustCertificate && alias == null) { alias = keyVaultCertificates.refreshAndGetAliasByCertificate(cert); } return alias; } @Override public Certificate[] engineGetCertificateChain(String alias) { Certificate[] chain = null; Certificate certificate = engineGetCertificate(alias); if (certificate != null) { chain = new Certificate[1]; chain[0] = certificate; } return chain; } @Override public Date engineGetCreationDate(String alias) { return new Date(creationDate.getTime()); } @Override public KeyStore.Entry engineGetEntry(String alias, KeyStore.ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { return super.engineGetEntry(alias, protParam); } @Override public Key engineGetKey(String alias, char[] password) { return allCertificates.stream() .map(AzureCertificates::getCertificateKeys) .filter(a -> a.containsKey(alias)) .findFirst() .map(certificateKeys -> certificateKeys.get(alias)) .orElse(null); } @Override public boolean engineIsCertificateEntry(String alias) { return getAllAliases().contains(alias); } @Override public boolean engineIsKeyEntry(String alias) { return engineIsCertificateEntry(alias); } @Override public void engineLoad(KeyStore.LoadStoreParameter param) { if (param instanceof KeyVaultLoadStoreParameter) { KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param; if (parameter.getClientId() != null) { keyVaultClient = new KeyVaultClient( parameter.getUri(), parameter.getTenantId(), parameter.getClientId(), parameter.getClientSecret()); } else if (parameter.getManagedIdentity() != null) { keyVaultClient = new KeyVaultClient( parameter.getUri(), parameter.getManagedIdentity() ); } else { keyVaultClient = new KeyVaultClient(parameter.getUri()); } keyVaultCertificates.setKeyVaultClient(keyVaultClient); } classpathCertificates.loadCertificatesFromClasspath(); } @Override public void engineLoad(InputStream stream, char[] password) { classpathCertificates.loadCertificatesFromClasspath(); } private List<String> getAllAliases() { List<String> allAliases = new ArrayList<>(); allAliases.addAll(jreCertificates.getAliases()); Map<String, List<String>> aliasLists = new HashMap<>(); aliasLists.put("well known certificates", wellKnowCertificates.getAliases()); aliasLists.put("custom certificates", customCertificates.getAliases()); aliasLists.put("key vault certificates", keyVaultCertificates.getAliases()); aliasLists.put("class path certificates", classpathCertificates.getAliases()); aliasLists.forEach((key, value) -> { value.forEach(a -> { if (allAliases.contains(a)) { LOGGER.log(FINE, String.format("The certificate with alias %s under %s already exists", a, key)); } else { allAliases.add(a); } }); }); return allAliases; } @Override public void engineSetCertificateEntry(String alias, Certificate certificate) { if (getAllAliases().contains(alias)) { LOGGER.log(WARNING, "Cannot overwrite own certificate"); return; } classpathCertificates.setCertificateEntry(alias, certificate); } @Override public void engineSetEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) throws KeyStoreException { super.engineSetEntry(alias, entry, protParam); } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) { } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) { } @Override public int engineSize() { return getAllAliases().size(); } @Override public void engineStore(OutputStream stream, char[] password) { } @Override public void engineStore(KeyStore.LoadStoreParameter param) { } }
Mark.
public void testSetCertificateEntry() { specificPathCertificates = SpecificPathCertificates.getFileSystemCertificates(getFilePath("custom\\")); specificPathCertificates.loadCertificatesFromFileSystem(); Assertions.assertTrue(specificPathCertificates.getAliases().contains("sideload")); }
specificPathCertificates.loadCertificatesFromFileSystem();
public void testSetCertificateEntry() { specificPathCertificates = SpecificPathCertificates.getSpecificPathCertificates(getFilePath("custom\\")); Assertions.assertTrue(specificPathCertificates.getAliases().contains("sideload")); }
class SpecificPathCertificatesTest { SpecificPathCertificates specificPathCertificates; public static String getFilePath(String packageName) { String filepath = "\\src\\test\\resources\\" + packageName; return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator")); } @Test }
class SpecificPathCertificatesTest { SpecificPathCertificates specificPathCertificates; public static String getFilePath(String packageName) { String filepath = "\\src\\test\\resources\\" + packageName; return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator")); } @Test }
Can we delete this line after move `loadCertificatesFromFileSystem` to constructor?
public void testSetCertificateEntry() { specificPathCertificates = SpecificPathCertificates.getFileSystemCertificates(getFilePath("custom\\")); specificPathCertificates.loadCertificatesFromFileSystem(); Assertions.assertTrue(specificPathCertificates.getAliases().contains("sideload")); }
specificPathCertificates.loadCertificatesFromFileSystem();
public void testSetCertificateEntry() { specificPathCertificates = SpecificPathCertificates.getSpecificPathCertificates(getFilePath("custom\\")); Assertions.assertTrue(specificPathCertificates.getAliases().contains("sideload")); }
class SpecificPathCertificatesTest { SpecificPathCertificates specificPathCertificates; public static String getFilePath(String packageName) { String filepath = "\\src\\test\\resources\\" + packageName; return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator")); } @Test }
class SpecificPathCertificatesTest { SpecificPathCertificates specificPathCertificates; public static String getFilePath(String packageName) { String filepath = "\\src\\test\\resources\\" + packageName; return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator")); } @Test }
Mark.
public void testCertificatePriority2() { System.setProperty("azure.cert-path.custom", getFilePath("custom\\")); KeyVaultKeyStore ks = new KeyVaultKeyStore(); ks.engineLoad(null); X509Certificate fileSystemCertificate = getCertificateByFile(new File(getFilePath("custom\\sideload2.pem"))); X509Certificate classPathCertificate = getCertificateByFile(new File(getFilePath("keyvault\\sideload2.pem"))); assertEquals(fileSystemCertificate, ks.engineGetCertificate("sideload2")); assertNotEquals(classPathCertificate, ks.engineGetCertificate("sideload2")); }
X509Certificate fileSystemCertificate = getCertificateByFile(new File(getFilePath("custom\\sideload2.pem")));
public void testCertificatePriority2() { System.setProperty("azure.cert-path.custom", getFilePath("custom\\")); KeyVaultKeyStore ks = new KeyVaultKeyStore(); ks.engineLoad(null); X509Certificate specificPathCertificate = getCertificateByFile(new File(getFilePath("custom\\sideload2.pem"))); X509Certificate classPathCertificate = getCertificateByFile(new File(getFilePath("keyvault\\sideload2.pem"))); assertEquals(specificPathCertificate, ks.engineGetCertificate("sideload2")); assertNotEquals(classPathCertificate, ks.engineGetCertificate("sideload2")); }
class SpecificPathCertificatesTest { @BeforeAll public static void setEnvironmentProperty() { PropertyConvertorUtils.putEnvironmentPropertyToSystemPropertyForKeyVaultJca(); PropertyConvertorUtils.addKeyVaultJcaProvider(); } public static String getFilePath(String packageName) { String filepath = "\\src\\test\\resources\\" + packageName; return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator")); } @Test public void testGetFileSystemCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { System.setProperty("azure.cert-path.custom", getFilePath("custom")); KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore(); Assertions.assertNotNull(keyStore.getCertificate("sideload")); } @Test public void testCertificatePriority1() { System.setProperty("azure.cert-path.well-known", getFilePath("well-known\\")); System.setProperty("azure.cert-path.custom", getFilePath("custom\\")); KeyVaultKeyStore ks = new KeyVaultKeyStore(); ks.engineLoad(null); X509Certificate customCertificate = getCertificateByFile(new File(getFilePath("custom\\sideload.x509"))); X509Certificate wellKnownCertificate = getCertificateByFile(new File(getFilePath("well-known\\sideload.pem"))); assertEquals(wellKnownCertificate, ks.engineGetCertificate("sideload")); assertNotEquals(customCertificate, ks.engineGetCertificate("sideload")); } @Test private X509Certificate getCertificateByFile(File file) { X509Certificate certificate; try (InputStream inputStream = new FileInputStream(file); BufferedInputStream bytes = new BufferedInputStream(inputStream)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate(bytes); } catch (Exception e) { throw new ProviderException(e); } return certificate; } }
class SpecificPathCertificatesTest { @BeforeAll public static void setEnvironmentProperty() { PropertyConvertorUtils.putEnvironmentPropertyToSystemPropertyForKeyVaultJca(); PropertyConvertorUtils.addKeyVaultJcaProvider(); } public static String getFilePath(String packageName) { String filepath = "\\src\\test\\resources\\" + packageName; return System.getProperty("user.dir") + filepath.replace("\\", System.getProperty("file.separator")); } @Test public void testGetSpecificPathCertificate() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { System.setProperty("azure.cert-path.custom", getFilePath("custom")); KeyStore keyStore = PropertyConvertorUtils.getKeyVaultKeyStore(); Assertions.assertNotNull(keyStore.getCertificate("sideload")); } @Test public void testCertificatePriority1() { System.setProperty("azure.cert-path.well-known", getFilePath("well-known\\")); System.setProperty("azure.cert-path.custom", getFilePath("custom\\")); KeyVaultKeyStore ks = new KeyVaultKeyStore(); ks.engineLoad(null); X509Certificate customCertificate = getCertificateByFile(new File(getFilePath("custom\\sideload.x509"))); X509Certificate wellKnownCertificate = getCertificateByFile(new File(getFilePath("well-known\\sideload.pem"))); assertEquals(wellKnownCertificate, ks.engineGetCertificate("sideload")); assertNotEquals(customCertificate, ks.engineGetCertificate("sideload")); } @Test private X509Certificate getCertificateByFile(File file) { X509Certificate certificate; try (InputStream inputStream = new FileInputStream(file); BufferedInputStream bytes = new BufferedInputStream(inputStream)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate(bytes); } catch (Exception e) { throw new ProviderException(e); } return certificate; } }
I don't think you need this `isDebugEnabled()` check
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", grantedAuthorities); } return grantedAuthorities; }
if (LOGGER.isDebugEnabled()) {
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final Logger LOGGER = LoggerFactory.getLogger(AADJwtGrantedAuthoritiesConverter.class); private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.hasClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; } }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.containsClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; } }
nice catch, we should always fix deprecated code, thanks
private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.hasClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; }
if (jwt.hasClaim(claimName)) {
private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.containsClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final Logger LOGGER = LoggerFactory.getLogger(AADJwtGrantedAuthoritiesConverter.class); private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", grantedAuthorities); } return grantedAuthorities; } }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; } }
it seems too simple for a log, probably provide more context info? I'm not sure
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", grantedAuthorities); } return grantedAuthorities; }
LOGGER.debug("User's authorities: {}.", grantedAuthorities);
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final Logger LOGGER = LoggerFactory.getLogger(AADJwtGrantedAuthoritiesConverter.class); private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.hasClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; } }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.containsClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; } }
And this method is duplicated with `com.azure.spring.autoconfigure.b2c.AADB2CJwtGrantedAuthoritiesConverter#getAuthorities` could you also some refactor to remove this duplication code?
private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.hasClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; }
if (jwt.hasClaim(claimName)) {
private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.containsClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final Logger LOGGER = LoggerFactory.getLogger(AADJwtGrantedAuthoritiesConverter.class); private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", grantedAuthorities); } return grantedAuthorities; } }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; } }
How about `User's authorities created from jwt token: {}.`
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", grantedAuthorities); } return grantedAuthorities; }
LOGGER.debug("User's authorities: {}.", grantedAuthorities);
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final Logger LOGGER = LoggerFactory.getLogger(AADJwtGrantedAuthoritiesConverter.class); private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.hasClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; } }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.containsClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; } }
Mark.
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = oidcUserService.loadUser(userRequest); OidcIdToken idToken = oidcUser.getIdToken(); Set<String> authorityStrings = new HashSet<>(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(true); if (authentication != null) { return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER); } authorityStrings.addAll(extractRolesFromIdToken(idToken)); authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken())); Set<SimpleGrantedAuthority> authorities = authorityStrings.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); if (authorities.isEmpty()) { authorities = DEFAULT_AUTHORITY_SET; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", authorities); } String nameAttributeKey = Optional.of(userRequest) .map(OAuth2UserRequest::getClientRegistration) .map(ClientRegistration::getProviderDetails) .map(ClientRegistration.ProviderDetails::getUserInfoEndpoint) .map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName) .filter(StringUtils::hasText) .orElse(AADTokenClaim.NAME); DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey); session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser); return defaultOidcUser; }
LOGGER.debug("User's authorities: {}.", authorities);
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = oidcUserService.loadUser(userRequest); OidcIdToken idToken = oidcUser.getIdToken(); Set<String> authorityStrings = new HashSet<>(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(true); if (authentication != null) { LOGGER.debug("User {}'s authorities saved from session: {}.", authentication.getName(), authentication.getAuthorities()); return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER); } authorityStrings.addAll(extractRolesFromIdToken(idToken)); authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken())); Set<SimpleGrantedAuthority> authorities = authorityStrings.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); if (authorities.isEmpty()) { authorities = DEFAULT_AUTHORITY_SET; } String nameAttributeKey = Optional.of(userRequest) .map(OAuth2UserRequest::getClientRegistration) .map(ClientRegistration::getProviderDetails) .map(ClientRegistration.ProviderDetails::getUserInfoEndpoint) .map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName) .filter(StringUtils::hasText) .orElse(AADTokenClaim.NAME); LOGGER.debug("User {}'s authorities extracted by id token and access token: {}.", oidcUser.getClaim(nameAttributeKey), authorities); DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey); session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser); return defaultOidcUser; }
class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2UserService.class); private final OidcUserService oidcUserService; private final List<String> allowedGroupNames; private final Set<String> allowedGroupIds; private final boolean enableFullList; private final GraphClient graphClient; private static final String DEFAULT_OIDC_USER = "defaultOidcUser"; private static final String ROLES = "roles"; public AADOAuth2UserService(AADAuthenticationProperties properties) { this(properties, new GraphClient(properties)); } public AADOAuth2UserService(AADAuthenticationProperties properties, GraphClient graphClient) { allowedGroupNames = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupNames) .orElseGet(Collections::emptyList); allowedGroupIds = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupIds) .orElseGet(Collections::emptySet); enableFullList = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getEnableFullList) .orElse(false); this.oidcUserService = new OidcUserService(); this.graphClient = graphClient; } @Override Set<String> extractRolesFromIdToken(OidcIdToken idToken) { return Optional.ofNullable(idToken) .map(token -> (Collection<?>) token.getClaim(ROLES)) .filter(obj -> obj instanceof List<?>) .map(Collection::stream) .orElseGet(Stream::empty) .filter(s -> StringUtils.hasText(s.toString())) .map(role -> APPROLE_PREFIX + role) .collect(Collectors.toSet()); } Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) { if (allowedGroupNames.isEmpty() && allowedGroupIds.isEmpty()) { return Collections.emptySet(); } Set<String> roles = new HashSet<>(); GroupInformation groupInformation = getGroupInformation(accessToken); if (!allowedGroupNames.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsNames) .map(Collection::stream) .orElseGet(Stream::empty) .filter(allowedGroupNames::contains) .forEach(roles::add); } if (!allowedGroupIds.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsIds) .map(Collection::stream) .orElseGet(Stream::empty) .filter(this::isAllowedGroupId) .forEach(roles::add); } return roles.stream() .map(roleStr -> ROLE_PREFIX + roleStr) .collect(Collectors.toSet()); } private boolean isAllowedGroupId(String groupId) { if (enableFullList) { return true; } if (allowedGroupIds.size() == 1 && allowedGroupIds.contains("all")) { return true; } return allowedGroupIds.contains(groupId); } private GroupInformation getGroupInformation(OAuth2AccessToken accessToken) { return Optional.of(accessToken) .map(AbstractOAuth2Token::getTokenValue) .map(graphClient::getGroupInformation) .orElseGet(GroupInformation::new); } }
class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2UserService.class); private final OidcUserService oidcUserService; private final List<String> allowedGroupNames; private final Set<String> allowedGroupIds; private final boolean enableFullList; private final GraphClient graphClient; private static final String DEFAULT_OIDC_USER = "defaultOidcUser"; private static final String ROLES = "roles"; public AADOAuth2UserService(AADAuthenticationProperties properties) { this(properties, new GraphClient(properties)); } public AADOAuth2UserService(AADAuthenticationProperties properties, GraphClient graphClient) { allowedGroupNames = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupNames) .orElseGet(Collections::emptyList); allowedGroupIds = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupIds) .orElseGet(Collections::emptySet); enableFullList = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getEnableFullList) .orElse(false); this.oidcUserService = new OidcUserService(); this.graphClient = graphClient; } @Override Set<String> extractRolesFromIdToken(OidcIdToken idToken) { return Optional.ofNullable(idToken) .map(token -> (Collection<?>) token.getClaim(ROLES)) .filter(obj -> obj instanceof List<?>) .map(Collection::stream) .orElseGet(Stream::empty) .filter(s -> StringUtils.hasText(s.toString())) .map(role -> APPROLE_PREFIX + role) .collect(Collectors.toSet()); } Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) { if (allowedGroupNames.isEmpty() && allowedGroupIds.isEmpty()) { return Collections.emptySet(); } Set<String> roles = new HashSet<>(); GroupInformation groupInformation = getGroupInformation(accessToken); if (!allowedGroupNames.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsNames) .map(Collection::stream) .orElseGet(Stream::empty) .filter(allowedGroupNames::contains) .forEach(roles::add); } if (!allowedGroupIds.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsIds) .map(Collection::stream) .orElseGet(Stream::empty) .filter(this::isAllowedGroupId) .forEach(roles::add); } return roles.stream() .map(roleStr -> ROLE_PREFIX + roleStr) .collect(Collectors.toSet()); } private boolean isAllowedGroupId(String groupId) { if (enableFullList) { return true; } if (allowedGroupIds.size() == 1 && allowedGroupIds.contains("all")) { return true; } return allowedGroupIds.contains(groupId); } private GroupInformation getGroupInformation(OAuth2AccessToken accessToken) { return Optional.of(accessToken) .map(AbstractOAuth2Token::getTokenValue) .map(graphClient::getGroupInformation) .orElseGet(GroupInformation::new); } }
`User's authorities extracted by id token and access token: {}.`
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = oidcUserService.loadUser(userRequest); OidcIdToken idToken = oidcUser.getIdToken(); Set<String> authorityStrings = new HashSet<>(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(true); if (authentication != null) { return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER); } authorityStrings.addAll(extractRolesFromIdToken(idToken)); authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken())); Set<SimpleGrantedAuthority> authorities = authorityStrings.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); if (authorities.isEmpty()) { authorities = DEFAULT_AUTHORITY_SET; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", authorities); } String nameAttributeKey = Optional.of(userRequest) .map(OAuth2UserRequest::getClientRegistration) .map(ClientRegistration::getProviderDetails) .map(ClientRegistration.ProviderDetails::getUserInfoEndpoint) .map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName) .filter(StringUtils::hasText) .orElse(AADTokenClaim.NAME); DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey); session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser); return defaultOidcUser; }
LOGGER.debug("User's authorities: {}.", authorities);
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = oidcUserService.loadUser(userRequest); OidcIdToken idToken = oidcUser.getIdToken(); Set<String> authorityStrings = new HashSet<>(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(true); if (authentication != null) { LOGGER.debug("User {}'s authorities saved from session: {}.", authentication.getName(), authentication.getAuthorities()); return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER); } authorityStrings.addAll(extractRolesFromIdToken(idToken)); authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken())); Set<SimpleGrantedAuthority> authorities = authorityStrings.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); if (authorities.isEmpty()) { authorities = DEFAULT_AUTHORITY_SET; } String nameAttributeKey = Optional.of(userRequest) .map(OAuth2UserRequest::getClientRegistration) .map(ClientRegistration::getProviderDetails) .map(ClientRegistration.ProviderDetails::getUserInfoEndpoint) .map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName) .filter(StringUtils::hasText) .orElse(AADTokenClaim.NAME); LOGGER.debug("User {}'s authorities extracted by id token and access token: {}.", oidcUser.getClaim(nameAttributeKey), authorities); DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey); session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser); return defaultOidcUser; }
class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2UserService.class); private final OidcUserService oidcUserService; private final List<String> allowedGroupNames; private final Set<String> allowedGroupIds; private final boolean enableFullList; private final GraphClient graphClient; private static final String DEFAULT_OIDC_USER = "defaultOidcUser"; private static final String ROLES = "roles"; public AADOAuth2UserService(AADAuthenticationProperties properties) { this(properties, new GraphClient(properties)); } public AADOAuth2UserService(AADAuthenticationProperties properties, GraphClient graphClient) { allowedGroupNames = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupNames) .orElseGet(Collections::emptyList); allowedGroupIds = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupIds) .orElseGet(Collections::emptySet); enableFullList = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getEnableFullList) .orElse(false); this.oidcUserService = new OidcUserService(); this.graphClient = graphClient; } @Override Set<String> extractRolesFromIdToken(OidcIdToken idToken) { return Optional.ofNullable(idToken) .map(token -> (Collection<?>) token.getClaim(ROLES)) .filter(obj -> obj instanceof List<?>) .map(Collection::stream) .orElseGet(Stream::empty) .filter(s -> StringUtils.hasText(s.toString())) .map(role -> APPROLE_PREFIX + role) .collect(Collectors.toSet()); } Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) { if (allowedGroupNames.isEmpty() && allowedGroupIds.isEmpty()) { return Collections.emptySet(); } Set<String> roles = new HashSet<>(); GroupInformation groupInformation = getGroupInformation(accessToken); if (!allowedGroupNames.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsNames) .map(Collection::stream) .orElseGet(Stream::empty) .filter(allowedGroupNames::contains) .forEach(roles::add); } if (!allowedGroupIds.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsIds) .map(Collection::stream) .orElseGet(Stream::empty) .filter(this::isAllowedGroupId) .forEach(roles::add); } return roles.stream() .map(roleStr -> ROLE_PREFIX + roleStr) .collect(Collectors.toSet()); } private boolean isAllowedGroupId(String groupId) { if (enableFullList) { return true; } if (allowedGroupIds.size() == 1 && allowedGroupIds.contains("all")) { return true; } return allowedGroupIds.contains(groupId); } private GroupInformation getGroupInformation(OAuth2AccessToken accessToken) { return Optional.of(accessToken) .map(AbstractOAuth2Token::getTokenValue) .map(graphClient::getGroupInformation) .orElseGet(GroupInformation::new); } }
class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2UserService.class); private final OidcUserService oidcUserService; private final List<String> allowedGroupNames; private final Set<String> allowedGroupIds; private final boolean enableFullList; private final GraphClient graphClient; private static final String DEFAULT_OIDC_USER = "defaultOidcUser"; private static final String ROLES = "roles"; public AADOAuth2UserService(AADAuthenticationProperties properties) { this(properties, new GraphClient(properties)); } public AADOAuth2UserService(AADAuthenticationProperties properties, GraphClient graphClient) { allowedGroupNames = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupNames) .orElseGet(Collections::emptyList); allowedGroupIds = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupIds) .orElseGet(Collections::emptySet); enableFullList = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getEnableFullList) .orElse(false); this.oidcUserService = new OidcUserService(); this.graphClient = graphClient; } @Override Set<String> extractRolesFromIdToken(OidcIdToken idToken) { return Optional.ofNullable(idToken) .map(token -> (Collection<?>) token.getClaim(ROLES)) .filter(obj -> obj instanceof List<?>) .map(Collection::stream) .orElseGet(Stream::empty) .filter(s -> StringUtils.hasText(s.toString())) .map(role -> APPROLE_PREFIX + role) .collect(Collectors.toSet()); } Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) { if (allowedGroupNames.isEmpty() && allowedGroupIds.isEmpty()) { return Collections.emptySet(); } Set<String> roles = new HashSet<>(); GroupInformation groupInformation = getGroupInformation(accessToken); if (!allowedGroupNames.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsNames) .map(Collection::stream) .orElseGet(Stream::empty) .filter(allowedGroupNames::contains) .forEach(roles::add); } if (!allowedGroupIds.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsIds) .map(Collection::stream) .orElseGet(Stream::empty) .filter(this::isAllowedGroupId) .forEach(roles::add); } return roles.stream() .map(roleStr -> ROLE_PREFIX + roleStr) .collect(Collectors.toSet()); } private boolean isAllowedGroupId(String groupId) { if (enableFullList) { return true; } if (allowedGroupIds.size() == 1 && allowedGroupIds.contains("all")) { return true; } return allowedGroupIds.contains(groupId); } private GroupInformation getGroupInformation(OAuth2AccessToken accessToken) { return Optional.of(accessToken) .map(AbstractOAuth2Token::getTokenValue) .map(graphClient::getGroupInformation) .orElseGet(GroupInformation::new); } }
OK
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = oidcUserService.loadUser(userRequest); OidcIdToken idToken = oidcUser.getIdToken(); Set<String> authorityStrings = new HashSet<>(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(true); if (authentication != null) { return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER); } authorityStrings.addAll(extractRolesFromIdToken(idToken)); authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken())); Set<SimpleGrantedAuthority> authorities = authorityStrings.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); if (authorities.isEmpty()) { authorities = DEFAULT_AUTHORITY_SET; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", authorities); } String nameAttributeKey = Optional.of(userRequest) .map(OAuth2UserRequest::getClientRegistration) .map(ClientRegistration::getProviderDetails) .map(ClientRegistration.ProviderDetails::getUserInfoEndpoint) .map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName) .filter(StringUtils::hasText) .orElse(AADTokenClaim.NAME); DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey); session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser); return defaultOidcUser; }
LOGGER.debug("User's authorities: {}.", authorities);
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = oidcUserService.loadUser(userRequest); OidcIdToken idToken = oidcUser.getIdToken(); Set<String> authorityStrings = new HashSet<>(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(true); if (authentication != null) { LOGGER.debug("User {}'s authorities saved from session: {}.", authentication.getName(), authentication.getAuthorities()); return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER); } authorityStrings.addAll(extractRolesFromIdToken(idToken)); authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken())); Set<SimpleGrantedAuthority> authorities = authorityStrings.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); if (authorities.isEmpty()) { authorities = DEFAULT_AUTHORITY_SET; } String nameAttributeKey = Optional.of(userRequest) .map(OAuth2UserRequest::getClientRegistration) .map(ClientRegistration::getProviderDetails) .map(ClientRegistration.ProviderDetails::getUserInfoEndpoint) .map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName) .filter(StringUtils::hasText) .orElse(AADTokenClaim.NAME); LOGGER.debug("User {}'s authorities extracted by id token and access token: {}.", oidcUser.getClaim(nameAttributeKey), authorities); DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey); session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser); return defaultOidcUser; }
class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2UserService.class); private final OidcUserService oidcUserService; private final List<String> allowedGroupNames; private final Set<String> allowedGroupIds; private final boolean enableFullList; private final GraphClient graphClient; private static final String DEFAULT_OIDC_USER = "defaultOidcUser"; private static final String ROLES = "roles"; public AADOAuth2UserService(AADAuthenticationProperties properties) { this(properties, new GraphClient(properties)); } public AADOAuth2UserService(AADAuthenticationProperties properties, GraphClient graphClient) { allowedGroupNames = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupNames) .orElseGet(Collections::emptyList); allowedGroupIds = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupIds) .orElseGet(Collections::emptySet); enableFullList = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getEnableFullList) .orElse(false); this.oidcUserService = new OidcUserService(); this.graphClient = graphClient; } @Override Set<String> extractRolesFromIdToken(OidcIdToken idToken) { return Optional.ofNullable(idToken) .map(token -> (Collection<?>) token.getClaim(ROLES)) .filter(obj -> obj instanceof List<?>) .map(Collection::stream) .orElseGet(Stream::empty) .filter(s -> StringUtils.hasText(s.toString())) .map(role -> APPROLE_PREFIX + role) .collect(Collectors.toSet()); } Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) { if (allowedGroupNames.isEmpty() && allowedGroupIds.isEmpty()) { return Collections.emptySet(); } Set<String> roles = new HashSet<>(); GroupInformation groupInformation = getGroupInformation(accessToken); if (!allowedGroupNames.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsNames) .map(Collection::stream) .orElseGet(Stream::empty) .filter(allowedGroupNames::contains) .forEach(roles::add); } if (!allowedGroupIds.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsIds) .map(Collection::stream) .orElseGet(Stream::empty) .filter(this::isAllowedGroupId) .forEach(roles::add); } return roles.stream() .map(roleStr -> ROLE_PREFIX + roleStr) .collect(Collectors.toSet()); } private boolean isAllowedGroupId(String groupId) { if (enableFullList) { return true; } if (allowedGroupIds.size() == 1 && allowedGroupIds.contains("all")) { return true; } return allowedGroupIds.contains(groupId); } private GroupInformation getGroupInformation(OAuth2AccessToken accessToken) { return Optional.of(accessToken) .map(AbstractOAuth2Token::getTokenValue) .map(graphClient::getGroupInformation) .orElseGet(GroupInformation::new); } }
class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> { private static final Logger LOGGER = LoggerFactory.getLogger(AADOAuth2UserService.class); private final OidcUserService oidcUserService; private final List<String> allowedGroupNames; private final Set<String> allowedGroupIds; private final boolean enableFullList; private final GraphClient graphClient; private static final String DEFAULT_OIDC_USER = "defaultOidcUser"; private static final String ROLES = "roles"; public AADOAuth2UserService(AADAuthenticationProperties properties) { this(properties, new GraphClient(properties)); } public AADOAuth2UserService(AADAuthenticationProperties properties, GraphClient graphClient) { allowedGroupNames = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupNames) .orElseGet(Collections::emptyList); allowedGroupIds = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getAllowedGroupIds) .orElseGet(Collections::emptySet); enableFullList = Optional.ofNullable(properties) .map(AADAuthenticationProperties::getUserGroup) .map(AADAuthenticationProperties.UserGroupProperties::getEnableFullList) .orElse(false); this.oidcUserService = new OidcUserService(); this.graphClient = graphClient; } @Override Set<String> extractRolesFromIdToken(OidcIdToken idToken) { return Optional.ofNullable(idToken) .map(token -> (Collection<?>) token.getClaim(ROLES)) .filter(obj -> obj instanceof List<?>) .map(Collection::stream) .orElseGet(Stream::empty) .filter(s -> StringUtils.hasText(s.toString())) .map(role -> APPROLE_PREFIX + role) .collect(Collectors.toSet()); } Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) { if (allowedGroupNames.isEmpty() && allowedGroupIds.isEmpty()) { return Collections.emptySet(); } Set<String> roles = new HashSet<>(); GroupInformation groupInformation = getGroupInformation(accessToken); if (!allowedGroupNames.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsNames) .map(Collection::stream) .orElseGet(Stream::empty) .filter(allowedGroupNames::contains) .forEach(roles::add); } if (!allowedGroupIds.isEmpty()) { Optional.of(groupInformation) .map(GroupInformation::getGroupsIds) .map(Collection::stream) .orElseGet(Stream::empty) .filter(this::isAllowedGroupId) .forEach(roles::add); } return roles.stream() .map(roleStr -> ROLE_PREFIX + roleStr) .collect(Collectors.toSet()); } private boolean isAllowedGroupId(String groupId) { if (enableFullList) { return true; } if (allowedGroupIds.size() == 1 && allowedGroupIds.contains("all")) { return true; } return allowedGroupIds.contains(groupId); } private GroupInformation getGroupInformation(OAuth2AccessToken accessToken) { return Optional.of(accessToken) .map(AbstractOAuth2Token::getTokenValue) .map(graphClient::getGroupInformation) .orElseGet(GroupInformation::new); } }
Yes, I have optimized the converter structure.
private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.hasClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; }
if (jwt.hasClaim(claimName)) {
private Collection<String> getAuthorities(Jwt jwt) { Collection<String> authoritiesList = new ArrayList<String>(); for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.containsClaim(claimName)) { if (jwt.getClaim(claimName) instanceof String) { if (StringUtils.hasText(jwt.getClaim(claimName))) { authoritiesList.addAll(Arrays.asList(((String) jwt.getClaim(claimName)).split(" ")) .stream() .map(s -> DEFAULT_SCP_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } else if (jwt.getClaim(claimName) instanceof Collection) { authoritiesList.addAll(((Collection<?>) jwt.getClaim(claimName)) .stream() .filter(s -> StringUtils.hasText((String) s)) .map(s -> DEFAULT_ROLES_AUTHORITY_PREFIX + s) .collect(Collectors.toList())); } } } return authoritiesList; }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final Logger LOGGER = LoggerFactory.getLogger(AADJwtGrantedAuthoritiesConverter.class); private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("User's authorities: {}.", grantedAuthorities); } return grantedAuthorities; } }
class AADJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private static final String DEFAULT_SCP_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_ROLES_AUTHORITY_PREFIX = "APPROLE_"; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scp", "roles"); @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } return grantedAuthorities; } }
Can we call `AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName, String authorityPrefix)` in this method?
public AADJwtBearerTokenAuthenticationConverter() { super(); principalClaimName = DEFAULT_PRINCIPAL_CLAIM_NAME; }
principalClaimName = DEFAULT_PRINCIPAL_CLAIM_NAME;
public AADJwtBearerTokenAuthenticationConverter() { this(DEFAULT_PRINCIPAL_CLAIM_NAME, DEFAULT_CLAIM_TO_AUTHORITY_PREFIX_MAP); }
class AADJwtBearerTokenAuthenticationConverter extends AbstractJwtBearerTokenAuthenticationConverter { private static final String DEFAULT_PRINCIPAL_CLAIM_NAME = "sub"; /** * Use AADJwtGrantedAuthoritiesConverter, it can resolve the access token of scp and roles. */ /** * Using spring security provides JwtGrantedAuthoritiesConverter, it can resolve the access token of scp or roles. * * @param authoritiesClaimName authorities claim name */ public AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName) { this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX); } public AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName, String authorityPrefix) { super(authoritiesClaimName, authorityPrefix); principalClaimName = DEFAULT_PRINCIPAL_CLAIM_NAME; } @Override protected OAuth2AuthenticatedPrincipal getAuthenticatedPrincipal(Map<String, Object> headers, Map<String, Object> claims, Collection<GrantedAuthority> authorities, String tokenValue) { return new AADOAuth2AuthenticatedPrincipal( headers, claims, authorities, tokenValue, principalClaimName); } }
class AADJwtBearerTokenAuthenticationConverter extends AbstractJwtBearerTokenAuthenticationConverter { /** * Construct AADJwtBearerTokenAuthenticationConverter by DEFAULT_PRINCIPAL_CLAIM_NAME and DEFAULT_CLAIM_TO_AUTHORITY_PREFIX_MAP. */ /** * Construct AADJwtBearerTokenAuthenticationConverter with the authority claim. * @param authoritiesClaimName authority claim name */ public AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName) { this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX); } /** * Construct AADJwtBearerTokenAuthenticationConverter with the authority claim name and prefix. * @param authoritiesClaimName authority claim name * @param authorityPrefix the prefix name of the authority */ public AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName, String authorityPrefix) { this(null, buildClaimToAuthorityPrefixMap(authoritiesClaimName, authorityPrefix)); } /** * Using spring security provides JwtGrantedAuthoritiesConverter, it can resolve the access token of scp or roles. * * @param principalClaimName authorities claim name * @param claimToAuthorityPrefixMap the authority name and prefix map */ public AADJwtBearerTokenAuthenticationConverter(String principalClaimName, Map<String, String> claimToAuthorityPrefixMap) { super(principalClaimName, claimToAuthorityPrefixMap); } @Override protected OAuth2AuthenticatedPrincipal getAuthenticatedPrincipal(Map<String, Object> headers, Map<String, Object> claims, Collection<GrantedAuthority> authorities, String tokenValue) { String name = Optional.ofNullable(principalClaimName) .map(n -> (String) claims.get(n)) .orElseGet(() -> (String) claims.get("sub")); return new AADOAuth2AuthenticatedPrincipal(headers, claims, authorities, tokenValue, name); } }
Can we delete this line?
public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
when(jwt.getClaim("scp")).thenReturn(null);
public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { jwt = mock(Jwt.class); claims = new HashMap<>(); headers = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeAll public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testParameterConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testParameterConstructorExtractRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test }
Same here.
public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); }
when(jwt.getClaim("roles")).thenReturn(null);
public void testParameterConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { jwt = mock(Jwt.class); claims = new HashMap<>(); headers = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeAll public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test @Test public void testParameterConstructorExtractRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } }
Same here.
public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); }
when(jwt.getClaim("scp")).thenReturn(null);
public void testParameterConstructorExtractRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { jwt = mock(Jwt.class); claims = new HashMap<>(); headers = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeAll public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testParameterConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } }
Same here.
public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
when(jwt.getClaim("roles")).thenReturn(null);
public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
Same here.
public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); }
when(jwt.getClaim("scp")).thenReturn(null);
public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
Same here.
public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
when(jwt.getClaim("scp")).thenReturn(null);
public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
Same here.
public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
when(jwt.getClaim("roles")).thenReturn(null);
public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
Same here.
public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); }
when(jwt.getClaim("scp")).thenReturn(null);
public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test }
nit: this(null, buildClaimToAuthorityPrefixMap(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX));
public AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName) { this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX); }
this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX);
public AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName) { this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX); }
class AADJwtBearerTokenAuthenticationConverter extends AbstractJwtBearerTokenAuthenticationConverter { /** * Construct AADJwtBearerTokenAuthenticationConverter by DEFAULT_PRINCIPAL_CLAIM_NAME and DEFAULT_CLAIM_TO_AUTHORITY_PREFIX_MAP. */ public AADJwtBearerTokenAuthenticationConverter() { this(DEFAULT_PRINCIPAL_CLAIM_NAME, DEFAULT_CLAIM_TO_AUTHORITY_PREFIX_MAP); } /** * Construct AADJwtBearerTokenAuthenticationConverter with the authority claim. * @param authoritiesClaimName authority claim name */ /** * Construct AADJwtBearerTokenAuthenticationConverter with the authority claim name and prefix. * @param authoritiesClaimName authority claim name * @param authorityPrefix the prefix name of the authority */ public AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName, String authorityPrefix) { this(null, buildClaimToAuthorityPrefixMap(authoritiesClaimName, authorityPrefix)); } /** * Using spring security provides JwtGrantedAuthoritiesConverter, it can resolve the access token of scp or roles. * * @param principalClaimName authorities claim name * @param claimToAuthorityPrefixMap the authority name and prefix map */ public AADJwtBearerTokenAuthenticationConverter(String principalClaimName, Map<String, String> claimToAuthorityPrefixMap) { super(principalClaimName, claimToAuthorityPrefixMap); } @Override protected OAuth2AuthenticatedPrincipal getAuthenticatedPrincipal(Map<String, Object> headers, Map<String, Object> claims, Collection<GrantedAuthority> authorities, String tokenValue) { String name = Optional.ofNullable(principalClaimName) .map(n -> (String) claims.get(n)) .orElseGet(() -> (String) claims.get("sub")); return new AADOAuth2AuthenticatedPrincipal(headers, claims, authorities, tokenValue, name); } }
class AADJwtBearerTokenAuthenticationConverter extends AbstractJwtBearerTokenAuthenticationConverter { /** * Construct AADJwtBearerTokenAuthenticationConverter by DEFAULT_PRINCIPAL_CLAIM_NAME and DEFAULT_CLAIM_TO_AUTHORITY_PREFIX_MAP. */ public AADJwtBearerTokenAuthenticationConverter() { this(DEFAULT_PRINCIPAL_CLAIM_NAME, DEFAULT_CLAIM_TO_AUTHORITY_PREFIX_MAP); } /** * Construct AADJwtBearerTokenAuthenticationConverter with the authority claim. * @param authoritiesClaimName authority claim name */ /** * Construct AADJwtBearerTokenAuthenticationConverter with the authority claim name and prefix. * @param authoritiesClaimName authority claim name * @param authorityPrefix the prefix name of the authority */ public AADJwtBearerTokenAuthenticationConverter(String authoritiesClaimName, String authorityPrefix) { this(null, buildClaimToAuthorityPrefixMap(authoritiesClaimName, authorityPrefix)); } /** * Using spring security provides JwtGrantedAuthoritiesConverter, it can resolve the access token of scp or roles. * * @param principalClaimName authorities claim name * @param claimToAuthorityPrefixMap the authority name and prefix map */ public AADJwtBearerTokenAuthenticationConverter(String principalClaimName, Map<String, String> claimToAuthorityPrefixMap) { super(principalClaimName, claimToAuthorityPrefixMap); } @Override protected OAuth2AuthenticatedPrincipal getAuthenticatedPrincipal(Map<String, Object> headers, Map<String, Object> claims, Collection<GrantedAuthority> authorities, String tokenValue) { String name = Optional.ofNullable(principalClaimName) .map(n -> (String) claims.get(n)) .orElseGet(() -> (String) claims.get("sub")); return new AADOAuth2AuthenticatedPrincipal(headers, claims, authorities, tokenValue, name); } }
Hi @chenrujun , done, please help review.
public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
when(jwt.getClaim("roles")).thenReturn(null);
public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
Same here.
public AADB2CJwtBearerTokenAuthenticationConverter(String authoritiesClaimName) { this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX); }
this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX);
public AADB2CJwtBearerTokenAuthenticationConverter(String authoritiesClaimName) { this(authoritiesClaimName, DEFAULT_AUTHORITY_PREFIX); }
class AADB2CJwtBearerTokenAuthenticationConverter extends AbstractJwtBearerTokenAuthenticationConverter { /** * Use {@link AADJwtGrantedAuthoritiesConverter}, it can resolve the access token of scp and roles. */ public AADB2CJwtBearerTokenAuthenticationConverter() { this(null, DEFAULT_CLAIM_TO_AUTHORITY_PREFIX_MAP); } /** * Construct AADB2CJwtBearerTokenAuthenticationConverter with the authority claim. * @param authoritiesClaimName authority claim name */ /** * Construct AADB2CJwtBearerTokenAuthenticationConverter with the authority claim name and prefix. * @param authoritiesClaimName authority claim name * @param authorityPrefix the prefix name of the authority */ public AADB2CJwtBearerTokenAuthenticationConverter(String authoritiesClaimName, String authorityPrefix) { this(null, buildClaimToAuthorityPrefixMap(authoritiesClaimName, authorityPrefix)); } public AADB2CJwtBearerTokenAuthenticationConverter(String principalClaimName, Map<String, String> claimToAuthorityPrefixMap) { super(principalClaimName, claimToAuthorityPrefixMap); } @Override protected OAuth2AuthenticatedPrincipal getAuthenticatedPrincipal(Map<String, Object> headers, Map<String, Object> claims, Collection<GrantedAuthority> authorities, String tokenValue) { String name = Optional.ofNullable(principalClaimName) .map(n -> (String) claims.get(n)) .orElseGet(() -> (String) claims.get("sub")); return new AADOAuth2AuthenticatedPrincipal(headers, claims, authorities, tokenValue, name); } }
class AADB2CJwtBearerTokenAuthenticationConverter extends AbstractJwtBearerTokenAuthenticationConverter { /** * Use {@link AADJwtGrantedAuthoritiesConverter}, it can resolve the access token of scp and roles. */ public AADB2CJwtBearerTokenAuthenticationConverter() { this(null, DEFAULT_CLAIM_TO_AUTHORITY_PREFIX_MAP); } /** * Construct AADB2CJwtBearerTokenAuthenticationConverter with the authority claim. * @param authoritiesClaimName authority claim name */ /** * Construct AADB2CJwtBearerTokenAuthenticationConverter with the authority claim name and prefix. * @param authoritiesClaimName authority claim name * @param authorityPrefix the prefix name of the authority */ public AADB2CJwtBearerTokenAuthenticationConverter(String authoritiesClaimName, String authorityPrefix) { this(null, buildClaimToAuthorityPrefixMap(authoritiesClaimName, authorityPrefix)); } public AADB2CJwtBearerTokenAuthenticationConverter(String principalClaimName, Map<String, String> claimToAuthorityPrefixMap) { super(principalClaimName, claimToAuthorityPrefixMap); } @Override protected OAuth2AuthenticatedPrincipal getAuthenticatedPrincipal(Map<String, Object> headers, Map<String, Object> claims, Collection<GrantedAuthority> authorities, String tokenValue) { String name = Optional.ofNullable(principalClaimName) .map(n -> (String) claims.get(n)) .orElseGet(() -> (String) claims.get("sub")); return new AADOAuth2AuthenticatedPrincipal(headers, claims, authorities, tokenValue, name); } }
Change `@BeforeEach` to `@BeforeAll`.
public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); }
AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter();
public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test @Test public void testParameterConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testParameterConstructorExtractRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeAll public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testParameterConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testParameterConstructorExtractRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } }
Could you please keep this test?
public void testParameterConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); }
AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp");
public void testParameterConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test @Test public void testParameterConstructorExtractRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } }
class AADJwtBearerTokenAuthenticationConverterTest { private Jwt jwt = mock(Jwt.class); private Map<String, Object> claims = new HashMap<>(); private Map<String, Object> headers = new HashMap<>(); private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeAll public void init() { claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getClaims()).isNotEmpty(); assertThat(principal.getIssuer()).isEqualTo(claims.get("iss")); assertThat(principal.getTenantId()).isEqualTo(claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test public void testNoArgumentsConstructorExtractScopeAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(4); } @Test @Test public void testParameterConstructorExtractRoleAuthorities() { AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADJwtBearerTokenAuthenticationConverter converter = new AADJwtBearerTokenAuthenticationConverter("scp", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } }
Hi, @moarychan , release in June has already finished. please update this PR.
public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
when(jwt.getClaim("roles")).thenReturn(null);
public void testNoArgumentsConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
class AADB2CUserPrincipalTest { private Jwt jwt; private Map<String, Object> claims; private Map<String, Object> headers; private JSONArray jsonArray = new JSONArray().appendElement("User.read").appendElement("User.write"); @BeforeEach public void init() { claims = new HashMap<>(); claims.put("iss", "fake-issuer"); claims.put("tid", "fake-tid"); headers = new HashMap<>(); headers.put("kid", "kg2LYs2T0CTjIfj4rt6JIynen38"); jwt = mock(Jwt.class); when(jwt.getClaim("scp")).thenReturn("Order.read Order.write"); when(jwt.getClaim("roles")).thenReturn(jsonArray); when(jwt.getTokenValue()).thenReturn("fake-token-value"); when(jwt.getIssuedAt()).thenReturn(Instant.now()); when(jwt.getHeaders()).thenReturn(headers); when(jwt.getExpiresAt()).thenReturn(Instant.MAX); when(jwt.getClaims()).thenReturn(claims); } @Test public void testCreateUserPrincipal() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getClaims().isEmpty()); Assertions.assertEquals(principal.getIssuer(), claims.get("iss")); Assertions.assertEquals(principal.getTenantId(), claims.get("tid")); } @Test public void testNoArgumentsConstructorDefaultScopeAndRoleAuthorities() { AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 4); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test @Test public void testNoArgumentsConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter(); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } @Test public void testConstructorExtractRoleAuthoritiesWithAuthorityPrefixMapParameter() { when(jwt.getClaim("scp")).thenReturn(null); Map<String, String> claimToAuthorityPrefixMap = new HashMap<>(); claimToAuthorityPrefixMap.put("roles", "APPROLE_"); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("sub", claimToAuthorityPrefixMap); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); assertThat(authenticationToken.getPrincipal()).isExactlyInstanceOf(AADOAuth2AuthenticatedPrincipal.class); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); assertThat(principal.getAttributes()).isNotEmpty(); assertThat(principal.getAttributes()).hasSize(2); assertThat(principal.getAuthorities()).hasSize(2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractScopeAuthorities() { when(jwt.getClaim("roles")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("scp"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); } @Test public void testParameterConstructorExtractRoleAuthorities() { when(jwt.getClaim("scp")).thenReturn(null); AADB2CJwtBearerTokenAuthenticationConverter converter = new AADB2CJwtBearerTokenAuthenticationConverter("roles", "APPROLE_"); AbstractAuthenticationToken authenticationToken = converter.convert(jwt); Assertions.assertTrue(authenticationToken.getPrincipal().getClass().isAssignableFrom(AADOAuth2AuthenticatedPrincipal.class)); AADOAuth2AuthenticatedPrincipal principal = (AADOAuth2AuthenticatedPrincipal) authenticationToken .getPrincipal(); Assertions.assertFalse(principal.getAttributes().isEmpty()); Assertions.assertTrue(principal.getAttributes().size() == 2); Assertions.assertTrue(principal.getAuthorities().size() == 2); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.read"))); Assertions.assertTrue(principal.getAuthorities().contains(new SimpleGrantedAuthority("APPROLE_User.write"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.read"))); Assertions.assertFalse(principal.getAuthorities().contains(new SimpleGrantedAuthority("SCOPE_Order.write"))); } }
The retryRate is not used in this method, probably can move this logic to reevaluateThresholds
private void recordOperation(boolean isRetry) { long totalSnapshot = this.totalOperationCount.incrementAndGet(); CurrentIntervalThresholds currentThresholdsSnapshot = this.currentThresholds.get(); long currentTotalCountSnapshot = currentThresholdsSnapshot.currentOperationCount.incrementAndGet(); long currentRetryCountSnapshot; if (isRetry) { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.incrementAndGet(); } else { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.get(); } double retryRate = (double)currentRetryCountSnapshot / currentTotalCountSnapshot; Pair<Boolean, Boolean> shouldReevaluateResult = this.shouldReevaluateThresholds(totalSnapshot, currentTotalCountSnapshot); boolean shouldReevaluate = shouldReevaluateResult.getLeft(); if (shouldReevaluate) { boolean onlyUpscale = shouldReevaluateResult.getRight(); if (onlyUpscale || this.currentThresholds.compareAndSet(currentThresholdsSnapshot, new CurrentIntervalThresholds())) { this.reevaluateThresholds( totalSnapshot, currentTotalCountSnapshot, currentRetryCountSnapshot, retryRate, shouldReevaluateResult.getRight()); } } }
double retryRate = (double)currentRetryCountSnapshot / currentTotalCountSnapshot;
private void recordOperation(boolean isRetry) { long totalSnapshot = this.totalOperationCount.incrementAndGet(); CurrentIntervalThresholds currentThresholdsSnapshot = this.currentThresholds.get(); long currentTotalCountSnapshot = currentThresholdsSnapshot.currentOperationCount.incrementAndGet(); long currentRetryCountSnapshot; if (isRetry) { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.incrementAndGet(); } else { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.get(); } Pair<Boolean, Boolean> shouldReevaluateResult = this.shouldReevaluateThresholds(totalSnapshot, currentTotalCountSnapshot); boolean shouldReevaluate = shouldReevaluateResult.getLeft(); if (shouldReevaluate) { boolean onlyUpscale = shouldReevaluateResult.getRight(); if (onlyUpscale || this.currentThresholds.compareAndSet(currentThresholdsSnapshot, new CurrentIntervalThresholds())) { this.reevaluateThresholds( totalSnapshot, currentTotalCountSnapshot, currentRetryCountSnapshot, shouldReevaluateResult.getRight()); } } }
class PartitionScopeThresholds<TContext> { private final static Logger logger = LoggerFactory.getLogger(PartitionScopeThresholds.class); private final String pkRangeId; private final BulkProcessingOptions<TContext> options; private final AtomicInteger targetMicroBatchSize; private final AtomicLong totalOperationCount; private final AtomicReference<CurrentIntervalThresholds> currentThresholds; private final String identifier = UUID.randomUUID().toString(); private final double minRetryRate; private final double maxRetryRate; private final double avgRetryRate; public PartitionScopeThresholds(String pkRangeId, BulkProcessingOptions<TContext> options) { checkNotNull(pkRangeId, "expected non-null pkRangeId"); checkNotNull(options, "expected non-null options"); this.pkRangeId = pkRangeId; this.options = options; this.targetMicroBatchSize = new AtomicInteger(options.getMaxMicroBatchSize()); this.totalOperationCount = new AtomicLong(0); this.currentThresholds = new AtomicReference<>(new CurrentIntervalThresholds()); this.minRetryRate = options.getMinTargetedMicroBatchRetryRate(); this.maxRetryRate = options.getMaxTargetedMicroBatchRetryRate(); this.avgRetryRate = ((this.maxRetryRate + this.minRetryRate)/2); } public String getPartitionKeyRangeId() { return this.pkRangeId; } private Pair<Boolean, Boolean> shouldReevaluateThresholds(long totalSnapshot, long currentSnapshot) { if (totalSnapshot < 1_000) { return Pair.of(currentSnapshot == 100, false); } if (totalSnapshot < 10_000) { return Pair.of(currentSnapshot == 1_000, false); } return Pair.of(currentSnapshot % 1_000 == 0, currentSnapshot % 10_000 == 0); } private void reevaluateThresholds( long totalCount, long currentCount, long retryCount, double retryRate, boolean onlyUpscale) { int microBatchSizeBefore = this.targetMicroBatchSize.get(); int microBatchSizeAfter = microBatchSizeBefore; if (retryRate < this.minRetryRate && microBatchSizeBefore < this.options.getMaxMicroBatchSize()) { int targetedNewBatchSize = Math.min( Math.min( microBatchSizeBefore * 2, microBatchSizeBefore + (int)(this.options.getMaxMicroBatchSize() * this.avgRetryRate)), this.options.getMaxMicroBatchSize()); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } else if (!onlyUpscale && retryRate > this.maxRetryRate && microBatchSizeBefore > 1) { double deltaRate = retryRate - this.avgRetryRate; int targetedNewBatchSize = Math.max(1, (int) (microBatchSizeBefore * (1 - deltaRate))); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } logger.debug( "Reevaluated thresholds for PKRange '{} "CurrentRetryRate: {} - BatchSize {} -> {}, OnlyUpscale: {})", this.pkRangeId, this.identifier, totalCount, currentCount, retryCount, retryRate, microBatchSizeBefore, microBatchSizeAfter, onlyUpscale); } public void recordSuccessfulOperation() { this.recordOperation(false); } public void recordEnqueuedRetry() { this.recordOperation(true); } public int getTargetMicroBatchSizeSnapshot() { return this.targetMicroBatchSize.get(); } private static class CurrentIntervalThresholds { public final AtomicLong currentOperationCount = new AtomicLong(0); public final AtomicLong currentRetriedOperationCount = new AtomicLong(0); } }
class PartitionScopeThresholds<TContext> { private final static Logger logger = LoggerFactory.getLogger(PartitionScopeThresholds.class); private final String pkRangeId; private final BulkProcessingOptions<TContext> options; private final AtomicInteger targetMicroBatchSize; private final AtomicLong totalOperationCount; private final AtomicReference<CurrentIntervalThresholds> currentThresholds; private final String identifier = UUID.randomUUID().toString(); private final double minRetryRate; private final double maxRetryRate; private final double avgRetryRate; public PartitionScopeThresholds(String pkRangeId, BulkProcessingOptions<TContext> options) { checkNotNull(pkRangeId, "expected non-null pkRangeId"); checkNotNull(options, "expected non-null options"); this.pkRangeId = pkRangeId; this.options = options; this.targetMicroBatchSize = new AtomicInteger(options.getMaxMicroBatchSize()); this.totalOperationCount = new AtomicLong(0); this.currentThresholds = new AtomicReference<>(new CurrentIntervalThresholds()); this.minRetryRate = options.getMinTargetedMicroBatchRetryRate(); this.maxRetryRate = options.getMaxTargetedMicroBatchRetryRate(); this.avgRetryRate = ((this.maxRetryRate + this.minRetryRate)/2); } public String getPartitionKeyRangeId() { return this.pkRangeId; } private Pair<Boolean, Boolean> shouldReevaluateThresholds(long totalSnapshot, long currentSnapshot) { if (totalSnapshot < 1_000) { return Pair.of(currentSnapshot == 100, false); } if (totalSnapshot < 10_000) { return Pair.of(currentSnapshot == 1_000, false); } return Pair.of(currentSnapshot % 1_000 == 0, currentSnapshot % 10_000 == 0); } private void reevaluateThresholds( long totalCount, long currentCount, long retryCount, boolean onlyUpscale) { double retryRate = currentCount == 0 ? 0 : (double)retryCount / currentCount; int microBatchSizeBefore = this.targetMicroBatchSize.get(); int microBatchSizeAfter = microBatchSizeBefore; if (retryRate < this.minRetryRate && microBatchSizeBefore < this.options.getMaxMicroBatchSize()) { int targetedNewBatchSize = Math.min( Math.min( microBatchSizeBefore * 2, microBatchSizeBefore + (int)(this.options.getMaxMicroBatchSize() * this.avgRetryRate)), this.options.getMaxMicroBatchSize()); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } else if (!onlyUpscale && retryRate > this.maxRetryRate && microBatchSizeBefore > 1) { double deltaRate = retryRate - this.avgRetryRate; int targetedNewBatchSize = Math.max(1, (int) (microBatchSizeBefore * (1 - deltaRate))); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } logger.debug( "Reevaluated thresholds for PKRange '{} "CurrentRetryRate: {} - BatchSize {} -> {}, OnlyUpscale: {})", this.pkRangeId, this.identifier, totalCount, currentCount, retryCount, retryRate, microBatchSizeBefore, microBatchSizeAfter, onlyUpscale); } public void recordSuccessfulOperation() { this.recordOperation(false); } public void recordEnqueuedRetry() { this.recordOperation(true); } public int getTargetMicroBatchSizeSnapshot() { return this.targetMicroBatchSize.get(); } private static class CurrentIntervalThresholds { public final AtomicLong currentOperationCount = new AtomicLong(0); public final AtomicLong currentRetriedOperationCount = new AtomicLong(0); } }
It is used in line 87
private void recordOperation(boolean isRetry) { long totalSnapshot = this.totalOperationCount.incrementAndGet(); CurrentIntervalThresholds currentThresholdsSnapshot = this.currentThresholds.get(); long currentTotalCountSnapshot = currentThresholdsSnapshot.currentOperationCount.incrementAndGet(); long currentRetryCountSnapshot; if (isRetry) { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.incrementAndGet(); } else { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.get(); } double retryRate = (double)currentRetryCountSnapshot / currentTotalCountSnapshot; Pair<Boolean, Boolean> shouldReevaluateResult = this.shouldReevaluateThresholds(totalSnapshot, currentTotalCountSnapshot); boolean shouldReevaluate = shouldReevaluateResult.getLeft(); if (shouldReevaluate) { boolean onlyUpscale = shouldReevaluateResult.getRight(); if (onlyUpscale || this.currentThresholds.compareAndSet(currentThresholdsSnapshot, new CurrentIntervalThresholds())) { this.reevaluateThresholds( totalSnapshot, currentTotalCountSnapshot, currentRetryCountSnapshot, retryRate, shouldReevaluateResult.getRight()); } } }
double retryRate = (double)currentRetryCountSnapshot / currentTotalCountSnapshot;
private void recordOperation(boolean isRetry) { long totalSnapshot = this.totalOperationCount.incrementAndGet(); CurrentIntervalThresholds currentThresholdsSnapshot = this.currentThresholds.get(); long currentTotalCountSnapshot = currentThresholdsSnapshot.currentOperationCount.incrementAndGet(); long currentRetryCountSnapshot; if (isRetry) { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.incrementAndGet(); } else { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.get(); } Pair<Boolean, Boolean> shouldReevaluateResult = this.shouldReevaluateThresholds(totalSnapshot, currentTotalCountSnapshot); boolean shouldReevaluate = shouldReevaluateResult.getLeft(); if (shouldReevaluate) { boolean onlyUpscale = shouldReevaluateResult.getRight(); if (onlyUpscale || this.currentThresholds.compareAndSet(currentThresholdsSnapshot, new CurrentIntervalThresholds())) { this.reevaluateThresholds( totalSnapshot, currentTotalCountSnapshot, currentRetryCountSnapshot, shouldReevaluateResult.getRight()); } } }
class PartitionScopeThresholds<TContext> { private final static Logger logger = LoggerFactory.getLogger(PartitionScopeThresholds.class); private final String pkRangeId; private final BulkProcessingOptions<TContext> options; private final AtomicInteger targetMicroBatchSize; private final AtomicLong totalOperationCount; private final AtomicReference<CurrentIntervalThresholds> currentThresholds; private final String identifier = UUID.randomUUID().toString(); private final double minRetryRate; private final double maxRetryRate; private final double avgRetryRate; public PartitionScopeThresholds(String pkRangeId, BulkProcessingOptions<TContext> options) { checkNotNull(pkRangeId, "expected non-null pkRangeId"); checkNotNull(options, "expected non-null options"); this.pkRangeId = pkRangeId; this.options = options; this.targetMicroBatchSize = new AtomicInteger(options.getMaxMicroBatchSize()); this.totalOperationCount = new AtomicLong(0); this.currentThresholds = new AtomicReference<>(new CurrentIntervalThresholds()); this.minRetryRate = options.getMinTargetedMicroBatchRetryRate(); this.maxRetryRate = options.getMaxTargetedMicroBatchRetryRate(); this.avgRetryRate = ((this.maxRetryRate + this.minRetryRate)/2); } public String getPartitionKeyRangeId() { return this.pkRangeId; } private Pair<Boolean, Boolean> shouldReevaluateThresholds(long totalSnapshot, long currentSnapshot) { if (totalSnapshot < 1_000) { return Pair.of(currentSnapshot == 100, false); } if (totalSnapshot < 10_000) { return Pair.of(currentSnapshot == 1_000, false); } return Pair.of(currentSnapshot % 1_000 == 0, currentSnapshot % 10_000 == 0); } private void reevaluateThresholds( long totalCount, long currentCount, long retryCount, double retryRate, boolean onlyUpscale) { int microBatchSizeBefore = this.targetMicroBatchSize.get(); int microBatchSizeAfter = microBatchSizeBefore; if (retryRate < this.minRetryRate && microBatchSizeBefore < this.options.getMaxMicroBatchSize()) { int targetedNewBatchSize = Math.min( Math.min( microBatchSizeBefore * 2, microBatchSizeBefore + (int)(this.options.getMaxMicroBatchSize() * this.avgRetryRate)), this.options.getMaxMicroBatchSize()); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } else if (!onlyUpscale && retryRate > this.maxRetryRate && microBatchSizeBefore > 1) { double deltaRate = retryRate - this.avgRetryRate; int targetedNewBatchSize = Math.max(1, (int) (microBatchSizeBefore * (1 - deltaRate))); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } logger.debug( "Reevaluated thresholds for PKRange '{} "CurrentRetryRate: {} - BatchSize {} -> {}, OnlyUpscale: {})", this.pkRangeId, this.identifier, totalCount, currentCount, retryCount, retryRate, microBatchSizeBefore, microBatchSizeAfter, onlyUpscale); } public void recordSuccessfulOperation() { this.recordOperation(false); } public void recordEnqueuedRetry() { this.recordOperation(true); } public int getTargetMicroBatchSizeSnapshot() { return this.targetMicroBatchSize.get(); } private static class CurrentIntervalThresholds { public final AtomicLong currentOperationCount = new AtomicLong(0); public final AtomicLong currentRetriedOperationCount = new AtomicLong(0); } }
class PartitionScopeThresholds<TContext> { private final static Logger logger = LoggerFactory.getLogger(PartitionScopeThresholds.class); private final String pkRangeId; private final BulkProcessingOptions<TContext> options; private final AtomicInteger targetMicroBatchSize; private final AtomicLong totalOperationCount; private final AtomicReference<CurrentIntervalThresholds> currentThresholds; private final String identifier = UUID.randomUUID().toString(); private final double minRetryRate; private final double maxRetryRate; private final double avgRetryRate; public PartitionScopeThresholds(String pkRangeId, BulkProcessingOptions<TContext> options) { checkNotNull(pkRangeId, "expected non-null pkRangeId"); checkNotNull(options, "expected non-null options"); this.pkRangeId = pkRangeId; this.options = options; this.targetMicroBatchSize = new AtomicInteger(options.getMaxMicroBatchSize()); this.totalOperationCount = new AtomicLong(0); this.currentThresholds = new AtomicReference<>(new CurrentIntervalThresholds()); this.minRetryRate = options.getMinTargetedMicroBatchRetryRate(); this.maxRetryRate = options.getMaxTargetedMicroBatchRetryRate(); this.avgRetryRate = ((this.maxRetryRate + this.minRetryRate)/2); } public String getPartitionKeyRangeId() { return this.pkRangeId; } private Pair<Boolean, Boolean> shouldReevaluateThresholds(long totalSnapshot, long currentSnapshot) { if (totalSnapshot < 1_000) { return Pair.of(currentSnapshot == 100, false); } if (totalSnapshot < 10_000) { return Pair.of(currentSnapshot == 1_000, false); } return Pair.of(currentSnapshot % 1_000 == 0, currentSnapshot % 10_000 == 0); } private void reevaluateThresholds( long totalCount, long currentCount, long retryCount, boolean onlyUpscale) { double retryRate = currentCount == 0 ? 0 : (double)retryCount / currentCount; int microBatchSizeBefore = this.targetMicroBatchSize.get(); int microBatchSizeAfter = microBatchSizeBefore; if (retryRate < this.minRetryRate && microBatchSizeBefore < this.options.getMaxMicroBatchSize()) { int targetedNewBatchSize = Math.min( Math.min( microBatchSizeBefore * 2, microBatchSizeBefore + (int)(this.options.getMaxMicroBatchSize() * this.avgRetryRate)), this.options.getMaxMicroBatchSize()); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } else if (!onlyUpscale && retryRate > this.maxRetryRate && microBatchSizeBefore > 1) { double deltaRate = retryRate - this.avgRetryRate; int targetedNewBatchSize = Math.max(1, (int) (microBatchSizeBefore * (1 - deltaRate))); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } logger.debug( "Reevaluated thresholds for PKRange '{} "CurrentRetryRate: {} - BatchSize {} -> {}, OnlyUpscale: {})", this.pkRangeId, this.identifier, totalCount, currentCount, retryCount, retryRate, microBatchSizeBefore, microBatchSizeAfter, onlyUpscale); } public void recordSuccessfulOperation() { this.recordOperation(false); } public void recordEnqueuedRetry() { this.recordOperation(true); } public int getTargetMicroBatchSizeSnapshot() { return this.targetMicroBatchSize.get(); } private static class CurrentIntervalThresholds { public final AtomicLong currentOperationCount = new AtomicLong(0); public final AtomicLong currentRetriedOperationCount = new AtomicLong(0); } }
but we pass currentRetryCountSnapshot, currentTotalCountSnapshot to that method?
private void recordOperation(boolean isRetry) { long totalSnapshot = this.totalOperationCount.incrementAndGet(); CurrentIntervalThresholds currentThresholdsSnapshot = this.currentThresholds.get(); long currentTotalCountSnapshot = currentThresholdsSnapshot.currentOperationCount.incrementAndGet(); long currentRetryCountSnapshot; if (isRetry) { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.incrementAndGet(); } else { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.get(); } double retryRate = (double)currentRetryCountSnapshot / currentTotalCountSnapshot; Pair<Boolean, Boolean> shouldReevaluateResult = this.shouldReevaluateThresholds(totalSnapshot, currentTotalCountSnapshot); boolean shouldReevaluate = shouldReevaluateResult.getLeft(); if (shouldReevaluate) { boolean onlyUpscale = shouldReevaluateResult.getRight(); if (onlyUpscale || this.currentThresholds.compareAndSet(currentThresholdsSnapshot, new CurrentIntervalThresholds())) { this.reevaluateThresholds( totalSnapshot, currentTotalCountSnapshot, currentRetryCountSnapshot, retryRate, shouldReevaluateResult.getRight()); } } }
double retryRate = (double)currentRetryCountSnapshot / currentTotalCountSnapshot;
private void recordOperation(boolean isRetry) { long totalSnapshot = this.totalOperationCount.incrementAndGet(); CurrentIntervalThresholds currentThresholdsSnapshot = this.currentThresholds.get(); long currentTotalCountSnapshot = currentThresholdsSnapshot.currentOperationCount.incrementAndGet(); long currentRetryCountSnapshot; if (isRetry) { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.incrementAndGet(); } else { currentRetryCountSnapshot = currentThresholdsSnapshot.currentRetriedOperationCount.get(); } Pair<Boolean, Boolean> shouldReevaluateResult = this.shouldReevaluateThresholds(totalSnapshot, currentTotalCountSnapshot); boolean shouldReevaluate = shouldReevaluateResult.getLeft(); if (shouldReevaluate) { boolean onlyUpscale = shouldReevaluateResult.getRight(); if (onlyUpscale || this.currentThresholds.compareAndSet(currentThresholdsSnapshot, new CurrentIntervalThresholds())) { this.reevaluateThresholds( totalSnapshot, currentTotalCountSnapshot, currentRetryCountSnapshot, shouldReevaluateResult.getRight()); } } }
class PartitionScopeThresholds<TContext> { private final static Logger logger = LoggerFactory.getLogger(PartitionScopeThresholds.class); private final String pkRangeId; private final BulkProcessingOptions<TContext> options; private final AtomicInteger targetMicroBatchSize; private final AtomicLong totalOperationCount; private final AtomicReference<CurrentIntervalThresholds> currentThresholds; private final String identifier = UUID.randomUUID().toString(); private final double minRetryRate; private final double maxRetryRate; private final double avgRetryRate; public PartitionScopeThresholds(String pkRangeId, BulkProcessingOptions<TContext> options) { checkNotNull(pkRangeId, "expected non-null pkRangeId"); checkNotNull(options, "expected non-null options"); this.pkRangeId = pkRangeId; this.options = options; this.targetMicroBatchSize = new AtomicInteger(options.getMaxMicroBatchSize()); this.totalOperationCount = new AtomicLong(0); this.currentThresholds = new AtomicReference<>(new CurrentIntervalThresholds()); this.minRetryRate = options.getMinTargetedMicroBatchRetryRate(); this.maxRetryRate = options.getMaxTargetedMicroBatchRetryRate(); this.avgRetryRate = ((this.maxRetryRate + this.minRetryRate)/2); } public String getPartitionKeyRangeId() { return this.pkRangeId; } private Pair<Boolean, Boolean> shouldReevaluateThresholds(long totalSnapshot, long currentSnapshot) { if (totalSnapshot < 1_000) { return Pair.of(currentSnapshot == 100, false); } if (totalSnapshot < 10_000) { return Pair.of(currentSnapshot == 1_000, false); } return Pair.of(currentSnapshot % 1_000 == 0, currentSnapshot % 10_000 == 0); } private void reevaluateThresholds( long totalCount, long currentCount, long retryCount, double retryRate, boolean onlyUpscale) { int microBatchSizeBefore = this.targetMicroBatchSize.get(); int microBatchSizeAfter = microBatchSizeBefore; if (retryRate < this.minRetryRate && microBatchSizeBefore < this.options.getMaxMicroBatchSize()) { int targetedNewBatchSize = Math.min( Math.min( microBatchSizeBefore * 2, microBatchSizeBefore + (int)(this.options.getMaxMicroBatchSize() * this.avgRetryRate)), this.options.getMaxMicroBatchSize()); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } else if (!onlyUpscale && retryRate > this.maxRetryRate && microBatchSizeBefore > 1) { double deltaRate = retryRate - this.avgRetryRate; int targetedNewBatchSize = Math.max(1, (int) (microBatchSizeBefore * (1 - deltaRate))); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } logger.debug( "Reevaluated thresholds for PKRange '{} "CurrentRetryRate: {} - BatchSize {} -> {}, OnlyUpscale: {})", this.pkRangeId, this.identifier, totalCount, currentCount, retryCount, retryRate, microBatchSizeBefore, microBatchSizeAfter, onlyUpscale); } public void recordSuccessfulOperation() { this.recordOperation(false); } public void recordEnqueuedRetry() { this.recordOperation(true); } public int getTargetMicroBatchSizeSnapshot() { return this.targetMicroBatchSize.get(); } private static class CurrentIntervalThresholds { public final AtomicLong currentOperationCount = new AtomicLong(0); public final AtomicLong currentRetriedOperationCount = new AtomicLong(0); } }
class PartitionScopeThresholds<TContext> { private final static Logger logger = LoggerFactory.getLogger(PartitionScopeThresholds.class); private final String pkRangeId; private final BulkProcessingOptions<TContext> options; private final AtomicInteger targetMicroBatchSize; private final AtomicLong totalOperationCount; private final AtomicReference<CurrentIntervalThresholds> currentThresholds; private final String identifier = UUID.randomUUID().toString(); private final double minRetryRate; private final double maxRetryRate; private final double avgRetryRate; public PartitionScopeThresholds(String pkRangeId, BulkProcessingOptions<TContext> options) { checkNotNull(pkRangeId, "expected non-null pkRangeId"); checkNotNull(options, "expected non-null options"); this.pkRangeId = pkRangeId; this.options = options; this.targetMicroBatchSize = new AtomicInteger(options.getMaxMicroBatchSize()); this.totalOperationCount = new AtomicLong(0); this.currentThresholds = new AtomicReference<>(new CurrentIntervalThresholds()); this.minRetryRate = options.getMinTargetedMicroBatchRetryRate(); this.maxRetryRate = options.getMaxTargetedMicroBatchRetryRate(); this.avgRetryRate = ((this.maxRetryRate + this.minRetryRate)/2); } public String getPartitionKeyRangeId() { return this.pkRangeId; } private Pair<Boolean, Boolean> shouldReevaluateThresholds(long totalSnapshot, long currentSnapshot) { if (totalSnapshot < 1_000) { return Pair.of(currentSnapshot == 100, false); } if (totalSnapshot < 10_000) { return Pair.of(currentSnapshot == 1_000, false); } return Pair.of(currentSnapshot % 1_000 == 0, currentSnapshot % 10_000 == 0); } private void reevaluateThresholds( long totalCount, long currentCount, long retryCount, boolean onlyUpscale) { double retryRate = currentCount == 0 ? 0 : (double)retryCount / currentCount; int microBatchSizeBefore = this.targetMicroBatchSize.get(); int microBatchSizeAfter = microBatchSizeBefore; if (retryRate < this.minRetryRate && microBatchSizeBefore < this.options.getMaxMicroBatchSize()) { int targetedNewBatchSize = Math.min( Math.min( microBatchSizeBefore * 2, microBatchSizeBefore + (int)(this.options.getMaxMicroBatchSize() * this.avgRetryRate)), this.options.getMaxMicroBatchSize()); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } else if (!onlyUpscale && retryRate > this.maxRetryRate && microBatchSizeBefore > 1) { double deltaRate = retryRate - this.avgRetryRate; int targetedNewBatchSize = Math.max(1, (int) (microBatchSizeBefore * (1 - deltaRate))); if (this.targetMicroBatchSize.compareAndSet(microBatchSizeBefore, targetedNewBatchSize)) { microBatchSizeAfter = targetedNewBatchSize; } } logger.debug( "Reevaluated thresholds for PKRange '{} "CurrentRetryRate: {} - BatchSize {} -> {}, OnlyUpscale: {})", this.pkRangeId, this.identifier, totalCount, currentCount, retryCount, retryRate, microBatchSizeBefore, microBatchSizeAfter, onlyUpscale); } public void recordSuccessfulOperation() { this.recordOperation(false); } public void recordEnqueuedRetry() { this.recordOperation(true); } public int getTargetMicroBatchSizeSnapshot() { return this.targetMicroBatchSize.get(); } private static class CurrentIntervalThresholds { public final AtomicLong currentOperationCount = new AtomicLong(0); public final AtomicLong currentRetriedOperationCount = new AtomicLong(0); } }
This is a break change. We should keep public APIs
public byte[] getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return amqpAnnotatedMessage.getBody().getFirstData(); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
case DATA:
public byte[] getBody() { return annotatedMessage.getBody().getFirstData(); }
class EventData { private static final int MAX_MESSAGE_ID_LENGTH = 128; private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final int MAX_SESSION_ID_LENGTH = 128; private final BinaryData body; private final AmqpAnnotatedMessage amqpAnnotatedMessage; private final ClientLogger logger = new ClientLogger(EventData.class); private Context context; /** * Creates an event containing the {@code body}. * * @param body The data to set for this event. * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(byte[] body) { this(BinaryData.fromBytes(Objects.requireNonNull(body, "'body' cannot be null."))); } /** * Creates an event containing the {@code body}. * * @param body The data to set for this event. * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(ByteBuffer body) { this(Objects.requireNonNull(body, "'body' cannot be null.").array()); } /** * Creates an event by encoding the {@code body} using UTF-8 charset. * * @param body The string that will be UTF-8 encoded to create an event. * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(String body) { this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(UTF_8)); } /** * Creates an event with the provided {@link BinaryData} as payload. * * @param body The {@link BinaryData} payload for this event. */ public EventData(BinaryData body) { this(body, Context.NONE); } /** * Creates an event with the given {@code body}, system properties and context. * * @param body The data to set for this event. * @param context A specified key-value pair of type {@link Context}. * @throws NullPointerException if {@code body}, {@code systemProperties}, or {@code context} is {@code null}. */ EventData(BinaryData body, Context context) { this.body = Objects.requireNonNull(body, "'body' cannot be null."); this.context = Objects.requireNonNull(context, "'context' cannot be null."); this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(AmqpMessageBody.fromData(body.toBytes())); } /** * Gets the set of free-form event properties which may be used for passing metadata associated with the event with * the event body during Event Hubs operations. A common use-case for {@code properties()} is to associate * serialization hints for the {@link * * <p><strong>Adding serialization hint using {@code getProperties()}</strong></p> * <p>In the sample, the type of telemetry is indicated by adding an application property with key "eventType".</p> * * {@codesnippet com.azure.messaging.eventhubs.eventdata.getProperties} * * @return Application properties associated with this {@link EventData}. */ public Map<String, Object> getProperties() { return amqpAnnotatedMessage.getApplicationProperties(); } /** * Gets the actual payload/data wrapped by EventData. * * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ /** * Returns event data as UTF-8 decoded string. * * @return UTF-8 decoded string representation of the event data. */ public String getBodyAsString() { return new String(body.toBytes(), UTF_8); } /** * Returns the {@link BinaryData} payload associated with this event. * * @return the {@link BinaryData} payload associated with this event. */ public BinaryData getBodyAsBinaryData() { return body; } /** * Gets the offset of the event when it was received from the associated Event Hub partition. This is only present * on a <b>received</b> {@link EventData}. * * @return The offset within the Event Hub partition of the received event. {@code null} if the {@link EventData} * was not received from Event Hubs service. */ public Long getOffset() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(OFFSET_ANNOTATION_NAME.getValue()); return value != null ? (Long) value : null; } /** * Sets the offset of the event when it was received from the associated Event Hub partition. * * @param offset Offset value of this message * * @return The updated {@link EventData}. * @see */ public EventData setOffset(Long offset) { amqpAnnotatedMessage.getMessageAnnotations().put(OFFSET_ANNOTATION_NAME.getValue(), offset); return this; } /** * Gets the partition hashing key if it was set when originally publishing the event. If it exists, this value was * used to compute a hash to select a partition to send the message to. This is only present on a <b>received</b> * {@link EventData}. * * @return A partition key for this Event Data. {@code null} if the {@link EventData} was not received from Event * Hubs service or there was no partition key set when the event was sent to the Event Hub. */ public String getPartitionKey() { return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue()); } /** * Sets the instant, in UTC, of when the event was enqueued in the Event Hub partition. * * @param enqueuedTime Enqueued time of this message * * @return The updated {@link EventData}. * @see */ public EventData setEnqueuedTime(Instant enqueuedTime) { amqpAnnotatedMessage.getMessageAnnotations().put(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue(), enqueuedTime); return this; } /** * Gets the instant, in UTC, of when the event was enqueued in the Event Hub partition. This is only present on a * <b>received</b> {@link EventData}. * * @return The instant, in UTC, this was enqueued in the Event Hub partition. {@code null} if the {@link EventData} * was not received from Event Hubs service. */ public Instant getEnqueuedTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); return value != null ? ((Date) value).toInstant() : null; } /** * Gets the sequence number assigned to the event when it was enqueued in the associated Event Hub partition. This * is unique for every message received in the Event Hub partition. This is only present on a <b>received</b> * {@link EventData}. * * @return The sequence number for this event. {@code null} if the {@link EventData} was not received from Event * Hubs service. */ public Long getSequenceNumber() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); return value != null ? (Long) value : null; } /** * Sets the sequence number assigned to the event when it was enqueued in the associated Event Hub partition. * * @param sequenceNumber Sequence number of this message * * @return The updated {@link EventData}. * @see */ public EventData setSequenceNumber(Long sequenceNumber) { amqpAnnotatedMessage.getMessageAnnotations().put(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber); return this; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventData eventData = (EventData) o; return Arrays.equals(body.toBytes(), eventData.body.toBytes()); } /** * {@inheritDoc} */ @Override public int hashCode() { return Arrays.hashCode(body.toBytes()); } /** * A specified key-value pair of type {@link Context} to set additional information on the event. * * @return the {@link Context} object set on the event */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Event Data. * * @param key The key for this context object * @param value The value for this context object. * @throws NullPointerException if {@code key} or {@code value} is null. * @return The updated {@link EventData}. */ public EventData addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } /** * Gets the content type of the message. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * @return The content type of the {@link EventData}. */ public String getContentType() { return amqpAnnotatedMessage.getProperties().getContentType(); } /** * Sets the content type of the {@link EventData}. * * <p> * Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, * for example "application/json". * </p> * * @param contentType RFC2045 Content-Type descriptor of the message. * * @return The updated {@link EventData}. */ public EventData setContentType(String contentType) { amqpAnnotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return The correlation id of this message. */ public String getCorrelationId() { String correlationId = null; AmqpMessageId amqpCorrelationId = amqpAnnotatedMessage.getProperties().getCorrelationId(); if (amqpCorrelationId != null) { correlationId = amqpCorrelationId.toString(); } return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link EventData}. * @see */ public EventData setCorrelationId(String correlationId) { AmqpMessageId id = null; if (correlationId != null) { id = new AmqpMessageId(correlationId); } amqpAnnotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. * </p> * * @return Id of the {@link EventData}. */ public byte[] getUserId() { return amqpAnnotatedMessage.getProperties().getUserId(); } /** * Sets the message id. * * @param userId The message id to be set. * * @return The updated {@link EventData}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public EventData setUserId(byte[] userId) { amqpAnnotatedMessage.getProperties().setUserId(userId); return this; } /** * Gets the message id. * * <p> * The message identifier is an application-defined value that uniquely identifies the message and its payload. The * identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. * </p> * * @return Id of the {@link EventData}. */ public String getMessageId() { String messageId = null; AmqpMessageId amqpMessageId = amqpAnnotatedMessage.getProperties().getMessageId(); if (amqpMessageId != null) { messageId = amqpMessageId.toString(); } return messageId; } /** * Sets the message id. * * @param messageId The message id to be set. * * @return The updated {@link EventData}. * @throws IllegalArgumentException if {@code messageId} is too long. */ public EventData setMessageId(String messageId) { checkIdLength("messageId", messageId, MAX_MESSAGE_ID_LENGTH); AmqpMessageId id = null; if (messageId != null) { id = new AmqpMessageId(messageId); } amqpAnnotatedMessage.getProperties().setMessageId(id); return this; } /** * Gets the subject for the message. * * <p> * This property enables the application to indicate the purpose of the message to the receiver in a standardized * fashion, similar to an email subject line. The mapped AMQP property is "subject". * </p> * * @return The subject for the message. */ public String getSubject() { return amqpAnnotatedMessage.getProperties().getSubject(); } /** * Sets the subject for the message. * * @param subject The application specific subject. * * @return The updated {@link EventData} object. */ public EventData setSubject(String subject) { amqpAnnotatedMessage.getProperties().setSubject(subject); return this; } /** * Gets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * auto-forward scenarios to indicate the intended logical destination of the message. * </p> * * @return "To" property value of this message */ public String getTo() { String to = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getTo(); if (amqpAddress != null) { to = amqpAddress.toString(); } return to; } /** * Sets the "to" address. * * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * auto-forward chaining scenarios to indicate the intended logical destination of the message. * </p> * * @param to To property value of this message. * * @return The updated {@link EventData}. */ public EventData setTo(String to) { AmqpAddress toAddress = null; if (to != null) { toAddress = new AmqpAddress(to); } amqpAnnotatedMessage.getProperties().setTo(toAddress); return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message */ public String getReplyTo() { String replyTo = null; AmqpAddress amqpAddress = amqpAnnotatedMessage.getProperties().getReplyTo(); if (amqpAddress != null) { replyTo = amqpAddress.toString(); } return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link EventData}. * @see */ public EventData setReplyTo(String replyTo) { AmqpAddress replyToAddress = null; if (replyTo != null) { replyToAddress = new AmqpAddress(replyTo); } amqpAnnotatedMessage.getProperties().setReplyTo(replyToAddress); return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message */ public Duration getTimeToLive() { return amqpAnnotatedMessage.getHeader().getTimeToLive(); } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link EventData}. * @see */ public EventData setTimeToLive(Duration timeToLive) { amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive); return this; } /** * Gets the session identifier for a session-aware entity. * * <p> * For session-aware entities, this application-defined value specifies the session affiliation of the message. * Messages with the same session identifier are subject to summary locking and enable exact in-order processing and * demultiplexing. For session-unaware entities, this value is ignored. * </p> * * @return The session id of the {@link EventData}. * @see <a href="https: */ public String getSessionId() { return amqpAnnotatedMessage.getProperties().getGroupId(); } /** * Sets the session identifier for a session-aware entity. * * @param sessionId The session identifier to be set. * * @return The updated {@link EventData}. * @throws IllegalArgumentException if {@code sessionId} is too long or if the {@code sessionId} does not match * the {@code partitionKey}. */ public EventData setSessionId(String sessionId) { checkIdLength("sessionId", sessionId, MAX_SESSION_ID_LENGTH); checkSessionId(sessionId); amqpAnnotatedMessage.getProperties().setGroupId(sessionId); return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the datetime at which the message will be enqueued in Azure Service Bus */ public OffsetDateTime getScheduledEnqueueTime() { Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((OffsetDateTime) value).toInstant().atOffset(ZoneOffset.UTC) : null; } /** * Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset * it could be done by value removing from {@link AmqpAnnotatedMessage * AmqpMessageConstant * * @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link EventData}. * @see */ public EventData setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) { if (scheduledEnqueueTime != null) { amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(), scheduledEnqueueTime); } return this; } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey The partition key of this message. * * @return The updated {@link EventData}. * @throws IllegalArgumentException if {@code partitionKey} is too long or if the {@code partitionKey} does not * match the {@code sessionId}. * @see */ public EventData setPartitionKey(String partitionKey) { checkIdLength("partitionKey", partitionKey, MAX_PARTITION_KEY_LENGTH); checkPartitionKey(partitionKey); amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey); return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the {@link * be set for the reply when sent to the reply entity. * * @return The {@code getReplyToGroupId} property value of this message. */ public String getReplyToSessionId() { return amqpAnnotatedMessage.getProperties().getReplyToGroupId(); } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId The ReplyToGroupId property value of this message. * * @return The updated {@link EventData}. */ public EventData setReplyToSessionId(String replyToSessionId) { amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId); return this; } /** * Gets the {@link AmqpAnnotatedMessage}. * * @return The raw AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return amqpAnnotatedMessage; } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkSessionId(String proposedSessionId) { if (proposedSessionId == null) { return; } if (this.getPartitionKey() != null && this.getPartitionKey().compareTo(proposedSessionId) != 0) { final String message = String.format( "sessionId:%s cannot be set to a different value than partitionKey:%s.", proposedSessionId, this.getPartitionKey()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Checks the length of ID fields. * * Some fields within the message will cause a failure in the service without enough context information. */ private void checkIdLength(String fieldName, String value, int maxLength) { if (value != null && value.length() > maxLength) { final String message = String.format("%s cannot be longer than %d characters.", fieldName, maxLength); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } /** * Validates that the user can't set the partitionKey to a different value than the session ID. (this will * eventually migrate to a service-side check) */ private void checkPartitionKey(String proposedPartitionKey) { if (proposedPartitionKey == null) { return; } if (this.getSessionId() != null && this.getSessionId().compareTo(proposedPartitionKey) != 0) { final String message = String.format( "partitionKey:%s cannot be set to a different value than sessionId:%s.", proposedPartitionKey, this.getSessionId()); throw logger.logExceptionAsError(new IllegalArgumentException(message)); } } }
class EventData { /* * These are properties owned by the service and set when a message is received. */ static final Set<String> RESERVED_SYSTEM_PROPERTIES; private final Map<String, Object> properties; private final SystemProperties systemProperties; private final AmqpAnnotatedMessage annotatedMessage; private Context context; static { final Set<String> properties = new HashSet<>(); properties.add(OFFSET_ANNOTATION_NAME.getValue()); properties.add(PARTITION_KEY_ANNOTATION_NAME.getValue()); properties.add(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue()); properties.add(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue()); properties.add(PUBLISHER_ANNOTATION_NAME.getValue()); RESERVED_SYSTEM_PROPERTIES = Collections.unmodifiableSet(properties); } /** * Creates an event containing the {@code body}. * * @param body The data to set for this event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(byte[] body) { this.context = Context.NONE; final AmqpMessageBody messageBody = AmqpMessageBody.fromData( Objects.requireNonNull(body, "'body' cannot be null.")); this.annotatedMessage = new AmqpAnnotatedMessage(messageBody); this.properties = annotatedMessage.getApplicationProperties(); this.systemProperties = new SystemProperties(); } /** * Creates an event containing the {@code body}. * * @param body The data to set for this event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(ByteBuffer body) { this(Objects.requireNonNull(body, "'body' cannot be null.").array()); } /** * Creates an event by encoding the {@code body} using UTF-8 charset. * * @param body The string that will be UTF-8 encoded to create an event. * * @throws NullPointerException if {@code body} is {@code null}. */ public EventData(String body) { this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(UTF_8)); } /** * Creates an event with the provided {@link BinaryData} as payload. * * @param body The {@link BinaryData} payload for this event. */ public EventData(BinaryData body) { this(Objects.requireNonNull(body, "'body' cannot be null.").toBytes()); } /** * Creates an event with the given {@code body}, system properties and context. Used in the case where a message * is received from the service. * * @param context A specified key-value pair of type {@link Context}. * @param amqpAnnotatedMessage Backing annotated message. * * @throws NullPointerException if {@code amqpAnnotatedMessage} or {@code context} is {@code null}. * @throws IllegalArgumentException if {@code amqpAnnotatedMessage}'s body type is unknown. */ EventData(AmqpAnnotatedMessage amqpAnnotatedMessage, SystemProperties systemProperties, Context context) { this.context = Objects.requireNonNull(context, "'context' cannot be null."); this.properties = Collections.unmodifiableMap(amqpAnnotatedMessage.getApplicationProperties()); this.annotatedMessage = Objects.requireNonNull(amqpAnnotatedMessage, "'amqpAnnotatedMessage' cannot be null."); this.systemProperties = systemProperties; switch (annotatedMessage.getBody().getBodyType()) { case DATA: break; case SEQUENCE: case VALUE: new ClientLogger(EventData.class).warning("Message body type '{}' is not supported in EH. " + " Getting contents of body may throw.", annotatedMessage.getBody().getBodyType()); break; default: throw new ClientLogger(EventData.class).logExceptionAsError(new IllegalArgumentException( "Body type not valid " + annotatedMessage.getBody().getBodyType())); } } /** * Gets the set of free-form event properties which may be used for passing metadata associated with the event with * the event body during Event Hubs operations. A common use-case for {@code properties()} is to associate * serialization hints for the {@link * * <p><strong>Adding serialization hint using {@code getProperties()}</strong></p> * <p>In the sample, the type of telemetry is indicated by adding an application property with key "eventType".</p> * * {@codesnippet com.azure.messaging.eventhubs.eventdata.getProperties} * * @return Application properties associated with this {@link EventData}. For received {@link EventData}, the map is * a read-only view. */ public Map<String, Object> getProperties() { return properties; } /** * Properties that are populated by Event Hubs service. As these are populated by the Event Hubs service, they are * only present on a <b>received</b> {@link EventData}. * * @return An encapsulation of all system properties appended by EventHubs service into {@link EventData}. {@code * null} if the {@link EventData} is not received from the Event Hubs service. */ public Map<String, Object> getSystemProperties() { return systemProperties; } /** * Gets the actual payload/data wrapped by EventData. * * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ /** * Returns event data as UTF-8 decoded string. * * @return UTF-8 decoded string representation of the event data. */ public String getBodyAsString() { return new String(annotatedMessage.getBody().getFirstData(), UTF_8); } /** * Returns the {@link BinaryData} payload associated with this event. * * @return the {@link BinaryData} payload associated with this event. */ public BinaryData getBodyAsBinaryData() { return BinaryData.fromBytes(annotatedMessage.getBody().getFirstData()); } /** * Gets the offset of the event when it was received from the associated Event Hub partition. This is only present * on a <b>received</b> {@link EventData}. * * @return The offset within the Event Hub partition of the received event. {@code null} if the {@link EventData} * was not received from Event Hubs service. */ public Long getOffset() { return systemProperties.getOffset(); } /** * Gets the partition hashing key if it was set when originally publishing the event. If it exists, this value was * used to compute a hash to select a partition to send the message to. This is only present on a <b>received</b> * {@link EventData}. * * @return A partition key for this Event Data. {@code null} if the {@link EventData} was not received from Event * Hubs service or there was no partition key set when the event was sent to the Event Hub. */ public String getPartitionKey() { return systemProperties.getPartitionKey(); } /** * Gets the instant, in UTC, of when the event was enqueued in the Event Hub partition. This is only present on a * <b>received</b> {@link EventData}. * * @return The instant, in UTC, this was enqueued in the Event Hub partition. {@code null} if the {@link EventData} * was not received from Event Hubs service. */ public Instant getEnqueuedTime() { return systemProperties.getEnqueuedTime(); } /** * Gets the sequence number assigned to the event when it was enqueued in the associated Event Hub partition. This * is unique for every message received in the Event Hub partition. This is only present on a <b>received</b> {@link * EventData}. * * @return The sequence number for this event. {@code null} if the {@link EventData} was not received from Event * Hubs service. */ public Long getSequenceNumber() { return systemProperties.getSequenceNumber(); } /** * Gets the underlying AMQP message. * * @return The underlying AMQP message. */ public AmqpAnnotatedMessage getRawAmqpMessage() { return annotatedMessage; } /** * Gets the content type. * * @return The content type. */ public String getContentType() { return annotatedMessage.getProperties().getContentType(); } /** * Sets the content type. * * @param contentType The content type. * * @return The updated {@link EventData}. */ public EventData setContentType(String contentType) { annotatedMessage.getProperties().setContentType(contentType); return this; } /** * Gets the correlation id. * * @return The correlation id. {@code null} if there is none set. */ public String getCorrelationId() { final AmqpMessageId messageId = annotatedMessage.getProperties().getCorrelationId(); return messageId != null ? messageId.toString() : null; } /** * Sets the correlation id. * * @param correlationId The correlation id. * * @return The updated {@link EventData}. */ public EventData setCorrelationId(String correlationId) { final AmqpMessageId id = correlationId != null ? new AmqpMessageId(correlationId) : null; annotatedMessage.getProperties().setCorrelationId(id); return this; } /** * Gets the message id. * * @return The message id. {@code null} if there is none set. */ public String getMessageId() { final AmqpMessageId messageId = annotatedMessage.getProperties().getMessageId(); return messageId != null ? messageId.toString() : null; } /** * Sets the message id. * * @param messageId The message id. * * @return The updated {@link EventData}. */ public EventData setMessageId(String messageId) { final AmqpMessageId id = messageId != null ? new AmqpMessageId(messageId) : null; annotatedMessage.getProperties().setMessageId(id); return this; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventData eventData = (EventData) o; return Arrays.equals(annotatedMessage.getBody().getFirstData(), eventData.annotatedMessage.getBody().getFirstData()); } /** * {@inheritDoc} */ @Override public int hashCode() { return Arrays.hashCode(annotatedMessage.getBody().getFirstData()); } /** * A specified key-value pair of type {@link Context} to set additional information on the event. * * @return the {@link Context} object set on the event */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Event Data. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link EventData}. * * @throws NullPointerException if {@code key} or {@code value} is null. */ public EventData addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } }