src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
UnmatchedMessageClassifier implements MessageClassifier { @Override public String toString() { return "unmatched"; } private UnmatchedMessageClassifier(); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final UnmatchedMessageClassifier ALWAYS_UNMATCHED; }
@Test public void testToString() { assertThat(underTest.toString(), is("unmatched")); }
UnmatchedMessageClassifier implements MessageClassifier { @Override public boolean equals(Object obj) { return this == obj; } private UnmatchedMessageClassifier(); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final UnmatchedMessageClassifier ALWAYS_UNMATCHED; }
@Test public void testEquals() { assertThat(underTest.equals(UnmatchedMessageClassifier.ALWAYS_UNMATCHED), is(true)); assertThat(underTest.equals(newClassifierCollection().build()), is(false)); assertThat(underTest.equals(null), is(false)); }
UnmatchedMessageClassifier implements MessageClassifier { @Override public int hashCode() { return 17 * 32; } private UnmatchedMessageClassifier(); @Override MessageClassificationOutcome classify(MessageClassificationContext context); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static final UnmatchedMessageClassifier ALWAYS_UNMATCHED; }
@Test public void testHashCode() { assertThat(underTest.hashCode(), is(544)); }
MessageClassificationExecutorService { @ApiOperation( value = "Start the Message Classification executor with the configuration in application.yml", code = 204 ) @POST @Path("/start") public void start() { LOGGER.info("MessageClassificationService scheduled to start in {} {} and then execute every {} {}", initialDelay, timeUnit, executionFrequency, timeUnit ); scheduleAtAFixedRate(initialDelay); } MessageClassificationExecutorService(ScheduledExecutorService scheduledExecutorService, MessageClassificationService messageClassificationService, long initialDelay, long executionFrequency, TimeUnit timeUnit); @ApiOperation( value = "Start the Message Classification executor with the configuration in application.yml", code = 204 ) @POST @Path("/start") void start(); @ApiOperation( value = "Synchronously execute the resend job for the given broker", code = 204 ) @POST @Path("/execute") void execute(); @ApiOperation( value = "Pause/Stop the Message Classification executor", code = 204 ) @PUT @Path("/pause") void pause(); void stop(); }
@Test public void jobExecutesSuccessfully() throws Exception { underTest.start(); verifyMessageClassificationServiceExecutions(75); } @Test public void jobContinuesToExecuteIfExceptionIsThrown() throws InterruptedException { doAnswer(decrementCountdownLatchAndThrowException()) .when(messageClassificationService) .classifyFailedMessages(); underTest.start(); verifyMessageClassificationServiceExecutions(75); verifyMessageClassificationServiceExecutions(120); }
MessageClassificationExecutorService { public void stop() { LOGGER.info("Stopping execution of the MessageClassificationService"); scheduledExecutorService.shutdown(); LOGGER.info("Execution of the MessageClassificationService stopped"); } MessageClassificationExecutorService(ScheduledExecutorService scheduledExecutorService, MessageClassificationService messageClassificationService, long initialDelay, long executionFrequency, TimeUnit timeUnit); @ApiOperation( value = "Start the Message Classification executor with the configuration in application.yml", code = 204 ) @POST @Path("/start") void start(); @ApiOperation( value = "Synchronously execute the resend job for the given broker", code = 204 ) @POST @Path("/execute") void execute(); @ApiOperation( value = "Pause/Stop the Message Classification executor", code = 204 ) @PUT @Path("/pause") void pause(); void stop(); }
@Test public void executorCanBeStopped() { underTest.stop(); assertThat(scheduledExecutorService.isShutdown(), is(true)); }
MessageClassificationResource implements MessageClassificationClient { @Override public void addMessageClassifier(MessageClassifier messageClassifier) { messageClassificationRepository.save(MessageClassifierGroup.newClassifierCollection().withClassifier(messageClassifier).build()); } MessageClassificationResource(MessageClassificationRepository messageClassificationRepository, FailedMessageSearchService failedMessageSearchService, MessageClassificationOutcomeAdapter outcomeAdapter); @Override void addMessageClassifier(MessageClassifier messageClassifier); @Override MessageClassifier listAllMessageClassifiers(); @Override void removeAllMessageClassifiers(); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessageId failedMessageId); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessage failedMessage); }
@Test public void addMessageClassifierDelegatesToRepository() { ArgumentCaptor<MessageClassifierGroup> captor = ArgumentCaptor.forClass(MessageClassifierGroup.class); Mockito.doNothing().when(repository).save(captor.capture()); underTest.addMessageClassifier(messageClassifier); assertThat(captor.getValue().getClassifiers(), contains(messageClassifier)); verify(repository).save(captor.getValue()); }
FailedMessageMongoDao implements FailedMessageDao { @Override public void addLabel(FailedMessageId failedMessageId, String label) { UpdateResult updateResult = collection.updateOne( failedMessageConverter.createId(failedMessageId), new Document("$addToSet", new Document(LABELS, label)) ); LOGGER.debug("{} rows updated", updateResult.getModifiedCount()); } FailedMessageMongoDao(MongoCollection<Document> collection, FailedMessageConverter failedMessageConverter, DocumentConverter<StatusHistoryEvent> failedMessageStatusConverter, RemoveRecordsQueryFactory removeRecordsQueryFactory); @Override void insert(FailedMessage failedMessage); @Override void update(FailedMessage failedMessage); @Override List<StatusHistoryEvent> getStatusHistory(FailedMessageId failedMessageId); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); @Override long findNumberOfMessagesForBroker(String broker); @Override long removeFailedMessages(); @Override void addLabel(FailedMessageId failedMessageId, String label); @Override void setLabels(FailedMessageId failedMessageId, Set<String> labels); @Override void removeLabel(FailedMessageId failedMessageId, String label); }
@Test public void addLabelToAFailedMessageThatDoesNotExist() { underTest.addLabel(failedMessageId, "foo"); assertThat(collection.count(), is(0L)); }
MessageClassificationResource implements MessageClassificationClient { @Override public MessageClassifier listAllMessageClassifiers() { return messageClassificationRepository.findLatest(); } MessageClassificationResource(MessageClassificationRepository messageClassificationRepository, FailedMessageSearchService failedMessageSearchService, MessageClassificationOutcomeAdapter outcomeAdapter); @Override void addMessageClassifier(MessageClassifier messageClassifier); @Override MessageClassifier listAllMessageClassifiers(); @Override void removeAllMessageClassifiers(); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessageId failedMessageId); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessage failedMessage); }
@Test public void listMessageClassifiers() { when(repository.findLatest()).thenReturn(messageClassifier); assertThat(underTest.listAllMessageClassifiers(), is(messageClassifier)); }
MessageClassificationResource implements MessageClassificationClient { @Override public void removeAllMessageClassifiers() { messageClassificationRepository.deleteAll(); } MessageClassificationResource(MessageClassificationRepository messageClassificationRepository, FailedMessageSearchService failedMessageSearchService, MessageClassificationOutcomeAdapter outcomeAdapter); @Override void addMessageClassifier(MessageClassifier messageClassifier); @Override MessageClassifier listAllMessageClassifiers(); @Override void removeAllMessageClassifiers(); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessageId failedMessageId); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessage failedMessage); }
@Test public void removeAllDelegatesFromRepository() { underTest.removeAllMessageClassifiers(); verify(repository).deleteAll(); }
MessageClassificationResource implements MessageClassificationClient { @Override public MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessageId failedMessageId) { return failedMessageSearchService.findById(failedMessageId) .map(this::classifyFailedMessage) .orElseThrow(failedMessageNotFound(failedMessageId)); } MessageClassificationResource(MessageClassificationRepository messageClassificationRepository, FailedMessageSearchService failedMessageSearchService, MessageClassificationOutcomeAdapter outcomeAdapter); @Override void addMessageClassifier(MessageClassifier messageClassifier); @Override MessageClassifier listAllMessageClassifiers(); @Override void removeAllMessageClassifiers(); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessageId failedMessageId); @Override MessageClassificationOutcomeResponse classifyFailedMessage(FailedMessage failedMessage); }
@Test(expected = FailedMessageNotFoundException.class) public void classifyByIfWhenFailedMessageDoesNotExist() { when(failedMessageSearchService.findById(failedMessageId)).thenReturn(Optional.empty()); underTest.classifyFailedMessage(failedMessageId); verifyZeroInteractions(messageClassifier); verifyZeroInteractions(outcomeAdapter); } @Test public void classifyByFailedMessageId() { when(failedMessageSearchService.findById(failedMessageId)).thenReturn(Optional.of(failedMessage)); when(repository.findLatest()).thenReturn(messageClassifier); when(messageClassifier.classify(new MessageClassificationContext(failedMessage))).thenReturn(messageClassificationOutcome); when(outcomeAdapter.toOutcomeResponse(messageClassificationOutcome)).thenReturn(messageClassificationOutcomeResponse); final MessageClassificationOutcomeResponse outcomeResponse = underTest.classifyFailedMessage(failedMessageId); assertThat(outcomeResponse, is(messageClassificationOutcomeResponse)); verify(failedMessageSearchService).findById(failedMessageId); verify(messageClassifier).classify(new MessageClassificationContext(failedMessage)); verify(outcomeAdapter).toOutcomeResponse(messageClassificationOutcome); verifyZeroInteractions(messageClassificationOutcome); } @Test public void classifyFailedMessage() { when(repository.findLatest()).thenReturn(messageClassifier); when(messageClassifier.classify(new MessageClassificationContext(failedMessage))).thenReturn(messageClassificationOutcome); when(outcomeAdapter.toOutcomeResponse(messageClassificationOutcome)).thenReturn(messageClassificationOutcomeResponse); final MessageClassificationOutcomeResponse outcome = underTest.classifyFailedMessage(failedMessage); assertThat(outcome, is(messageClassificationOutcomeResponse)); verify(messageClassifier).classify(new MessageClassificationContext(failedMessage)); verify(outcomeAdapter).toOutcomeResponse(messageClassificationOutcome); verifyZeroInteractions(messageClassificationOutcome); }
InMemoryMessageClassificationRepository implements MessageClassificationRepository { @Override public void deleteAll() { messageClassifiers.add(UnmatchedMessageClassifier.ALWAYS_UNMATCHED); } InMemoryMessageClassificationRepository(); InMemoryMessageClassificationRepository(Vector<MessageClassifier> messageClassifiers); @Override void save(MessageClassifier messageClassifier); @Override MessageClassifier findLatest(); @Override void deleteAll(); }
@Test public void deleteAllMessageClassifiers() { messageClassifiers.add(messageClassifier); underTest.deleteAll(); assertThat(messageClassifiers, contains(messageClassifier, ALWAYS_UNMATCHED)); }
InMemoryMessageClassificationRepository implements MessageClassificationRepository { @Override public MessageClassifier findLatest() { return messageClassifiers.isEmpty() ? null : messageClassifiers.lastElement(); } InMemoryMessageClassificationRepository(); InMemoryMessageClassificationRepository(Vector<MessageClassifier> messageClassifiers); @Override void save(MessageClassifier messageClassifier); @Override MessageClassifier findLatest(); @Override void deleteAll(); }
@Test public void findLatestMessageClassifiers() { messageClassifiers.add(mock(MessageClassifier.class)); messageClassifiers.add(messageClassifier); final MessageClassifier messageClassifiers = underTest.findLatest(); assertThat(messageClassifiers, is(messageClassifier)); } @Test public void findLatestMessageClassifierWhenEmpty() { assertThat(new InMemoryMessageClassificationRepository().findLatest(), nullValue()); }
MessageClassificationService { public void classifyFailedMessages() { Collection<FailedMessage> failedMessages = failedMessageSearchService.findByStatus(FAILED); if (failedMessages.isEmpty()) { LOGGER.info("No messages require classification"); return; } LOGGER.info("Attempting to classify {} messages", failedMessages.size()); MessageClassifier messageClassifiers = messageClassificationRepository.findLatest(); failedMessages .stream() .map(failedMessage -> messageClassifiers.classify(new MessageClassificationContext(failedMessage))) .peek(outcome -> LOGGER.debug("{}", outcome.getDescription())) .forEach(MessageClassificationOutcome::execute); } MessageClassificationService(FailedMessageSearchService failedMessageSearchService, MessageClassificationRepository messageClassificationRepository); void classifyFailedMessages(); }
@Test public void classifyFailedMessagesWhenNoneExist() { when(failedMessageSearchService.findByStatus(FAILED)).thenReturn(Collections.emptyList()); underTest.classifyFailedMessages(); verifyZeroInteractions(messageClassificationRepository); } @Test public void classifyFailedMessagesNotMatched() { when(failedMessageSearchService.findByStatus(FAILED)).thenReturn(singletonList(failedMessage)); when(messageClassificationRepository.findLatest()).thenReturn(messageClassifier); when(messageClassifier.classify(new MessageClassificationContext(failedMessage))).thenReturn(messageClassificationOutcome); when(messageClassificationOutcome.isMatched()).thenReturn(false); underTest.classifyFailedMessages(); verify(messageClassifier).classify(new MessageClassificationContext(failedMessage)); verify(messageClassificationOutcome).getDescription(); verify(messageClassificationOutcome).execute(); } @Test public void classifyFailedMessagesMatched() { when(failedMessageSearchService.findByStatus(FAILED)).thenReturn(singletonList(failedMessage)); when(messageClassificationRepository.findLatest()).thenReturn(messageClassifier); when(messageClassifier.classify(new MessageClassificationContext(failedMessage))).thenReturn(messageClassificationOutcome); underTest.classifyFailedMessages(); verify(messageClassifier).classify(new MessageClassificationContext(failedMessage)); verify(messageClassificationOutcome).getDescription(); verify(messageClassificationOutcome).execute(); }
FailedMessageMongoDao implements FailedMessageDao { @Override public void removeLabel(FailedMessageId failedMessageId, String label) { collection.updateOne( failedMessageConverter.createId(failedMessageId), new Document("$pull", new Document(LABELS, label)) ); } FailedMessageMongoDao(MongoCollection<Document> collection, FailedMessageConverter failedMessageConverter, DocumentConverter<StatusHistoryEvent> failedMessageStatusConverter, RemoveRecordsQueryFactory removeRecordsQueryFactory); @Override void insert(FailedMessage failedMessage); @Override void update(FailedMessage failedMessage); @Override List<StatusHistoryEvent> getStatusHistory(FailedMessageId failedMessageId); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); @Override long findNumberOfMessagesForBroker(String broker); @Override long removeFailedMessages(); @Override void addLabel(FailedMessageId failedMessageId, String label); @Override void setLabels(FailedMessageId failedMessageId, Set<String> labels); @Override void removeLabel(FailedMessageId failedMessageId, String label); }
@Test public void removeLabelForAFailedMessageThatDoesNotExist() { underTest.removeLabel(failedMessageId, "bar"); assertThat(collection.count(), is(0L)); }
PingServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { responseWriter.write(resp.getWriter()); } catch (IOException e) { handleError(resp, e); } } PingServlet(PingResponseWriter responseWriter); }
@Test public void successfullyWriteAResponse() throws Exception { when(httpServletResponse.getWriter()).thenReturn(printWriter); underTest.doGet(httpServletRequest, httpServletResponse); verify(responseWriter).write(printWriter); verifyZeroInteractions(httpServletRequest); } @Test public void unableToWriteAResponse() throws IOException, ServletException { when(httpServletResponse.getWriter()).thenThrow(IOException.class); underTest.doGet(httpServletRequest, httpServletResponse); verify(httpServletResponse).sendError(500, "An error occurred writing the response"); verifyZeroInteractions(responseWriter); verifyZeroInteractions(httpServletRequest); }
FailedMessageNotFoundException extends RuntimeException { public static Supplier<FailedMessageNotFoundException> failedMessageNotFound(FailedMessageId failedMessageId) { return () -> new FailedMessageNotFoundException(failedMessageId); } FailedMessageNotFoundException(FailedMessageId failedMessageId); static Supplier<FailedMessageNotFoundException> failedMessageNotFound(FailedMessageId failedMessageId); }
@Test public void verifySupplier() { final FailedMessageNotFoundException underTest = FailedMessageNotFoundException.failedMessageNotFound(FAILED_MESSAGE_ID).get(); assertEquals("Failed Message: " + FAILED_MESSAGE_ID + " not found", underTest.getMessage()); assertEquals("Failed Message: " + FAILED_MESSAGE_ID + " not found", underTest.getLocalizedMessage()); assertNull(underTest.getCause()); }
FailedMessageResponseFactory { public FailedMessageResponse create(FailedMessage failedMessage) { return new FailedMessageResponse( failedMessage.getFailedMessageId(), failedMessage.getDestination().getBrokerName(), failedMessage.getDestination().getName(), failedMessage.getSentAt(), failedMessage.getFailedAt(), failedMessage.getContent(), FailedMessageStatusAdapter.toFailedMessageStatus(failedMessage.getStatusHistoryEvent().getStatus()), failedMessage.getProperties(), failedMessage.getLabels()); } FailedMessageResponse create(FailedMessage failedMessage); }
@Test public void createFailedMessageResponseFromAFailedMessage() { FailedMessageResponse failedMessageResponse = underTest.create(newFailedMessage() .withContent("Hello World") .withDestination(new Destination("broker", of("queue"))) .withFailedDateTime(NOW) .withFailedMessageId(FAILED_MESSAGE_ID) .withProperties(Collections.singletonMap("foo", "bar")) .withSentDateTime(NOW) .build() ); assertThat(failedMessageResponse, CoreMatchers.is(aFailedMessage() .withFailedMessageId(equalTo(FAILED_MESSAGE_ID)) .withContent(equalTo("Hello World")) .withBroker(equalTo("broker")) .withDestination(equalTo(of("queue"))) .withFailedAt(equalTo(NOW)) .withProperties(Matchers.hasEntry("foo", "bar")) .withSentAt(equalTo(NOW)))); }
StatusUpdateRequestAdapter implements UpdateRequestAdapter<StatusUpdateRequest> { @Override public void adapt(StatusUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder) { failedMessageBuilder.withStatusHistoryEvent(new StatusHistoryEvent(updateRequest.getStatus(), updateRequest.getEffectiveDateTime())); } @Override void adapt(StatusUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder); }
@Test public void statusHistoryEventIsSet() { underTest.adapt(new StatusUpdateRequest(FAILED, NOW), failedMessageBuilder); verify(failedMessageBuilder).withStatusHistoryEvent( argThat(new HamcrestArgumentMatcher<>(StatusHistoryEventMatcher.equalTo(FAILED).withUpdatedDateTime(NOW))) ); }
LoggingUpdateRequestAdapter implements UpdateRequestAdapter<UpdateRequest> { @Override public void adapt(UpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder) { getLogger().warn("UpdateRequestAdapter not found for: {}", updateRequest.getClass().getName()); } @Override void adapt(UpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder); }
@Test public void classNameIsLoggedByTheAdapter() { underTest.adapt(new ExampleUpdateRequest(), failedMessageBuilder); verify(logger).warn("UpdateRequestAdapter not found for: {}", ExampleUpdateRequest.class.getName()); }
DestinationUpdateRequestAdapter implements UpdateRequestAdapter<DestinationUpdateRequest> { @Override public void adapt(DestinationUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder) { failedMessageBuilder.withDestination(new Destination(updateRequest.getBroker(), Optional.ofNullable(updateRequest.getDestination()))); } @Override void adapt(DestinationUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder); }
@Test public void verifyDestinationAdaptedCorrectly() { underTest.adapt(new DestinationUpdateRequest(BROKER_NAME, DESTINATION_NAME), failedMessageBuilder); verify(failedMessageBuilder).withDestination(new Destination(BROKER_NAME, Optional.of(DESTINATION_NAME))); }
PropertiesUpdateRequestAdapter implements UpdateRequestAdapter<PropertiesUpdateRequest> { @Override public void adapt(PropertiesUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder) { updateRequest.getDeletedProperties().forEach(failedMessageBuilder::removeProperty); updateRequest.getUpdatedProperties().forEach(failedMessageBuilder::withProperty); } @Override void adapt(PropertiesUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder); }
@Test public void propertiesAreDeleted() { underTest.adapt(new PropertiesUpdateRequest(Collections.singleton(SOME_KEY), Collections.emptyMap()), failedMessageBuilder); verify(failedMessageBuilder).removeProperty(SOME_KEY); verifyNoMoreInteractions(failedMessageBuilder); } @Test public void propertiesAreUpdated() { underTest.adapt(new PropertiesUpdateRequest(Collections.emptySet(), Collections.singletonMap(SOME_KEY, SOME_VALUE)), failedMessageBuilder); verify(failedMessageBuilder).withProperty(SOME_KEY, SOME_VALUE); verifyNoMoreInteractions(failedMessageBuilder); }
ContentUpdateRequestAdapter implements UpdateRequestAdapter<ContentUpdateRequest> { @Override public void adapt(ContentUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder) { failedMessageBuilder.withContent(updateRequest.getContent()); } @Override void adapt(ContentUpdateRequest updateRequest, FailedMessageBuilder failedMessageBuilder); }
@Test public void verifyMessageContentAdaptedCorrectly() { underTest.adapt(new ContentUpdateRequest("some-content"), failedMessageBuilder); verify(failedMessageBuilder).withContent("some-content"); }
UpdateRequestAdapterRegistry { @SuppressWarnings("unchecked") public <T extends UpdateRequest> UpdateRequestAdapter<T> getAdapter(T updateRequest) { return updateRequestAdapters.getOrDefault(updateRequest.getClass(), defaultUpdateRequestAdapter); } UpdateRequestAdapterRegistry(UpdateRequestAdapter<UpdateRequest> defaultUpdateRequestAdapter); UpdateRequestAdapterRegistry addAdapter(Class<T> clazz, UpdateRequestAdapter<T> adapter); @SuppressWarnings("unchecked") UpdateRequestAdapter<T> getAdapter(T updateRequest); }
@Test public void defaultAdapterIsReturnedWhenAdapterNotFoundForClass() { assertThat(underTest.getAdapter(updateRequest), is(defaultUpdateRequestAdapter)); }
FailedMessageSender implements MessageSender { public void send(FailedMessage failedMessage) { try { messageSender.send(failedMessage); failedMessageService.update(failedMessage.getFailedMessageId(), statusUpdateRequest(SENT)); } catch (Exception e) { LOGGER.error("Could not send FailedMessage: " + failedMessage.getFailedMessageId(), e); } } FailedMessageSender(MessageSender messageSender, FailedMessageService failedMessageService); void send(FailedMessage failedMessage); }
@Test public void successfullySendMessage() { when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); underTest.send(failedMessage); verify(messageSender).send(failedMessage); verify(failedMessageService).update(eq(FAILED_MESSAGE_ID), statusUpdateRequest.capture()); assertThat(statusUpdateRequest.getValue(), is(aStatusUpdateRequest(SENT))); }
MongoSearchRequestAdapter { public Document toQuery(SearchFailedMessageRequest request) { Document query; if (!request.getStatuses().isEmpty()) { query = mongoStatusHistoryQueryBuilder.currentStatusIn(fromFailedMessageStatus(request.getStatuses())); } else { query = mongoStatusHistoryQueryBuilder.currentStatusNotEqualTo(DELETED); } List<Document> predicates = new ArrayList<>(); request.getBroker().ifPresent(broker -> predicates.add(new Document(DESTINATION + "." + BROKER_NAME, broker))); request.getDestination().ifPresent(destination -> predicates.add(new Document(DESTINATION + "." + NAME, destination))); request.getContent().ifPresent(content -> predicates.add(new Document(CONTENT, Pattern.compile(content)))); request.getJmsMessageId().ifPresent(jmsMessageId -> predicates.add(new Document(JMS_MESSAGE_ID, jmsMessageId))); if (!predicates.isEmpty()) { query.append(request.getOperator() == AND ? QueryOperators.AND : QueryOperators.OR, predicates); } return query; } MongoSearchRequestAdapter(); Document toQuery(SearchFailedMessageRequest request); }
@Test public void searchRequestMatchingAllCriteriaWithAllParametersSpecified() { final Document document = underTest.toQuery(searchMatchingAllCriteria() .withBroker("broker-name") .withDestination("mars") .withStatus(FailedMessageStatus.FAILED) .withStatus(FailedMessageStatus.RESENDING) .withStatus(FailedMessageStatus.SENT) .withContent("id") .withJmsMessageId("ID:localhost.localdomain-46765-1518703251379-5:1:1:1:1") .build() ); assertThat(document, allOf( hasField("statusHistory.0.status", hasField(IN, hasItems("FAILED", "CLASSIFIED", "RESEND", "SENT"))), hasField("$and", containsInAnyOrder( hasField("destination.brokerName", equalTo("broker-name")), hasField("destination.name", equalTo("mars")), hasField("content", allOf(willMatch("user_id"), willMatch("id"), willMatch("hidden"), not(willMatch("find")))), hasField("jmsMessageId", equalTo("ID:localhost.localdomain-46765-1518703251379-5:1:1:1:1")) )))); } @Test public void searchRequestMatchingAnyCriteriaWithAllParametersSpecified() { final Document document = underTest.toQuery(searchMatchingAnyCriteria() .withBroker("broker-name") .withDestination("mars") .withStatus(FailedMessageStatus.FAILED) .withStatus(FailedMessageStatus.RESENDING) .withStatus(FailedMessageStatus.SENT) .withContent("id") .withJmsMessageId("ID:localhost.localdomain-46765-1518703251379-5:1:1:1:1") .build() ); assertThat(document, allOf( hasField("statusHistory.0.status", hasField(IN, hasItems("FAILED", "CLASSIFIED", "RESEND", "SENT"))), hasField("$or", containsInAnyOrder( hasField("destination.brokerName", equalTo("broker-name")), hasField("destination.name", equalTo("mars")), hasField("content", allOf(willMatch("user_id"), willMatch("id"), willMatch("hidden"), not(willMatch("find")))), hasField("jmsMessageId", equalTo("ID:localhost.localdomain-46765-1518703251379-5:1:1:1:1")) )))); } @Test public void searchRequestWithoutDestinationAndBrokerAndDefaultStatus() { final Document document = underTest.toQuery(searchMatchingAllCriteria().build()); assertThat(document, Matchers.allOf( hasField("statusHistory.0.status", hasField("$ne", equalTo("DELETED"))) )); }
MongoFailedMessageSearchService implements FailedMessageSearchService { @Override public Collection<FailedMessage> search(SearchFailedMessageRequest request) { final List<FailedMessage> failedMessages = getFailedMessages(mongoSearchRequestAdapter.toQuery(request)); LOGGER.debug("Found {} failedMessages", failedMessages.size()); return failedMessages; } MongoFailedMessageSearchService(MongoCollection<Document> dbCollection, MongoSearchRequestAdapter mongoSearchRequestAdapter, FailedMessageConverter failedMessageConverter, MongoStatusHistoryQueryBuilder mongoStatusHistoryQueryBuilder, FailedMessageDao failedMessageDao); @Override Collection<FailedMessage> search(SearchFailedMessageRequest request); @Override Collection<FailedMessage> findByStatus(StatusHistoryEvent.Status status); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); }
@Test public void search() { failedMessageMongoDao.insert(failedMessageBuilder.build()); when(mongoSearchRequestAdapter.toQuery(request)).thenReturn(new Document()); assertThat(underTest.search(request), contains(aFailedMessage().withFailedMessageId(equalTo(failedMessageId)))); }
MongoFailedMessageSearchService implements FailedMessageSearchService { @Override public Collection<FailedMessage> findByStatus(StatusHistoryEvent.Status status) { final List<FailedMessage> failedMessages = getFailedMessages(mongoStatusHistoryQueryBuilder.currentStatusEqualTo(status)); LOGGER.debug("Found {} failedMessages with status {}", failedMessages.size(), status); return failedMessages; } MongoFailedMessageSearchService(MongoCollection<Document> dbCollection, MongoSearchRequestAdapter mongoSearchRequestAdapter, FailedMessageConverter failedMessageConverter, MongoStatusHistoryQueryBuilder mongoStatusHistoryQueryBuilder, FailedMessageDao failedMessageDao); @Override Collection<FailedMessage> search(SearchFailedMessageRequest request); @Override Collection<FailedMessage> findByStatus(StatusHistoryEvent.Status status); @Override Optional<FailedMessage> findById(FailedMessageId failedMessageId); }
@Test public void findByStatus() { failedMessageMongoDao.insert(failedMessageBuilder.build()); when(mongoStatusHistoryQueryBuilder.currentStatusEqualTo(FAILED)).thenReturn(new Document()); assertThat(underTest.findByStatus(FAILED), contains(aFailedMessage().withFailedMessageId(equalTo(failedMessageId)))); }
MongoSearchResponseAdapter { public SearchFailedMessageResponse toResponse(Document document) { final Destination destination = failedMessageConverter.getDestination(document); final StatusHistoryEvent statusHistoryEvent = failedMessageConverter.getStatusHistoryEvent(document); return newSearchFailedMessageResponse() .withFailedMessageId(failedMessageConverter.getFailedMessageId(document)) .withBroker(destination.getBrokerName()) .withDestination(destination.getName().orElse(null)) .withContent(failedMessageConverter.getContent(document)) .withStatus(toFailedMessageStatus(statusHistoryEvent.getStatus())) .withStatusDateTime(statusHistoryEvent.getEffectiveDateTime()) .build(); } MongoSearchResponseAdapter(FailedMessageConverter failedMessageConverter); SearchFailedMessageResponse toResponse(Document document); }
@Test public void convertBasicDBbjectToSearchResponse() { when(failedMessageConverter.getDestination(document)).thenReturn(new Destination("broker-name", Optional.of("queue-name"))); when(failedMessageConverter.getStatusHistoryEvent(document)).thenReturn(new StatusHistoryEvent(StatusHistoryEvent.Status.FAILED, NOW)); when(failedMessageConverter.getFailedMessageId(document)).thenReturn(FAILED_MESSAGE_ID); when(failedMessageConverter.getContent(document)).thenReturn("some-content"); SearchFailedMessageResponse response = underTest.toResponse(document); assertThat(response, new TypeSafeMatcher<SearchFailedMessageResponse>() { @Override public void describeTo(Description description) { } @Override protected boolean matchesSafely(SearchFailedMessageResponse response) { return FAILED_MESSAGE_ID.equals(response.getFailedMessageId()) && "some-content".equals(response.getContent()) && NOW.equals(response.getStatusDateTime()) && FailedMessageStatus.FAILED.equals(response.getStatus()) && "broker-name".equals(response.getBroker()) && Optional.of("queue-name").equals(response.getDestination()); } }); }
SearchFailedMessageResponseAdapter { public SearchFailedMessageResponse toResponse(FailedMessage failedMessage) { return newSearchFailedMessageResponse() .withBroker(failedMessage.getDestination().getBrokerName()) .withContent(failedMessage.getContent()) .withDestination(failedMessage.getDestination().getName().orElse(null)) .withStatus(FailedMessageStatusAdapter.toFailedMessageStatus(failedMessage.getStatusHistoryEvent().getStatus())) .withStatusDateTime(failedMessage.getStatusHistoryEvent().getEffectiveDateTime()) .withFailedMessageId(failedMessage.getFailedMessageId()) .withJmsMessageId(failedMessage.getJmsMessageId()) .withLabels(failedMessage.getLabels()) .build(); } SearchFailedMessageResponse toResponse(FailedMessage failedMessage); }
@Test public void destinationNameIsEmpty() { assertThat(underTest.toResponse(failedMessageBuilder.withDestination(new Destination(BROKER_NAME, Optional.empty())).build()), is(aFailedMessage() .withBroker(equalTo(BROKER_NAME)) .withContent(equalTo(SOME_CONTENT)) .withDestination(equalTo(Optional.empty())) .withStatus(FailedMessageStatus.FAILED) .withStatusDateTime(NOW) .withFailedMessageId(equalTo(FAILED_MESSAGE_ID)) .withJmsMessageId(equalTo(JMS_MESSAGE_ID)) .withLabels(contains("foo")) )); } @Test public void destinationNameIsPopulated() { assertThat(underTest.toResponse(failedMessageBuilder.withDestination(new Destination(BROKER_NAME, Optional.of(DESTINATION_NAME))).build()), is(aFailedMessage() .withBroker(equalTo(BROKER_NAME)) .withContent(equalTo(SOME_CONTENT)) .withDestination(equalTo(Optional.of(DESTINATION_NAME))) .withStatus(FailedMessageStatus.FAILED) .withStatusDateTime(NOW) .withFailedMessageId(equalTo(FAILED_MESSAGE_ID)) .withJmsMessageId(equalTo(JMS_MESSAGE_ID)) .withLabels(contains("foo")) )); }
ActiveMQDestinationExtractor implements DestinationExtractor<ActiveMQMessage> { @Override public Destination extractDestination(ActiveMQMessage message) { return new Destination( brokerName, ofNullable(message.getOriginalDestination()) .map(ActiveMQDestination::getPhysicalName) ); } ActiveMQDestinationExtractor(String brokerName); @Override Destination extractDestination(ActiveMQMessage message); }
@Test public void createWhenOriginalDestinationPresent() { ActiveMQMessage message = mock(ActiveMQMessage.class); when(message.getOriginalDestination()).thenReturn(new ActiveMQQueue("queue.name")); Destination destination = underTest.extractDestination(message); assertThat(destination, equalTo(new Destination("internal", Optional.of("queue.name")))); } @Test public void createWhenOriginalDestinationNotPresent() { ActiveMQMessage message = mock(ActiveMQMessage.class); when(message.getOriginalDestination()).thenReturn(null); Destination destination = underTest.extractDestination(message); assertThat(destination, is(aDestination().withBrokerName("internal").withNoName())); }
ResendScheduledExecutorsResource { @ApiOperation("Start the resend executor for the given broker") @POST @Path("/start") public void start( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName) { getExecutor(brokerName).start(); } ResendScheduledExecutorsResource(Map<String, ResendScheduledExecutorService> resendScheduledExecutors); @ApiOperation("Start the resend executor for the given broker") @POST @Path("/start") void start( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Synchronously execute the resend job for the given broker") @POST @Path("/execute") void execute( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Pause the resend executor for the given broker") @PUT @Path("/pause") void pause( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); }
@Test(expected = BadRequestException.class) public void startThrowsABadRequestExceptionIfBrokerIsUnknown() { underTest.start("unknown-broker"); } @Test public void startResendScheduledExecutorService() { underTest.start("internal-broker"); verify(resendScheduledExecutorService).start(); }
ActiveMQFailedMessageFactory implements FailedMessageFactory { @Override public FailedMessage createFailedMessage(Message message) throws JMSException { validateMessageOfCorrectType(message); ActiveMQMessage activeMQMessage = (ActiveMQMessage) message; return FailedMessageBuilder.newFailedMessage() .withJmsMessageId(message.getJMSMessageID()) .withContent(messageTextExtractor.extractText(message)) .withDestination(destinationExtractor.extractDestination(activeMQMessage)) .withSentDateTime(extractTimestamp(activeMQMessage.getTimestamp())) .withFailedDateTime(extractTimestamp(activeMQMessage.getBrokerInTime())) .withProperties(messagePropertyExtractor.extractProperties(message)) .withFailedMessageIdFromPropertyIfPresent() .build(); } ActiveMQFailedMessageFactory(MessageTextExtractor messageTextExtractor, DestinationExtractor<ActiveMQMessage> destinationExtractor, MessagePropertyExtractor messagePropertyExtractor); @Override FailedMessage createFailedMessage(Message message); }
@Test public void exceptionIsThrownIfMessageIsNull() throws JMSException { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Message cannot be null"); underTest.createFailedMessage(null); } @Test public void exceptionIsThrownIfMessageIsNotActiveMQMessage() throws JMSException { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Expected ActiveMQMessage received: " + SomeMessage.class.getName()); underTest.createFailedMessage(new SomeMessage()); } @Test public void createAFailedMessage() throws JMSException { when(messageTextExtractor.extractText(message)).thenReturn(MESSAGE_CONTENT); when(destinationExtractor.extractDestination(message)).thenReturn(new Destination("broker.name", of("queue.name"))); when(messagePropertyExtractor.extractProperties(message)).thenReturn(emptyMap()); when(message.getJMSMessageID()).thenReturn(JMS_MESSAGE_ID); when(message.getTimestamp()).thenReturn(NOW.minusSeconds(5).toEpochMilli()); when(message.getBrokerInTime()).thenReturn(NOW.toEpochMilli()); FailedMessage failedMessage = underTest.createFailedMessage(message); assertThat(failedMessage, is(aFailedMessage() .withJmsMessageId(equalTo(JMS_MESSAGE_ID)) .withContent(equalTo(MESSAGE_CONTENT)) .withDestination(aDestination().withBrokerName("broker.name").withName("queue.name")) .withSentAt(equalTo(NOW.minusSeconds(5))) .withFailedAt(equalTo(NOW)) .withProperties(equalTo(emptyMap())))); } @Test public void createAFailedMessageWithFailedMessageIdFromProperty() throws JMSException { final Map<String, Object> messageProperties = singletonMap(FAILED_MESSAGE_ID, FAILED_MESSAGE_ID_VALUE.toString()); when(messageTextExtractor.extractText(message)).thenReturn(MESSAGE_CONTENT); when(destinationExtractor.extractDestination(message)).thenReturn(new Destination("broker.name", of("queue.name"))); when(messagePropertyExtractor.extractProperties(message)).thenReturn(messageProperties); when(message.getJMSMessageID()).thenReturn(JMS_MESSAGE_ID); when(message.getTimestamp()).thenReturn(NOW.minusSeconds(5).toEpochMilli()); when(message.getBrokerInTime()).thenReturn(NOW.toEpochMilli()); FailedMessage failedMessage = underTest.createFailedMessage(message); assertThat(failedMessage, is(aFailedMessage() .withFailedMessageId(equalTo(FAILED_MESSAGE_ID_VALUE)) .withJmsMessageId(equalTo(JMS_MESSAGE_ID)) .withContent(equalTo(MESSAGE_CONTENT)) .withDestination(aDestination().withBrokerName("broker.name").withName("queue.name")) .withSentAt(equalTo(NOW.minusSeconds(5))) .withFailedAt(equalTo(NOW)) .withProperties(equalTo(messageProperties)))); }
QueueBrowserService { public void browse() { jmsTemplate.browse(queueName, browserCallback); } QueueBrowserService(BrowserCallback<T> browserCallback, JmsTemplate jmsTemplate, String brokerName, String queueName); void browse(); String getBrokerName(); }
@Test public void browseDelegatesToJmsTemplate() { underTest.browse(); verify(jmsTemplate).browse("some-queue", browserCallback); }
QueueBrowserService { public String getBrokerName() { return brokerName; } QueueBrowserService(BrowserCallback<T> browserCallback, JmsTemplate jmsTemplate, String brokerName, String queueName); void browse(); String getBrokerName(); }
@Test public void brokerNameIsAvailable() { assertThat(underTest.getBrokerName(), is("some-broker")); }
QueueBrowserCallback implements BrowserCallback<Long> { @Override public Long doInJms(Session session, QueueBrowser browser) throws JMSException { long records = 0; LOGGER.debug("Browsing messages on {}", browser.getQueue()); final Enumeration enumeration = browser.getEnumeration(); while (enumeration.hasMoreElements()) { final Message message = (Message) enumeration.nextElement(); failedMessageListener.onMessage(message); records++; } LOGGER.debug("Processed {} messages on {}", records, browser.getQueue()); return records; } QueueBrowserCallback(FailedMessageListener failedMessageListener); @Override Long doInJms(Session session, QueueBrowser browser); }
@Test public void noMessagesToBrowse() throws JMSException { when(queueBrowser.getEnumeration()).thenReturn(enumeration); when(enumeration.hasMoreElements()).thenReturn(false); assertThat(underTest.doInJms(session, queueBrowser), is(0L)); verifyZeroInteractions(failedMessageListener); } @Test public void messagesToBrowse() throws JMSException { when(queueBrowser.getEnumeration()).thenReturn(enumeration); when(enumeration.hasMoreElements()).thenReturn(true).thenReturn(true).thenReturn(false); when(enumeration.nextElement()).thenReturn(textMessage1).thenReturn(textMessage2); assertThat(underTest.doInJms(session, queueBrowser), is(2L)); verify(failedMessageListener).onMessage(textMessage1); verify(failedMessageListener).onMessage(textMessage2); verifyZeroInteractions(failedMessageListener); }
QueueBrowserServiceBeanDefinitionFactory { public AbstractBeanDefinition create(String queueBrowserCallbackBeanName, String jmsTemplateBeanName, String brokerName, String queueName) { return genericBeanDefinition(QueueBrowserService.class) .addConstructorArgReference(queueBrowserCallbackBeanName) .addConstructorArgReference(jmsTemplateBeanName) .addConstructorArgValue(brokerName) .addConstructorArgValue(queueName) .getBeanDefinition(); } AbstractBeanDefinition create(String queueBrowserCallbackBeanName, String jmsTemplateBeanName, String brokerName, String queueName); String createBeanName(String brokerName); }
@Test public void createQueueBrowserServiceBeanDefinition() { AbstractBeanDefinition abstractBeanDefinition = underTest.create("queueBrowserCallback", "messageSender", BROKER_NAME, QUEUE_NAME); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(QueueBrowserService.class)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getIndexedArgumentValues().size(), is(4)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(0, BrowserCallback.class).getValue(), is(equalTo(new RuntimeBeanReference("queueBrowserCallback")))); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(1, JmsTemplate.class).getValue(), is(equalTo(new RuntimeBeanReference("messageSender")))); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(2, String.class).getValue(), is(BROKER_NAME)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(3, String.class).getValue(), is(QUEUE_NAME)); }
QueueBrowserServiceBeanDefinitionFactory { public String createBeanName(String brokerName) { return QUEUE_BROWSER_SERVICE_BEAN_NAME_PREFIX + brokerName; } AbstractBeanDefinition create(String queueBrowserCallbackBeanName, String jmsTemplateBeanName, String brokerName, String queueName); String createBeanName(String brokerName); }
@Test public void createBeanName() { assertThat(underTest.createBeanName(BROKER_NAME), is(equalTo(QUEUE_BROWSER_SERVICE_BEAN_NAME_PREFIX + BROKER_NAME))); }
ResendScheduledExecutorsResource { @ApiOperation("Synchronously execute the resend job for the given broker") @POST @Path("/execute") public void execute( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName) { getExecutor(brokerName).execute(); } ResendScheduledExecutorsResource(Map<String, ResendScheduledExecutorService> resendScheduledExecutors); @ApiOperation("Start the resend executor for the given broker") @POST @Path("/start") void start( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Synchronously execute the resend job for the given broker") @POST @Path("/execute") void execute( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Pause the resend executor for the given broker") @PUT @Path("/pause") void pause( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); }
@Test(expected = BadRequestException.class) public void executeThrowsABadRequestExceptionIfBrokerIsUnknown() { underTest.execute("unknown-broker"); } @Test public void executeResendScheduledExecutorService() { underTest.execute("internal-broker"); verify(resendScheduledExecutorService).execute(); }
QueueBrowserScheduledExecutorServiceBeanDefinitionFactory { public AbstractBeanDefinition create(ScheduledExecutorService executorService, String queueBrowserServiceBeanName, long initialDelay, long executionFrequency, TimeUnit timeUnit) { return genericBeanDefinition(QueueBrowserScheduledExecutorService.class) .addConstructorArgValue(executorService) .addConstructorArgReference(queueBrowserServiceBeanName) .addConstructorArgValue(initialDelay) .addConstructorArgValue(executionFrequency) .addConstructorArgValue(timeUnit) .setInitMethodName("start") .setDestroyMethodName("shutdown") .getBeanDefinition(); } AbstractBeanDefinition create(ScheduledExecutorService executorService, String queueBrowserServiceBeanName, long initialDelay, long executionFrequency, TimeUnit timeUnit); String createBeanName(String brokerName); static final String QUEUE_BROWSER_SCHEDULED_EXECUTOR_SERVICE_BEAN_NAME_PREFIX; }
@Test public void createResendScheduledExecutorServiceBeanDefinition(){ AbstractBeanDefinition abstractBeanDefinition = underTest.create( executorService, "queueBrowserService", 0, 10, SECONDS); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(QueueBrowserScheduledExecutorService.class)); ConstructorArgumentValues constructorArgumentValues = abstractBeanDefinition.getConstructorArgumentValues(); assertThat(constructorArgumentValues.getIndexedArgumentValues().size(), is(5)); assertThat(constructorArgumentValues.getArgumentValue(0, ExecutorService.class).getValue(), is(executorService)); assertThat(constructorArgumentValues.getArgumentValue(1, QueueBrowserService.class).getValue(), is(equalTo(new RuntimeBeanReference("queueBrowserService")))); assertThat(constructorArgumentValues.getArgumentValue(2, Long.class).getValue(), is(0L)); assertThat(constructorArgumentValues.getArgumentValue(3, Long.class).getValue(), is(10L)); assertThat(constructorArgumentValues.getArgumentValue(4, TimeUnit.class).getValue(), is(SECONDS)); }
QueueBrowserScheduledExecutorServiceBeanDefinitionFactory { public String createBeanName(String brokerName) { return QUEUE_BROWSER_SCHEDULED_EXECUTOR_SERVICE_BEAN_NAME_PREFIX + brokerName; } AbstractBeanDefinition create(ScheduledExecutorService executorService, String queueBrowserServiceBeanName, long initialDelay, long executionFrequency, TimeUnit timeUnit); String createBeanName(String brokerName); static final String QUEUE_BROWSER_SCHEDULED_EXECUTOR_SERVICE_BEAN_NAME_PREFIX; }
@Test public void createBeanName() throws Exception { assertThat(underTest.createBeanName(BROKER_NAME), is(equalTo(QUEUE_BROWSER_SCHEDULED_EXECUTOR_SERVICE_BEAN_NAME_PREFIX + BROKER_NAME))); }
MessageConsumerManagerResource { @ApiOperation("Start consuming messages from the DLQ on the given broker") @ApiResponses({ @ApiResponse(code = 204, message = "DLQ consumption started successfully"), @ApiResponse(code = 404, message = "brokerName not found") }) @POST @Path("/start/{brokerName}") public void start( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName) { LOGGER.info("Starting consuming messages of the {} broker", brokerName); getMessageConsumerManager(brokerName).start(); } MessageConsumerManagerResource(MessageConsumerManagerRegistry messageConsumerManagerRegistry); @ApiOperation("Start consuming messages from the DLQ on the given broker") @ApiResponses({ @ApiResponse(code = 204, message = "DLQ consumption started successfully"), @ApiResponse(code = 404, message = "brokerName not found") }) @POST @Path("/start/{brokerName}") void start( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Stop consuming messages from the DLQ on the given broker") @ApiResponses({ @ApiResponse(code = 204, message = "DLQ consumption stopped successfully"), @ApiResponse(code = 404, message = "brokerName not found") }) @POST @Path("/stop/{brokerName}") void stop( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Check the status of DLQ consumption on the given broker") @ApiResponses({ @ApiResponse(code = 200, message = "true - if the listener has been started, false - if the listener has been stopped"), @ApiResponse(code = 404, message = "brokerName not found") }) @GET @Path("/running/{brokerName}") String isRunning( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Read all messages on the DLQ for the given broker. This operation is only supported if the queue on the given broker is in read-only mode") @ApiResponses({ @ApiResponse(code = 204, message = "Queue Browser executed successfully"), @ApiResponse(code = 404, message = "brokerName not found"), @ApiResponse(code = 501, message = "Broker does not support this operation") }) @PUT @Path("/read-messages/{brokerName}") void readMessages( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); }
@Test(expected = NotFoundException.class) public void startThrowsANotFoundExceptionIfBrokerIsUnknown() { underTest.start("unknown-broker"); } @Test public void startDefaultMessageListenerContainer() { underTest.start("internal-broker"); verify(defaultMessageListenerContainer).start(); }
MessageConsumerManagerResource { @ApiOperation("Stop consuming messages from the DLQ on the given broker") @ApiResponses({ @ApiResponse(code = 204, message = "DLQ consumption stopped successfully"), @ApiResponse(code = 404, message = "brokerName not found") }) @POST @Path("/stop/{brokerName}") public void stop( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName) { LOGGER.info("Stopping consuming messages of the {} broker", brokerName); getMessageConsumerManager(brokerName).stop(); } MessageConsumerManagerResource(MessageConsumerManagerRegistry messageConsumerManagerRegistry); @ApiOperation("Start consuming messages from the DLQ on the given broker") @ApiResponses({ @ApiResponse(code = 204, message = "DLQ consumption started successfully"), @ApiResponse(code = 404, message = "brokerName not found") }) @POST @Path("/start/{brokerName}") void start( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Stop consuming messages from the DLQ on the given broker") @ApiResponses({ @ApiResponse(code = 204, message = "DLQ consumption stopped successfully"), @ApiResponse(code = 404, message = "brokerName not found") }) @POST @Path("/stop/{brokerName}") void stop( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Check the status of DLQ consumption on the given broker") @ApiResponses({ @ApiResponse(code = 200, message = "true - if the listener has been started, false - if the listener has been stopped"), @ApiResponse(code = 404, message = "brokerName not found") }) @GET @Path("/running/{brokerName}") String isRunning( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Read all messages on the DLQ for the given broker. This operation is only supported if the queue on the given broker is in read-only mode") @ApiResponses({ @ApiResponse(code = 204, message = "Queue Browser executed successfully"), @ApiResponse(code = 404, message = "brokerName not found"), @ApiResponse(code = 501, message = "Broker does not support this operation") }) @PUT @Path("/read-messages/{brokerName}") void readMessages( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); }
@Test(expected = NotFoundException.class) public void stopThrowsANotFoundExceptionIfBrokerIsUnknown() { underTest.stop("unknown-broker"); } @Test public void stopDefaultMessageListenerContainer() { underTest.stop("internal-broker"); verify(defaultMessageListenerContainer).stop(); }
MessageConsumerManagerResource { @ApiOperation("Read all messages on the DLQ for the given broker. This operation is only supported if the queue on the given broker is in read-only mode") @ApiResponses({ @ApiResponse(code = 204, message = "Queue Browser executed successfully"), @ApiResponse(code = 404, message = "brokerName not found"), @ApiResponse(code = 501, message = "Broker does not support this operation") }) @PUT @Path("/read-messages/{brokerName}") public void readMessages( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName) { final Optional<MessageConsumerManager> messageListenerManager = messageConsumerManagerRegistry.get(brokerName); if (messageListenerManager.isPresent()) { messageListenerManager .filter(QueueBrowserScheduledExecutorService.class::isInstance) .map(QueueBrowserScheduledExecutorService.class::cast) .orElseThrow(() -> new ServerErrorException(Response.Status.NOT_IMPLEMENTED)) .execute(); } else { throw new NotFoundException(); } } MessageConsumerManagerResource(MessageConsumerManagerRegistry messageConsumerManagerRegistry); @ApiOperation("Start consuming messages from the DLQ on the given broker") @ApiResponses({ @ApiResponse(code = 204, message = "DLQ consumption started successfully"), @ApiResponse(code = 404, message = "brokerName not found") }) @POST @Path("/start/{brokerName}") void start( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Stop consuming messages from the DLQ on the given broker") @ApiResponses({ @ApiResponse(code = 204, message = "DLQ consumption stopped successfully"), @ApiResponse(code = 404, message = "brokerName not found") }) @POST @Path("/stop/{brokerName}") void stop( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Check the status of DLQ consumption on the given broker") @ApiResponses({ @ApiResponse(code = 200, message = "true - if the listener has been started, false - if the listener has been stopped"), @ApiResponse(code = 404, message = "brokerName not found") }) @GET @Path("/running/{brokerName}") String isRunning( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Read all messages on the DLQ for the given broker. This operation is only supported if the queue on the given broker is in read-only mode") @ApiResponses({ @ApiResponse(code = 204, message = "Queue Browser executed successfully"), @ApiResponse(code = 404, message = "brokerName not found"), @ApiResponse(code = 501, message = "Broker does not support this operation") }) @PUT @Path("/read-messages/{brokerName}") void readMessages( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); }
@Test(expected = NotFoundException.class) public void readMessagesThrowsANotFoundExceptionIfBrokerIsUnknown() { underTest.readMessages("unknown-broker"); } @Test public void readMessagesThrowsAServerErrorExceptionIfBrokerIsNotReadOnly() { StubRuntimeDelegate.setExpectedStatus(Response.Status.NOT_IMPLEMENTED); expectedException.expect(ServerErrorException.class); expectedException.expectMessage("HTTP 501 Not Implemented"); underTest.readMessages("internal-broker"); } @Test public void readMessagesForAReadOnlyBroker() { underTest.readMessages("readonly-broker"); verify(queueBrowserScheduledExecutorService).execute(); }
ActiveMQConnectionFactoryFactoryBeanDefinitionFactory { public AbstractBeanDefinition create(String brokerName) { return genericBeanDefinition(ActiveMQConnectionFactoryFactory.class) .addConstructorArgValue(brokerName) .addConstructorArgReference("jmsListenerProperties") .getBeanDefinition(); } AbstractBeanDefinition create(String brokerName); String createBeanName(String brokerName); }
@Test public void createABeanDefinitionForActiveMqConnectionFactory() throws Exception { AbstractBeanDefinition abstractBeanDefinition = underTest.create(BROKER_NAME); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(ActiveMQConnectionFactoryFactory.class)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue(), is(BROKER_NAME)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(1, JmsListenerProperties.class, "jmsListenerProperties").getValue(), is(new RuntimeBeanReference("jmsListenerProperties"))); }
ResendScheduledExecutorsResource { @ApiOperation("Pause the resend executor for the given broker") @PUT @Path("/pause") public void pause( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName) { getExecutor(brokerName).pause(); } ResendScheduledExecutorsResource(Map<String, ResendScheduledExecutorService> resendScheduledExecutors); @ApiOperation("Start the resend executor for the given broker") @POST @Path("/start") void start( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Synchronously execute the resend job for the given broker") @POST @Path("/execute") void execute( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); @ApiOperation("Pause the resend executor for the given broker") @PUT @Path("/pause") void pause( @ApiParam(value = "name of the broker as defined in application.yml", required = true) @PathParam("brokerName") String brokerName); }
@Test(expected = BadRequestException.class) public void pauseThrowsABadRequestExceptionIfBrokerIsUnknown() { underTest.pause("unknown-broker"); } @Test public void pauseResendScheduledExecutorService() { underTest.pause("internal-broker"); verify(resendScheduledExecutorService).pause(); }
ActiveMQConnectionFactoryFactoryBeanDefinitionFactory { public String createBeanName(String brokerName) { return FACTORY_BEAN_NAME_PREFIX + brokerName; } AbstractBeanDefinition create(String brokerName); String createBeanName(String brokerName); }
@Test public void createBeanName() throws Exception { assertThat(underTest.createBeanName("foo"), is(equalTo(FACTORY_BEAN_NAME_PREFIX + "foo"))); }
FailedMessageListenerBeanDefinitionFactory { public AbstractBeanDefinition create(String brokerName) { return genericBeanDefinition(FailedMessageListener.class) .addConstructorArgValue(activeMQFailedMessageFactoryFactory.apply(brokerName)) .addConstructorArgReference("failedMessageProcessor") .getBeanDefinition(); } FailedMessageListenerBeanDefinitionFactory(Function<String, ActiveMQFailedMessageFactory> activeMQFailedMessageFactoryFactory); AbstractBeanDefinition create(String brokerName); String createBeanName(String brokerName); static final String FAILED_MESSAGE_LISTENER_BEAN_NAME_PREFIX; }
@Test public void createFailedMessageListenerBeanDefinition() { AbstractBeanDefinition abstractBeanDefinition = underTest.create(BROKER_NAME); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(FailedMessageListener.class)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getIndexedArgumentValues().size(), is(2)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(0, ActiveMQFailedMessageFactory.class).getValue(), is(activeMQFailedMessageFactory)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(1, ActiveMQFailedMessageFactory.class).getValue(), is(equalTo(new RuntimeBeanReference("failedMessageProcessor")))); }
FailedMessageListenerBeanDefinitionFactory { public String createBeanName(String brokerName) { return FAILED_MESSAGE_LISTENER_BEAN_NAME_PREFIX + brokerName; } FailedMessageListenerBeanDefinitionFactory(Function<String, ActiveMQFailedMessageFactory> activeMQFailedMessageFactoryFactory); AbstractBeanDefinition create(String brokerName); String createBeanName(String brokerName); static final String FAILED_MESSAGE_LISTENER_BEAN_NAME_PREFIX; }
@Test public void createBeanName() { assertThat(underTest.createBeanName(BROKER_NAME), is(equalTo(FAILED_MESSAGE_LISTENER_BEAN_NAME_PREFIX + BROKER_NAME))); }
NamedMessageListenerContainerBeanDefinitionFactory { public AbstractBeanDefinition create(String brokerName, String connectionFactoryBeanName, String queueName, String failedMessageListenerBeanName) { LOGGER.debug("Creating NamedMessageListenerContainer BeanDefinition for {}", brokerName); return genericBeanDefinition(NamedMessageListenerContainer.class) .addConstructorArgValue(brokerName) .addPropertyReference("connectionFactory", connectionFactoryBeanName) .addPropertyValue("destinationName", queueName) .addPropertyReference("messageListener", failedMessageListenerBeanName) .getBeanDefinition(); } AbstractBeanDefinition create(String brokerName, String connectionFactoryBeanName, String queueName, String failedMessageListenerBeanName); String createBeanName(String brokerName); static final String NAMED_MESSAGE_LISTENER_CONTAINER_BEAN_NAME_PREFIX; }
@Test public void createBeanDefinitionForDefaultMessageListenerContainer() { AbstractBeanDefinition abstractBeanDefinition = underTest.create( BROKER_NAME, CONNECTION_FACTORY_BEAN_NAME, QUEUE_NAME, FAILED_MESSAGE_LISTENER_BEAN_NAME ); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(NamedMessageListenerContainer.class)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getIndexedArgumentValues().size(), is(1)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue(), is(BROKER_NAME)); MutablePropertyValues propertyValues = abstractBeanDefinition.getPropertyValues(); assertThat(propertyValues.size(), is(3)); assertThat(propertyValues.getPropertyValue("connectionFactory").getValue(), is(equalTo(new RuntimeBeanReference(CONNECTION_FACTORY_BEAN_NAME)))); assertThat(propertyValues.getPropertyValue("destinationName").getValue(), is(QUEUE_NAME)); assertThat(propertyValues.getPropertyValue("messageListener").getValue(), is(equalTo(new RuntimeBeanReference(FAILED_MESSAGE_LISTENER_BEAN_NAME)))); }
NamedMessageListenerContainerBeanDefinitionFactory { public String createBeanName(String brokerName) { return NAMED_MESSAGE_LISTENER_CONTAINER_BEAN_NAME_PREFIX + brokerName; } AbstractBeanDefinition create(String brokerName, String connectionFactoryBeanName, String queueName, String failedMessageListenerBeanName); String createBeanName(String brokerName); static final String NAMED_MESSAGE_LISTENER_CONTAINER_BEAN_NAME_PREFIX; }
@Test public void createBeanName() throws Exception { assertThat(underTest.createBeanName("foo"), is(equalTo(NAMED_MESSAGE_LISTENER_CONTAINER_BEAN_NAME_PREFIX + "foo"))); }
ActiveMQConnectionFactoryFactory { public ConnectionFactory create() { JmsListenerProperties.BrokerProperties brokerConfig = jmsListenerProperties.getBrokerConfigFor(brokerName) .orElseThrow(() -> new RuntimeException("Could not find broker config for broker with name: " + brokerName)); Optional<JmsListenerProperties.BrokerProperties.TlsProperties> tlsConfig = Optional.ofNullable(brokerConfig.getTls()); return tlsConfig.map(tls -> { try { LOGGER.info("Found TLS configuration for broker with name: {}. Creating appropriate ssl connection factory.", brokerName); ActiveMQSslConnectionFactory activeMQSslConnectionFactory = new ActiveMQSslConnectionFactory(brokerConfig.getUrl()); activeMQSslConnectionFactory.setKeyStore(tls.getKeyStoreFilePath()); activeMQSslConnectionFactory.setKeyStorePassword(String.valueOf(tls.getKeyStorePassword())); activeMQSslConnectionFactory.setTrustStore(tls.getTrustStoreFilePath()); activeMQSslConnectionFactory.setTrustStorePassword(String.valueOf(tls.getTrustStorePassword())); return (ConnectionFactory) activeMQSslConnectionFactory; } catch (Exception e) { throw new RuntimeException(e); } }).orElseGet(() -> { LOGGER.info("Creating standard connection factory for broker with name: {}", brokerName); return new ActiveMQConnectionFactory(brokerConfig.getUrl()); }); } ActiveMQConnectionFactoryFactory(String brokerName, JmsListenerProperties jmsListenerProperties); ConnectionFactory create(); }
@Test public void ifNoTlsConffigExistsThenCreateVanillaActiveMQConnectionFactory() throws Exception { JmsListenerProperties.BrokerProperties brokerConfig = new JmsListenerProperties.BrokerProperties(); brokerConfig.setName(BROKER_NAME); brokerConfig.setUrl("tcp: JmsListenerProperties testConfig = new JmsListenerProperties(); testConfig.setBrokers(Collections.singletonList(brokerConfig)); ActiveMQConnectionFactoryFactory underTest = new ActiveMQConnectionFactoryFactory(BROKER_NAME, testConfig); ConnectionFactory connectionFactory = underTest.create(); assertThat(connectionFactory, instanceOf(ActiveMQConnectionFactory.class)); } @Test public void ifTlsOptionsAreDefinedInConfigThenSslConnectionFactoryShouldBeCreated() throws Exception { JmsListenerProperties.BrokerProperties.TlsProperties tlsProperties = new JmsListenerProperties.BrokerProperties.TlsProperties(); String expectedKeystoreFilePath = "keystoreFilePath"; String expectedKeyStorePassword = "keystore-password"; String expectedTrustStoreFilePath = "trustStoreFilePath"; String expectedTrustStorePassword = "trustStorePassword"; tlsProperties.setKeyStoreFilePath(expectedKeystoreFilePath); tlsProperties.setKeyStorePassword(expectedKeyStorePassword.toCharArray()); tlsProperties.setTrustStoreFilePath(expectedTrustStoreFilePath); tlsProperties.setTrustStorePassword(expectedTrustStorePassword.toCharArray()); JmsListenerProperties.BrokerProperties brokerConfig = new JmsListenerProperties.BrokerProperties(); brokerConfig.setName(BROKER_NAME); brokerConfig.setUrl("tcp: brokerConfig.setTls(tlsProperties); JmsListenerProperties testConfig = new JmsListenerProperties(); testConfig.setBrokers(Collections.singletonList(brokerConfig)); ActiveMQConnectionFactoryFactory underTest = new ActiveMQConnectionFactoryFactory(BROKER_NAME, testConfig); ConnectionFactory connectionFactory = underTest.create(); assertThat(connectionFactory, instanceOf(ActiveMQSslConnectionFactory.class)); ActiveMQSslConnectionFactory sslConnectionFactory = (ActiveMQSslConnectionFactory) connectionFactory; assertThat(sslConnectionFactory.getKeyStore(), is(expectedKeystoreFilePath)); assertThat(sslConnectionFactory.getKeyStorePassword(), is(expectedKeyStorePassword)); assertThat(sslConnectionFactory.getTrustStore(), is(expectedTrustStoreFilePath)); assertThat(sslConnectionFactory.getTrustStorePassword(), is(expectedTrustStorePassword)); }
ActiveMQConnectionFactoryBeanDefinitionFactory { public AbstractBeanDefinition create(String nameOfFactoryBean) { return genericBeanDefinition(ActiveMQConnectionFactory.class) .setFactoryMethodOnBean("create", nameOfFactoryBean) .getBeanDefinition(); } AbstractBeanDefinition create(String nameOfFactoryBean); String createBeanName(String brokerName); static final String ACTIVE_MQ_CONNECTION_FACTORY_BEAN_NAME_PREFIX; }
@Test public void createABeanDefinitionForActiveMqConnectionFactory() throws Exception { AbstractBeanDefinition abstractBeanDefinition = underTest.create(NAME_OF_FACTORY_BEAN); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(ActiveMQConnectionFactory.class)); assertThat(abstractBeanDefinition.getFactoryMethodName(), is("create")); assertThat(abstractBeanDefinition.getFactoryBeanName(), is(NAME_OF_FACTORY_BEAN)); }
ActiveMQConnectionFactoryBeanDefinitionFactory { public String createBeanName(String brokerName) { return ACTIVE_MQ_CONNECTION_FACTORY_BEAN_NAME_PREFIX + brokerName; } AbstractBeanDefinition create(String nameOfFactoryBean); String createBeanName(String brokerName); static final String ACTIVE_MQ_CONNECTION_FACTORY_BEAN_NAME_PREFIX; }
@Test public void createBeanName() throws Exception { assertThat(underTest.createBeanName("foo"), is(equalTo(ACTIVE_MQ_CONNECTION_FACTORY_BEAN_NAME_PREFIX + "foo"))); }
MustachePageRenderer { public void render(Page page, OutputStream output) throws IOException { try { final Mustache template = mustacheFactory.compile(page.getTemplate()); try (OutputStreamWriter writer = new OutputStreamWriter(output, UTF_8)) { template.execute(writer, Arrays.asList( page )); } } catch (Throwable e) { throw new RuntimeException("Mustache template error: " + page.getTemplate(), e); } } MustachePageRenderer(MustacheFactory mustacheFactory); void render(Page page, OutputStream output); }
@Test public void testRenderPage() throws Exception { try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { underTest.render(new TestPage(), output); assertThat(output.toString(), containsString("<p>some content</p>")); } }
FailedMessageListPage extends Page { public boolean isPopupRendered() { return popupRendered; } FailedMessageListPage(boolean popupRendered); boolean isPopupRendered(); }
@Test public void createFailedMessageListPage() { FailedMessageListPage underTest = new FailedMessageListPage(true); assertTrue(underTest.isPopupRendered()); assertEquals("list.mustache", underTest.getTemplate()); }
FailedMessageListController { @GET @Consumes(APPLICATION_JSON) @Produces(TEXT_HTML) public FailedMessageListPage getFailedMessages() { return new FailedMessageListPage(popupRendered); } FailedMessageListController(boolean popupRendered); @GET @Consumes(APPLICATION_JSON) @Produces(TEXT_HTML) FailedMessageListPage getFailedMessages(); }
@Test public void getFailedMessageListPage() { final FailedMessageListPage failedMessages = underTest.getFailedMessages(); assertThat(failedMessages.getTemplate(), is(equalTo("list.mustache"))); assertThat(failedMessages.isPopupRendered(), is(true)); }
LabelExtractor { public Set<String> extractLabels(String labels) { return Stream.of(split(labels, ",")) .map(String::trim) .filter(label -> !label.isEmpty()) .collect(toSet()); } Set<String> extractLabels(String labels); }
@Test public void emptyStingReturnsEmptySet() throws Exception { assertThat(underTest.extractLabels(""), is(emptyIterable())); } @Test public void stringContainingWhitespaceReturnsEmptySet() throws Exception { assertThat(underTest.extractLabels(" \t"), is(emptyIterable())); } @Test public void stringContainingOnlyCommasWhitespaceReturnsEmptySet() throws Exception { assertThat(underTest.extractLabels(" ,,\t,"), is(emptyIterable())); } @Test public void leadingAndTrailingWhitespaceIsRemovedFromLabels() { assertThat(underTest.extractLabels(" foo , bar\t"), containsInAnyOrder("foo", "bar")); }
FailedMessageChangeResource { @POST @Path("/labels") public String updateLabelsOnFailedMessages(LabelRequest request) { LOGGER.info("Updating the labels on {} failedMessages", request.getChanges().size()); request.getChanges() .forEach(change -> { LOGGER.info("Setting labels on FailedMessage: {} to '{}'", change.getRecid(), change.getLabels()); labelFailedMessageClient.setLabels( fromString(change.getRecid()), labelExtractor.extractLabels(change.getLabels()) ); }); return "{ 'status': 'success' }"; } FailedMessageChangeResource(LabelFailedMessageClient labelFailedMessageClient, LabelExtractor labelExtractor, DeleteFailedMessageClient deleteFailedMessageClient); @POST @Path("/labels") String updateLabelsOnFailedMessages(LabelRequest request); @POST @Path("/delete") String deleteFailedMessages(DeleteRequest request); }
@Test public void updateLabels() throws Exception { when(labelExtractor.extractLabels("foo, bar")).thenReturn(labels1); when(labelExtractor.extractLabels("black, white")).thenReturn(labels2); String result = underTest.updateLabelsOnFailedMessages( newLabelRequest() .withChange(newChange().withRecid(FAILED_MESSAGE_1_ID).withLabels("foo, bar")) .withChange(newChange().withRecid(FAILED_MESSAGE_2_ID).withLabels("black, white")) .build() ); assertThat(result, is(equalTo("{ 'status': 'success' }"))); verify(labelFailedMessageClient).setLabels(FAILED_MESSAGE_1_ID, labels1); verify(labelFailedMessageClient).setLabels(FAILED_MESSAGE_2_ID, labels2); }
FailedMessageChangeResource { @POST @Path("/delete") public String deleteFailedMessages(DeleteRequest request) { request.getSelected() .forEach(recid -> deleteFailedMessageClient.deleteFailedMessage(fromString(recid))); return "{ 'status': 'success' }"; } FailedMessageChangeResource(LabelFailedMessageClient labelFailedMessageClient, LabelExtractor labelExtractor, DeleteFailedMessageClient deleteFailedMessageClient); @POST @Path("/labels") String updateLabelsOnFailedMessages(LabelRequest request); @POST @Path("/delete") String deleteFailedMessages(DeleteRequest request); }
@Test public void deleteFailedMessages() { String result = underTest.deleteFailedMessages( newDeleteRequest().withSelectedRecords(FAILED_MESSAGE_1_ID, FAILED_MESSAGE_2_ID).build() ); assertThat(result, is(equalTo("{ 'status': 'success' }"))); verify(deleteFailedMessageClient).deleteFailedMessage(FAILED_MESSAGE_1_ID); verify(deleteFailedMessageClient).deleteFailedMessage(FAILED_MESSAGE_2_ID); }
Constants { public static Optional<String> toIsoDateTimeWithMs(Instant instant) { return Optional.ofNullable(instant).map(ISO_DATE_TIME_WITH_MS::format); } private Constants(); static Optional<String> toIsoDateTimeWithMs(Instant instant); static Optional<Instant> toInstantFromIsoDateTime(String instantAsString); }
@Test public void formatNullInstant() { assertEquals(Optional.empty(), Constants.toIsoDateTimeWithMs(null)); } @Test public void formatGivenInstant() { assertEquals(Optional.of("1970-01-01T00:00:00.000Z"), Constants.toIsoDateTimeWithMs(Instant.ofEpochMilli(0))); }
LoginController { @GET public LoginPage getLoginPage(@Context HttpServletRequest request) { Optional<String> errorMessage = authenticationExceptionAdapter .toErrorMessage((AuthenticationException) request.getSession().getAttribute(AUTHENTICATION_EXCEPTION)); return new LoginPage(errorMessage); } LoginController(AuthenticationExceptionAdapter authenticationExceptionAdapter); @GET LoginPage getLoginPage(@Context HttpServletRequest request); }
@Test public void loginPageIsCreatedSuccessfully() throws Exception { when(httpServletRequest.getSession()).thenReturn(httpSession); when(httpSession.getAttribute(AUTHENTICATION_EXCEPTION)).thenReturn(authenticationException); when(authenticationExceptionAdapter.toErrorMessage(authenticationException)).thenReturn(Optional.of("Error Message")); assertThat(underTest.getLoginPage(httpServletRequest), hasErrorMessage("Error Message")); }
AuthenticationExceptionAdapter { public Optional<String> toErrorMessage(AuthenticationException authenticationException) { return Optional.ofNullable(authenticationException) .map(exception -> { String message = exception.getMessage(); LOGGER.debug("Translating error message: {}", message); return "Incorrect username/password"; }); } Optional<String> toErrorMessage(AuthenticationException authenticationException); }
@Test public void nullExceptionReturnsEmptyString() throws Exception { assertThat(underTest.toErrorMessage(null), is(Optional.empty())); } @Test public void anyAuthenticationExceptionReturns() { assertThat(underTest.toErrorMessage(mock(AuthenticationException.class)), is(Optional.of("Incorrect username/password"))); }
SearchFailedMessageRequestAdapter { public SearchFailedMessageRequest adapt(SearchW2UIRequest request) { SearchFailedMessageRequestBuilder searchFailedMessageRequestBuilder = searchMatchingAnyCriteria(); for (Criteria criteria : request.getSearchCriteria()) { criteria.addToSearchRequest(searchFailedMessageRequestBuilder); } return searchFailedMessageRequestBuilder.build(); } SearchFailedMessageRequest adapt(SearchW2UIRequest request); }
@Test public void searchWithMultipleCriteria() throws Exception { when(searchW2UIRequest.getSearchCriteria()).thenReturn(Arrays.asList( new Criteria(Criteria.Field.BROKER, Criteria.Operator.BEGINS, "Lorem"), new Criteria(Criteria.Field.CONTENT, Criteria.Operator.ENDS, "Ipsum"), new Criteria(Criteria.Field.DESTINATION, Criteria.Operator.CONTAINS, "Dolor") )); SearchFailedMessageRequest request = underTest.adapt(searchW2UIRequest); assertThat(request, aSearchRequestMatchingAnyCriteria() .withBroker("Lorem") .withContent("Ipsum") .withDestination("Dolor")); } @Test public void searchWithNoCriteria() throws Exception { when(searchW2UIRequest.getSearchCriteria()).thenReturn(Collections.emptyList()); SearchFailedMessageRequest request = underTest.adapt(searchW2UIRequest); assertThat(request, aSearchRequestMatchingAnyCriteria() .withBroker(equalTo(Optional.empty())) .withContent(equalTo(Optional.empty())) .withDestination(equalTo(Optional.empty()))); }
HistoricStatusPredicate implements Predicate<FailedMessage> { @Override public boolean test(FailedMessage failedMessage) { return failedMessage.getStatusHistoryEvent().getEffectiveDateTime().isBefore(Instant.now()); } @Override boolean test(FailedMessage failedMessage); }
@Test public void effectiveDateTimeInPastReturnsTrue() throws Exception { when(failedMessage.getStatusHistoryEvent()).thenReturn(statusHistoryEvent); when(statusHistoryEvent.getEffectiveDateTime()).thenReturn(Instant.now().minus(1, MILLIS)); assertThat(underTest.test(failedMessage), is(true)); } @Test public void effectiveDateTimeInFutureReturnsFalse() throws Exception { when(failedMessage.getStatusHistoryEvent()).thenReturn(statusHistoryEvent); when(statusHistoryEvent.getEffectiveDateTime()).thenReturn(Instant.now().plus(1, SECONDS)); assertThat(underTest.test(failedMessage), is(false)); }
FailedMessageSenderBeanDefinitionFactory { public AbstractBeanDefinition create(String messageSenderDelegate) { return genericBeanDefinition(FailedMessageSender.class) .addConstructorArgReference(messageSenderDelegate) .addConstructorArgReference("failedMessageService") .addDependsOn("failedMessageDao") .getBeanDefinition(); } AbstractBeanDefinition create(String messageSenderDelegate); String createBeanName(String brokerName); }
@Test public void createFailedMessageSenderBeanDefinition() throws Exception { AbstractBeanDefinition abstractBeanDefinition = underTest.create("messageSenderDelegate"); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(FailedMessageSender.class)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getIndexedArgumentValues().size(), is(2)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(0, MessageSender.class).getValue(), is(equalTo(new RuntimeBeanReference("messageSenderDelegate")))); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(1, FailedMessageService.class).getValue(), is(equalTo(new RuntimeBeanReference("failedMessageService")))); }
FailedMessageSenderBeanDefinitionFactory { public String createBeanName(String brokerName) { return FAILED_MESSAGE_SENDER_BEAN_NAME_PREFIX + brokerName; } AbstractBeanDefinition create(String messageSenderDelegate); String createBeanName(String brokerName); }
@Test public void createBeanName() { assertThat(underTest.createBeanName(BROKER_NAME), is(equalTo(FAILED_MESSAGE_SENDER_BEAN_NAME_PREFIX + BROKER_NAME))); }
ResendScheduledExecutorServiceBeanDefinitionFactory { public AbstractBeanDefinition create(ScheduledExecutorService executorService, String resendFailedMessageServiceBeanName, long initialDelay, long executionFrequency, TimeUnit timeUnit) { return genericBeanDefinition(ResendScheduledExecutorService.class) .addConstructorArgValue(executorService) .addConstructorArgReference(resendFailedMessageServiceBeanName) .addConstructorArgValue(initialDelay) .addConstructorArgValue(executionFrequency) .addConstructorArgValue(timeUnit) .setInitMethodName("start") .setDestroyMethodName("shutdown") .getBeanDefinition(); } AbstractBeanDefinition create(ScheduledExecutorService executorService, String resendFailedMessageServiceBeanName, long initialDelay, long executionFrequency, TimeUnit timeUnit); String createBeanName(String brokerName); }
@Test public void createResendScheduledExecutorServiceBeanDefinition() throws Exception { AbstractBeanDefinition abstractBeanDefinition = underTest.create( executorService, "resendFailedMessageService", 0, 10, SECONDS); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(ResendScheduledExecutorService.class)); ConstructorArgumentValues constructorArgumentValues = abstractBeanDefinition.getConstructorArgumentValues(); assertThat(constructorArgumentValues.getIndexedArgumentValues().size(), is(5)); assertThat(constructorArgumentValues.getArgumentValue(0, ExecutorService.class).getValue(), is(executorService)); assertThat(constructorArgumentValues.getArgumentValue(1, ResendFailedMessageService.class).getValue(), is(equalTo(new RuntimeBeanReference("resendFailedMessageService")))); assertThat(constructorArgumentValues.getArgumentValue(2, Long.class).getValue(), is(0L)); assertThat(constructorArgumentValues.getArgumentValue(3, Long.class).getValue(), is(10L)); assertThat(constructorArgumentValues.getArgumentValue(4, TimeUnit.class).getValue(), is(SECONDS)); }
ResendScheduledExecutorServiceBeanDefinitionFactory { public String createBeanName(String brokerName) { return RESEND_SCHEDULED_EXECUTOR_SERVICE_BEAN_NAME_PREFIX + brokerName; } AbstractBeanDefinition create(ScheduledExecutorService executorService, String resendFailedMessageServiceBeanName, long initialDelay, long executionFrequency, TimeUnit timeUnit); String createBeanName(String brokerName); }
@Test public void createBeanName() throws Exception { assertThat(underTest.createBeanName(BROKER_NAME), is(equalTo(RESEND_SCHEDULED_EXECUTOR_SERVICE_BEAN_NAME_PREFIX + BROKER_NAME))); }
ResendFailedMessageServiceBeanDefinitionFactory { public AbstractBeanDefinition create(String brokerName, String messageSenderBeanName) { return genericBeanDefinition(ResendFailedMessageService.class) .addConstructorArgValue(brokerName) .addConstructorArgReference("failedMessageSearchService") .addConstructorArgReference(messageSenderBeanName) .addConstructorArgValue(historicStatusPredicate) .getBeanDefinition(); } ResendFailedMessageServiceBeanDefinitionFactory(HistoricStatusPredicate historicStatusPredicate); AbstractBeanDefinition create(String brokerName, String messageSenderBeanName); String createBeanName(String brokerName); }
@Test public void createResendFailedMessageServiceBeanDefinition() throws Exception { AbstractBeanDefinition abstractBeanDefinition = underTest.create(BROKER_NAME, "messageSender"); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(ResendFailedMessageService.class)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getIndexedArgumentValues().size(), is(4)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue(), is(BROKER_NAME)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(1, FailedMessageSearchService.class).getValue(), is(equalTo(new RuntimeBeanReference("failedMessageSearchService")))); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(2, MessageSender.class).getValue(), is(equalTo(new RuntimeBeanReference("messageSender")))); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(3, HistoricStatusPredicate.class).getValue(), is(historicStatusPredicate)); }
ResendFailedMessageServiceBeanDefinitionFactory { public String createBeanName(String brokerName) { return RESEND_FAILED_MESSAGE_SERVICE_BEAN_NAME_PREFIX + brokerName; } ResendFailedMessageServiceBeanDefinitionFactory(HistoricStatusPredicate historicStatusPredicate); AbstractBeanDefinition create(String brokerName, String messageSenderBeanName); String createBeanName(String brokerName); }
@Test public void createBeanName() throws Exception { assertThat(underTest.createBeanName(BROKER_NAME), is(equalTo(RESEND_FAILED_MESSAGE_SERVICE_BEAN_NAME_PREFIX + BROKER_NAME))); }
ResendFailedMessageService { public void resendMessages() { LOGGER.debug("Resending FailedMessages to: {}", brokerName); failedMessageSearchService .search(searchMatchingAllCriteria() .withBroker(brokerName) .withStatus(RESENDING) .build()) .stream() .filter(historicStatusPredicate::test) .forEach(messageSender::send); } ResendFailedMessageService(String brokerName, FailedMessageSearchService failedMessageSearchService, MessageSender messageSender, HistoricStatusPredicate historicStatusPredicate); void resendMessages(); String getBrokerName(); }
@Test public void successfullyResendFailedMessages() throws Exception { SearchFailedMessageRequest searchRequest = argThat(new HamcrestArgumentMatcher<>(aSearchRequestMatchingAllCriteria() .withBroker(equalTo(Optional.of(BROKER_NAME))) .withStatusMatcher(contains(RESENDING)))); when(failedMessageSearchService.search(searchRequest)).thenReturn(asList(failedMessage, anotherFailedMessage)); when(historicStatusPredicate.test(failedMessage)).thenReturn(true); when(historicStatusPredicate.test(anotherFailedMessage)).thenReturn(false); underTest.resendMessages(); verify(messageSender).send(failedMessage); verifyNoMoreInteractions(messageSender); }
VaultApiFactory { Vault createVaultAPI(VaultProperties vaultProperties) throws VaultException { return new Vault(buildConfiguration(vaultProperties)); } }
@Test public void throwsExceptionWhenTokenFileNotFound() throws Exception { VaultProperties vaultProperties = createVaultPropertiesWithTokenFileAt(FILE_LOCATION_THAT_DOES_NOT_EXIST); expectedException.expect(VaultException.class); expectedException.expectCause(isA(NoSuchFileException.class)); expectedException.expectMessage(is("java.nio.file.NoSuchFileException: /tmp/file-does-not-exist")); underTest.createVaultAPI(vaultProperties); } @Test public void readsTokenFileWhenItExists() throws Exception { String tokenFileLocation = ensureTokenFileExists(); VaultProperties vaultProperties = createVaultPropertiesWithTokenFileAt(tokenFileLocation); Vault vaultAPI = underTest.createVaultAPI(vaultProperties); assertThat(new File(tokenFileLocation).exists(), is(true)); assertThat(vaultAPI, is(notNullValue())); } @Test public void readsTokenFileWhenItIsAFileUri() throws Exception { String tokenFileLocation = ensureTokenFileExists(); VaultProperties vaultProperties = createVaultPropertiesWithTokenFileAt("file:" + tokenFileLocation); Vault vaultAPI = underTest.createVaultAPI(vaultProperties); assertThat(vaultAPI, is(notNullValue())); } @Test public void readsTokenFileWhenItIsAClasspathFile() throws Exception { VaultProperties vaultProperties = createVaultPropertiesWithTokenFileAt("classpath:test-token-value-file"); Vault vaultAPI = underTest.createVaultAPI(vaultProperties); assertThat(vaultAPI, is(notNullValue())); }
FailedMessageId implements Id { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return id.equals(((FailedMessageId) o).id); } private FailedMessageId(UUID id); static FailedMessageId newFailedMessageId(); static FailedMessageId fromUUID(UUID uuid); @JsonCreator static FailedMessageId fromString(String uuid); @Override UUID getId(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); static final String FAILED_MESSAGE_ID; }
@Test public void equalsTest() { assertFalse(FAILED_MESSAGE_ID.equals(null)); assertFalse(FailedMessageId.fromUUID(A_UUID).equals(A_UUID)); assertFalse(FailedMessageId.newFailedMessageId().equals(FAILED_MESSAGE_ID)); assertTrue(FAILED_MESSAGE_ID.equals(FAILED_MESSAGE_ID)); assertTrue(FailedMessageId.fromUUID(A_UUID).equals(FailedMessageId.fromUUID(A_UUID))); }
SingleValueVaultLookupStrategy implements SensitiveConfigValueLookupStrategy { @Override public boolean matches(String secret) { return isVaultEnabledAndPatternMatches(secret); } SingleValueVaultLookupStrategy(VaultProperties vaultProperties, VaultApiFactory vaultApiFactory); @Override boolean matches(String secret); @Override DecryptedValue retrieveSecret(String secretPath); }
@Test public void matchesWhenConfiguredAndCorrectPath() throws Exception { assertThat(underTest.matches(MATCHING_PATH), is(true)); } @Test public void secretPathDoesNotMatch() throws Exception { assertThat(underTest.matches(NON_MATCHING_PATH), is(false)); }
SingleValueVaultLookupStrategy implements SensitiveConfigValueLookupStrategy { @Override public DecryptedValue retrieveSecret(String secretPath) { Matcher matcher = PATTERN.matcher(secretPath); if (matcher.matches()) { String vaultPath = matcher.group(1); try { String value = vaultAPI().logical().read(vaultPath).getData().get(VALUE_KEY); return new DecryptedValue(value.toCharArray()); } catch (VaultException e) { int httpStatusCode = e.getHttpStatusCode(); switch (httpStatusCode) { case 0: throw new RuntimeException("Unable to connect to vault at:'" + vaultProperties.getAddress() + "', looking up the path '" + secretPath + "'", e); case 404: case 403: throw new RuntimeException("Connected to '" + vaultProperties.getAddress() + "': unable to read secret at path '" + secretPath + "'", e); default: throw new RuntimeException("HTTP status " + httpStatusCode + ". Could not retrieve from Vault '" + vaultProperties.getAddress() + "': the path '" + secretPath + "'", e); } } } else { throw new IllegalStateException("Secret: '" + secretPath + "' did not match pattern did you call matches(secret) first?"); } } SingleValueVaultLookupStrategy(VaultProperties vaultProperties, VaultApiFactory vaultApiFactory); @Override boolean matches(String secret); @Override DecryptedValue retrieveSecret(String secretPath); }
@Test public void unableToRetrieveIfNotAVaultSecretPath() throws Exception { expectedException.expect(IllegalStateException.class); underTest.retrieveSecret(NON_MATCHING_PATH); } @Test public void readsSecretFromVault() throws Exception { DecryptedValue decryptedPassword = underTest.retrieveSecret(MATCHING_PATH); assertThat(decryptedPassword.getClearText(), is(SECRET_VALUE.toCharArray())); } @Test public void wrapsVaultException() throws Exception { doAnswer(invocation -> { throw new VaultException("expected"); }).when(vault).logical(); expectedException.expect(RuntimeException.class); expectedException.expectMessage("Unable to connect to vault at:'null', looking up the path 'VAULT(/some/secret/path)'"); underTest.retrieveSecret(MATCHING_PATH); } @Test public void ensureThatARuntimeExceptionIsThrownWhenVaultKeyIsNotFound() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage(is("Connected to '" + VAULT_PROPERTIES.getAddress() + "': unable to read secret at path '" + MATCHING_PATH + "'")); Logical logical = mock(Logical.class); when(vault.logical()).thenReturn(logical); when(logical.read(SOME_PATH)).thenThrow(new VaultException("Oops", 404)); underTest.retrieveSecret(MATCHING_PATH); }
SensitiveConfigValueLookupRegistry { public DecryptedValue retrieveSecret(String secretPath) { return resolutionStrategies .stream() .filter(service -> service.matches(secretPath)) .findFirst() .map(service -> service.retrieveSecret(secretPath)) .orElseThrow(() -> new IllegalArgumentException("No relevant strategy could be found to resolve vault path for: " + secretPath)); } SensitiveConfigValueLookupRegistry(List<SensitiveConfigValueLookupStrategy> resolutionStrategies); DecryptedValue retrieveSecret(String secretPath); }
@Test public void ensureThatIfNoResolutionStrategyForAVaultKeyCanBeFound_thenThrowAnIllegalArgumentException() throws Exception { SensitiveConfigValueLookupRegistry registry = new SensitiveConfigValueLookupRegistry(emptyList()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(is("No relevant strategy could be found to resolve vault path for: bogus/path")); registry.retrieveSecret("bogus/path"); } @Test public void ensureThatIfResolutionStrategyIsFoundButItReturnsNull_thenThrowAnIllegalArgumentException() throws Exception { List<SensitiveConfigValueLookupStrategy> listOfStrategies = new ArrayList<>(); listOfStrategies.add(new SensitiveConfigValueLookupStrategy() { @Override public DecryptedValue retrieveSecret(String secret) { return null; } @Override public boolean matches(String secret) { return true; } }); SensitiveConfigValueLookupRegistry registry = new SensitiveConfigValueLookupRegistry(listOfStrategies); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(is("No relevant strategy could be found to resolve vault path for: bogus/path")); registry.retrieveSecret("bogus/path"); }
VaultPropertySource extends MapPropertySource { @Override public char[] getProperty(String name) { if (containsProperty(name)) { LOGGER.trace("Attempting to lookup property key = {}", name); return sensitiveConfigValueLookupRegistry.retrieveSecret(super.getProperty(name).toString()).getClearText(); } return null; } VaultPropertySource(Map<String, Object> source, SensitiveConfigValueLookupRegistry registry); @Override char[] getProperty(String name); }
@Test public void ensureThatPropertyKeyThatRequiresResolutionFromVault_isDelegatedToTheUnderlyingRegistry() throws Exception { Map<String, Object> mapOfKeys = new HashMap<>(); String expectedTestKey = "expected.test.key"; String vaultConfigValue = "VAULT(my/secret/path)"; char[] expectedResolvedValue = new char[]{'p', 'a', 's', 's'}; mapOfKeys.put(expectedTestKey, vaultConfigValue); when(registry.retrieveSecret(vaultConfigValue)).thenReturn(new DecryptedValue(expectedResolvedValue)); VaultPropertySource vaultPropertySource = new VaultPropertySource(mapOfKeys, registry); char[] actualResolverKey = vaultPropertySource.getProperty(expectedTestKey); assertTrue(Arrays.equals(actualResolverKey, expectedResolvedValue)); } @Test public void ensureThatIfAttemptingToRetriveAKeyThatIsNotInTheListOfResovableKeys_thenReturnNull() throws Exception { VaultPropertySource vaultPropertySource = new VaultPropertySource(new HashMap<>(), registry); char[] property = vaultPropertySource.getProperty("non-existent-key"); assertNull(property); verifyZeroInteractions(registry); }
FailedMessageId implements Id { @Override public int hashCode() { return id.hashCode(); } private FailedMessageId(UUID id); static FailedMessageId newFailedMessageId(); static FailedMessageId fromUUID(UUID uuid); @JsonCreator static FailedMessageId fromString(String uuid); @Override UUID getId(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); static final String FAILED_MESSAGE_ID; }
@Test public void hashCodeTest() { assertNotEquals(FAILED_MESSAGE_ID.hashCode(), FailedMessageId.newFailedMessageId().hashCode()); assertEquals(FAILED_MESSAGE_ID.getId().hashCode(), FAILED_MESSAGE_ID.hashCode()); }
FailedMessageBuilderFactory { public FailedMessageBuilder create(FailedMessageId failedMessageId) { return failedMessageDao.findById(failedMessageId) .filter(IS_DELETED.negate()) .map(createFailedMessageBuilder()) .orElseThrow(failedMessageNotFound(failedMessageId)) .withUpdateRequestAdapterRegistry(updateRequestAdapterRegistry); } FailedMessageBuilderFactory(UpdateRequestAdapterRegistry updateRequestAdapterRegistry, FailedMessageDao failedMessageDao); FailedMessageBuilder create(FailedMessageId failedMessageId); }
@Test public void failedMessageNotFoundExceptionThrownWhenFailedMessageEmpty() { expectedException.expect(FailedMessageNotFoundException.class); expectedException.expectMessage("Failed Message: " + FAILED_MESSAGE_ID + " not found"); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.empty()); underTest.create(FAILED_MESSAGE_ID); verifyZeroInteractions(failedMessageBuilder); } @Test public void failedMessageNotFoundExceptionThrownIfStatusIsDeleted() { expectedException.expect(FailedMessageNotFoundException.class); expectedException.expectMessage("Failed Message: " + FAILED_MESSAGE_ID + " not found"); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); when(failedMessage.getStatus()).thenReturn(DELETED); underTest.create(FAILED_MESSAGE_ID); verifyZeroInteractions(failedMessageBuilder); } @Test public void successfullyCreateAFailedMessageBuilder() { when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); when(failedMessage.getStatus()).thenReturn(FAILED); when(failedMessageBuilder.withUpdateRequestAdapterRegistry(updateRequestAdapterRegistry)).thenReturn(failedMessageBuilder); assertThat(underTest.create(FAILED_MESSAGE_ID), is(failedMessageBuilder)); verify(failedMessageBuilder).withUpdateRequestAdapterRegistry(updateRequestAdapterRegistry); }
FailedMessageLabelService { public void addLabel(FailedMessageId failedMessageId, String label) { LOGGER.debug("Adding label '{}' to FailedMessage: {}", label, failedMessageId); failedMessageDao.addLabel(failedMessageId, label); } FailedMessageLabelService(FailedMessageDao failedMessageDao); void addLabel(FailedMessageId failedMessageId, String label); void removeLabel(FailedMessageId failedMessageId, String label); void setLabels(FailedMessageId failedMessageId, Set<String> labels); }
@Test public void addLabelDelegatesToDao() throws Exception { underTest.addLabel(FAILED_MESSAGE_ID, LABEL); verify(failedMessageDao).addLabel(FAILED_MESSAGE_ID, LABEL); }
FailedMessageLabelService { public void removeLabel(FailedMessageId failedMessageId, String label) { LOGGER.debug("Removing label '{}' from FailedMessage: {}", label, failedMessageId); failedMessageDao.removeLabel(failedMessageId, label); } FailedMessageLabelService(FailedMessageDao failedMessageDao); void addLabel(FailedMessageId failedMessageId, String label); void removeLabel(FailedMessageId failedMessageId, String label); void setLabels(FailedMessageId failedMessageId, Set<String> labels); }
@Test public void removeLabelDelegatesToDao() throws Exception { underTest.removeLabel(FAILED_MESSAGE_ID, LABEL); verify(failedMessageDao).removeLabel(FAILED_MESSAGE_ID, LABEL); }
FailedMessageLabelService { public void setLabels(FailedMessageId failedMessageId, Set<String> labels) { LOGGER.debug("Replacing all labels on FailedMessage: {}", failedMessageId); failedMessageDao.setLabels(failedMessageId, labels); } FailedMessageLabelService(FailedMessageDao failedMessageDao); void addLabel(FailedMessageId failedMessageId, String label); void removeLabel(FailedMessageId failedMessageId, String label); void setLabels(FailedMessageId failedMessageId, Set<String> labels); }
@Test public void setLabelsDelegatesToDao() { underTest.setLabels(FAILED_MESSAGE_ID, singleton(LABEL)); verify(failedMessageDao).setLabels(FAILED_MESSAGE_ID, singleton(LABEL)); }
FailedMessageService { public void create(FailedMessage failedMessage) { failedMessageDao.insert(failedMessage); } FailedMessageService(FailedMessageDao failedMessageDao, FailedMessageBuilderFactory failedMessageBuilderFactory); void create(FailedMessage failedMessage); void delete(FailedMessageId failedMessageId); void update(FailedMessageId failedMessageId, T updateRequest); void update(FailedMessageId failedMessageId, List<? extends UpdateRequest> updateRequests); }
@Test public void createFailedMessageDelegatesToDao() { underTest.create(failedMessage); Mockito.verify(failedMessageDao).insert(failedMessage); }
FailedMessageService { public <T extends UpdateRequest> void update(FailedMessageId failedMessageId, T updateRequest) { update(failedMessageId, Collections.singletonList(updateRequest)); } FailedMessageService(FailedMessageDao failedMessageDao, FailedMessageBuilderFactory failedMessageBuilderFactory); void create(FailedMessage failedMessage); void delete(FailedMessageId failedMessageId); void update(FailedMessageId failedMessageId, T updateRequest); void update(FailedMessageId failedMessageId, List<? extends UpdateRequest> updateRequests); }
@Test public void noUpdatesArePerformedIfTheUpdateRequestListIsEmpty() { underTest.update(FAILED_MESSAGE_ID, Collections.emptyList()); verifyZeroInteractions(failedMessageDao); verifyZeroInteractions(failedMessageBuilderFactory); }
PredicateOutcomeFailedMessageProcessor implements FailedMessageProcessor { @Override public void process(FailedMessage failedMessage) { if (predicate.test(failedMessage)) { positiveOutcomeFailedMessageProcessor.process(failedMessage); } else { negativeOutcomeFailedMessageProcessor.process(failedMessage); } } PredicateOutcomeFailedMessageProcessor(Predicate<FailedMessage> predicate, FailedMessageProcessor positiveOutcomeFailedMessageProcessor, FailedMessageProcessor negativeOutcomeFailedMessageProcessor); @Override void process(FailedMessage failedMessage); }
@Test public void messageIsADuplicate() { duplicate = true; underTest.process(failedMessage); verify(duplicateFailedMessageProcessor).process(failedMessage); verifyZeroInteractions(newFailedMessageProcessor); } @Test public void messageIsNotADuplicate() { duplicate = false; underTest.process(failedMessage); verify(newFailedMessageProcessor).process(failedMessage); verifyZeroInteractions(duplicateFailedMessageProcessor); }
FailedMessageId implements Id { @Override public String toString() { return id.toString(); } private FailedMessageId(UUID id); static FailedMessageId newFailedMessageId(); static FailedMessageId fromUUID(UUID uuid); @JsonCreator static FailedMessageId fromString(String uuid); @Override UUID getId(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); static final String FAILED_MESSAGE_ID; }
@Test public void toStringTest() { assertEquals(FAILED_MESSAGE_ID.getId().toString(), FAILED_MESSAGE_ID.toString()); }
NewFailedMessageProcessor implements FailedMessageProcessor { @Override public void process(FailedMessage failedMessage) { failedMessageService.create(failedMessage); } NewFailedMessageProcessor(FailedMessageService failedMessageService); @Override void process(FailedMessage failedMessage); }
@Test public void delegatesToFailedMessageService() { underTest.process(failedMessage); }
UniqueFailedMessageIdPredicate implements Predicate<FailedMessage> { @Override public boolean test(FailedMessage failedMessage) { return !failedMessageDao.findById(failedMessage.getFailedMessageId()).isPresent(); } UniqueFailedMessageIdPredicate(FailedMessageDao failedMessageDao); @Override boolean test(FailedMessage failedMessage); }
@Test public void predicateReturnsTrueWhenFailedMesageWithIdDoesNotExist() { when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.empty()); assertThat(underTest.test(failedMessage), is(true)); } @Test public void predicateReturnsFalseWhenFailedMessageWithIdExists() { when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); assertThat(underTest.test(failedMessage), is(false)); }
ExistingFailedMessageProcessor implements FailedMessageProcessor { @Override public void process(FailedMessage failedMessage) { failedMessageDao.update(failedMessage); } ExistingFailedMessageProcessor(FailedMessageDao failedMessageDao); @Override void process(FailedMessage failedMessage); }
@Test public void successfullyProcessExistingFailedMessage() { underTest.process(failedMessage); verify(failedMessageDao).update(failedMessage); }
UniqueJmsMessageIdPredicate implements Predicate<FailedMessage> { @Override public boolean test(FailedMessage failedMessage) { return failedMessageSearchService.search(searchMatchingAllCriteria() .withBroker(failedMessage.getDestination().getBrokerName()) .withJmsMessageId(failedMessage.getJmsMessageId()) .build() ).isEmpty(); } UniqueJmsMessageIdPredicate(FailedMessageSearchService failedMessageSearchService); @Override boolean test(FailedMessage failedMessage); }
@Test public void predicateReturnsTrueIfSearchFindsAResult() { when(destination.getBrokerName()).thenReturn(BROKER_NAME); when(failedMessage.getDestination()).thenReturn(destination); when(failedMessage.getJmsMessageId()).thenReturn(JMS_MESSAGE_ID); when(failedMessageSearchService.search(any(SearchFailedMessageRequest.class))).thenReturn(Collections.emptySet()); assertThat(underTest.test(failedMessage), is(true)); verify(failedMessageSearchService).search(argThat(aSearchRequestMatchingAllCriteria() .withBroker(BROKER_NAME) .withJmsMessageId(JMS_MESSAGE_ID))); } @Test public void predicateReturnsFalseIfSearchFindsAResult() { when(destination.getBrokerName()).thenReturn(BROKER_NAME); when(failedMessage.getDestination()).thenReturn(destination); when(failedMessage.getJmsMessageId()).thenReturn(JMS_MESSAGE_ID); when(failedMessageSearchService.search(any(SearchFailedMessageRequest.class))).thenReturn(singleton(mock(FailedMessage.class))); assertThat(underTest.test(failedMessage), is(false)); verify(failedMessageSearchService).search(argThat(aSearchRequestMatchingAllCriteria() .withBroker(BROKER_NAME) .withJmsMessageId(JMS_MESSAGE_ID))); }
PropertiesConverter implements ObjectConverter<Map<String, Object>, String> { @Override public Map<String, Object> convertToObject(String value) { if (value == null) { return Collections.emptyMap(); } try { return objectMapper.readValue(value, new TypeReference<Map<String, Object>>() {}); } catch (IOException e) { LOGGER.error("Could read the following properties: " + value, e); } return Collections.emptyMap(); } PropertiesConverter(ObjectMapper objectMapper); @Override Map<String, Object> convertToObject(String value); @Override String convertFromObject(Map<String, Object> item); }
@Test public void nullPropertiesReturnsANewHashMap() { assertThat(underTest.convertToObject(null), is(equalTo(new HashMap<>()))); } @Test public void nullValueIsReturnedIfTheJsonCannotBeRead() throws IOException { when(objectMapper.readValue(any(String.class), any(TypeReference.class))).thenThrow(IOException.class); assertThat(new PropertiesConverter(objectMapper).convertToObject("foo"), is(Collections.emptyMap())); }
PropertiesConverter implements ObjectConverter<Map<String, Object>, String> { @Override public String convertFromObject(Map<String, Object> item) { if (item == null) { return null; } try { return objectMapper.writeValueAsString(item); } catch (JsonProcessingException e) { LOGGER.error("Could not convert the following Map: " + item, e); } return null; } PropertiesConverter(ObjectMapper objectMapper); @Override Map<String, Object> convertToObject(String value); @Override String convertFromObject(Map<String, Object> item); }
@Test public void convertingNullMapToStringReturnsNull() { assertThat(underTest.convertFromObject(null), is(nullValue())); } @Test public void nullValueIsReturnedIfTheMapCannotBeParsed() throws Exception { when(objectMapper.writeValueAsString(singletonMap("foo", "bar"))).thenThrow(JsonProcessingException.class); assertThat(new PropertiesConverter(objectMapper).convertFromObject(singletonMap("foo", "bar")), is(nullValue())); }
InstantAsDateTimeCodec implements Codec<Instant> { @Override public void encode(BsonWriter writer, Instant value, EncoderContext encoderContext) { writer.writeDateTime(value.toEpochMilli()); } @Override void encode(BsonWriter writer, Instant value, EncoderContext encoderContext); @Override Instant decode(BsonReader reader, DecoderContext decoderContext); @Override Class<Instant> getEncoderClass(); }
@Test public void encode() { underTest.encode(bsonWriter, AN_INSTANT, encoderContext); verify(bsonWriter).writeDateTime(EPOCH_MILLI); }
StatusHistoryResponse { public StatusHistoryResponse(@JsonProperty("status") FailedMessageStatus status, @JsonProperty("effectiveDateTime") Instant effectiveDateTime) { this.status = status; this.effectiveDateTime = effectiveDateTime; } StatusHistoryResponse(@JsonProperty("status") FailedMessageStatus status, @JsonProperty("effectiveDateTime") Instant effectiveDateTime); FailedMessageStatus getStatus(); Instant getEffectiveDateTime(); @Override String toString(); }
@Test public void statusHistoryResponseTest() { assertThat(underTest, is(statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW))); } @Test public void serialiseAndDeserialiseObject() throws IOException { final String json = OBJECT_MAPPER.writeValueAsString(underTest); assertThat(OBJECT_MAPPER.readValue(json, StatusHistoryResponse.class), is(statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW))); }
CreateFailedMessageRequest { CreateFailedMessageRequest(@JsonProperty("failedMessageId") FailedMessageId failedMessageId, @JsonProperty("brokerName") String brokerName, @JsonProperty("destinationName") String destination, @JsonProperty("sentAt") Instant sentAt, @JsonProperty("failedAt") Instant failedAt, @JsonProperty("content") String content, @JsonProperty("properties") Map<String, Object> properties, @JsonProperty("labels") Set<String> labels) { this.failedMessageId = failedMessageId; this.brokerName = brokerName; this.destination = destination; this.sentAt = sentAt; this.failedAt = failedAt; this.content = content; this.properties = properties; this.labels = labels; } CreateFailedMessageRequest(@JsonProperty("failedMessageId") FailedMessageId failedMessageId, @JsonProperty("brokerName") String brokerName, @JsonProperty("destinationName") String destination, @JsonProperty("sentAt") Instant sentAt, @JsonProperty("failedAt") Instant failedAt, @JsonProperty("content") String content, @JsonProperty("properties") Map<String, Object> properties, @JsonProperty("labels") Set<String> labels); static CreateFailedMessageRequestBuilder newCreateFailedMessageRequest(); FailedMessageId getFailedMessageId(); String getBrokerName(); String getDestinationName(); Instant getSentAt(); Instant getFailedAt(); String getContent(); Map<String, Object> getProperties(); Set<String> getLabels(); }
@Test public void attemptingToSetNullPropertiesCreatesAnEmptyMap() { final CreateFailedMessageRequest createFailedMessageRequest = createFailedMessageRequestBuilder .withProperties(null) .build(); assertThat(createFailedMessageRequest, is(createFailedMessageRequest().withProperties(equalTo(emptyMap())))); } @Test public void attemptingToSetNullLabelsCreatesAnEmptySet() { final CreateFailedMessageRequest createFailedMessageRequest = createFailedMessageRequestBuilder .withLabels(null) .build(); assertThat(createFailedMessageRequest, is(createFailedMessageRequest().withLabels(emptyIterable()))); } @Test public void addProperties() { final CreateFailedMessageRequest createFailedMessageRequest = createFailedMessageRequestBuilder .withProperties(Collections.singletonMap("foo", "bar")) .withProperty("ham", "eggs") .build(); assertThat(createFailedMessageRequest, is(createFailedMessageRequest() .withProperties(allOf(Matchers.hasEntry("foo", "bar"), Matchers.hasEntry("ham", "eggs"))))); } @Test public void addLabels() { final CreateFailedMessageRequest createFailedMessageRequest = createFailedMessageRequestBuilder .withLabels(Collections.singleton("foo")) .withLabel("bar") .build(); assertThat(createFailedMessageRequest, is(createFailedMessageRequest() .withLabels(containsInAnyOrder("foo", "bar")))); }
SearchFailedMessageRequest { public static SearchFailedMessageRequestBuilder searchMatchingAllCriteria() { return new SearchFailedMessageRequestBuilder(AND); } private SearchFailedMessageRequest(@JsonProperty("broker") Optional<String> broker, @JsonProperty("destination") Optional<String> destination, @JsonProperty("statuses") Set<FailedMessageStatus> statuses, @JsonProperty("content") Optional<String> content, @JsonProperty("jmsMessageId") Optional<String> jmsMessageId, @JsonProperty("operator") Operator operator); static SearchFailedMessageRequestBuilder searchMatchingAllCriteria(); static SearchFailedMessageRequestBuilder searchMatchingAnyCriteria(); Optional<String> getBroker(); Optional<String> getDestination(); Set<FailedMessageStatus> getStatuses(); Optional<String> getContent(); Optional<String> getJmsMessageId(); Operator getOperator(); @Override String toString(); }
@Test public void serialiseAndDeserialiseWithOptionalFieldsMissing() throws Exception { String json = OBJECT_MAPPER.writeValueAsString( SearchFailedMessageRequest.searchMatchingAllCriteria() .withStatus(FAILED) .build()); assertThat(OBJECT_MAPPER.readValue(json, SearchFailedMessageRequest.class), is( aSearchRequestMatchingAllCriteria() .withBroker(equalTo(Optional.empty())) .withDestination(equalTo(Optional.empty())) .withStatusMatcher(contains(FAILED)) .withNoJmsMessageId() )); } @Test public void serialiseAndDeserialiseWithAllFieldsPopulated() throws Exception { String json = OBJECT_MAPPER.writeValueAsString( SearchFailedMessageRequest.searchMatchingAllCriteria() .withBroker("broker") .withDestination("queue") .withStatus(FAILED) .withJmsMessageId("ID:localhost.localdomain-46765-1518703251379-5:1:1:1:1") .build()); assertThat(OBJECT_MAPPER.readValue(json, SearchFailedMessageRequest.class), is( aSearchRequestMatchingAllCriteria() .withBroker(equalTo(Optional.of("broker"))) .withDestination(equalTo(Optional.of("queue"))) .withStatusMatcher(contains(FAILED)) .withJmsMessageId("ID:localhost.localdomain-46765-1518703251379-5:1:1:1:1") )); }
RemoveFailedMessageService { public void removeFailedMessages() { try { logger.info("Attempting to remove FailedMessages"); final long count = failedMessageDao.removeFailedMessages(); logger.info("Successfully removed {} messages", count); } catch (Exception e) { logger.error("Could not remove messages", e); } } RemoveFailedMessageService(FailedMessageDao failedMessageDao); RemoveFailedMessageService(FailedMessageDao failedMessageDao, Logger logger); void removeFailedMessages(); }
@Test public void removeDelegatesToTheDao() { when(failedMessageDao.removeFailedMessages()).thenReturn(NUMBER_OF_MESSAGES_REMOVED); underTest.removeFailedMessages(); verify(failedMessageDao).removeFailedMessages(); } @Test public void exceptionsAreSwallowedAndLogged() { when(failedMessageDao.removeFailedMessages()).thenThrow(exception); underTest.removeFailedMessages(); verify(logger).error("Could not remove messages", exception); }
InstantAsDateTimeCodec implements Codec<Instant> { @Override public Instant decode(BsonReader reader, DecoderContext decoderContext) { return Instant.ofEpochMilli(reader.readDateTime()); } @Override void encode(BsonWriter writer, Instant value, EncoderContext encoderContext); @Override Instant decode(BsonReader reader, DecoderContext decoderContext); @Override Class<Instant> getEncoderClass(); }
@Test public void decode() { when(bsonReader.readDateTime()).thenReturn(EPOCH_MILLI); assertThat(underTest.decode(bsonReader, decoderContext), equalTo(AN_INSTANT)); }
ResendFailedMessageResource implements ResendFailedMessageClient { @Override public void resendFailedMessage(FailedMessageId failedMessageId) { failedMessageService.update(failedMessageId, statusUpdateRequest(RESEND)); } ResendFailedMessageResource(FailedMessageService failedMessageService, Clock clock); @Override void resendFailedMessage(FailedMessageId failedMessageId); @Override void resendFailedMessageWithDelay(FailedMessageId failedMessageId, Duration duration); }
@Test public void successfullyMarkAMessageForResending() { underTest.resendFailedMessage(FAILED_MESSAGE_ID); verify(failedMessageService).update(eq(FAILED_MESSAGE_ID), statusUpdateRequest.capture()); assertThat(statusUpdateRequest.getValue(), aStatusUpdateRequest(RESEND)); }
ResendFailedMessageResource implements ResendFailedMessageClient { @Override public void resendFailedMessageWithDelay(FailedMessageId failedMessageId, Duration duration) { failedMessageService.update(failedMessageId, new StatusUpdateRequest(RESEND, Instant.now(clock).plus(duration))); } ResendFailedMessageResource(FailedMessageService failedMessageService, Clock clock); @Override void resendFailedMessage(FailedMessageId failedMessageId); @Override void resendFailedMessageWithDelay(FailedMessageId failedMessageId, Duration duration); }
@Test public void successfullyMarkAMessageForResendingInTheFuture() { underTest.resendFailedMessageWithDelay(FAILED_MESSAGE_ID, Duration.ofSeconds(100)); verify(failedMessageService).update(eq(FAILED_MESSAGE_ID), statusUpdateRequest.capture()); assertThat(statusUpdateRequest.getValue(), aStatusUpdateRequest(RESEND) .withUpdatedDateTime(Matchers.equalTo(NOW.plus(100, SECONDS)))); }