target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testConstructionNullServerUri() throws MqttException { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_SERVER_URI); new PahoAsyncMqttClientService(null, BrokerHelper.getClientId(), MqttClientConnectionType.PUBSUB, null); }
@Override public String getClientId() { return mqttClient.getClientId(); }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } PahoAsyncMqttClientService(final String serverUri, final String clientId, final MqttClientConnectionType connectionType, final MqttClientPersistence clientPersistence); }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } PahoAsyncMqttClientService(final String serverUri, final String clientId, final MqttClientConnectionType connectionType, final MqttClientPersistence clientPersistence); @Override /** * Publishes a {@link Message} to the MQTT Broker. * * @param message the {@link Message} to send * @throws IllegalArgumentException if the {@code message} is null * @throws MessagingException if the {@code message} could not be sent */ void handleMessage(final Message<?> message); @Override String getClientId(); @Override boolean start(); @Override boolean isConnected(); @Override String getConnectedServerUri(); @Override void subscribe(final String topicFilter, final MqttQualityOfService qualityOfService); @Override void unsubscribe(final String topicFilter); @Override void stop(); @Override void close(); @Override void connectionLost(final Throwable throwable); @Override void deliveryComplete(final IMqttDeliveryToken token); @Override void messageArrived(final String topic, final MqttMessage message); MqttConnectOptions getMqttConnectOptions(); @Override void connectComplete(final boolean reconnect, final String serverUri); @Override void onFailure(final IMqttToken token, final Throwable throwable); @Override void onSuccess(final IMqttToken token); }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } PahoAsyncMqttClientService(final String serverUri, final String clientId, final MqttClientConnectionType connectionType, final MqttClientPersistence clientPersistence); @Override /** * Publishes a {@link Message} to the MQTT Broker. * * @param message the {@link Message} to send * @throws IllegalArgumentException if the {@code message} is null * @throws MessagingException if the {@code message} could not be sent */ void handleMessage(final Message<?> message); @Override String getClientId(); @Override boolean start(); @Override boolean isConnected(); @Override String getConnectedServerUri(); @Override void subscribe(final String topicFilter, final MqttQualityOfService qualityOfService); @Override void unsubscribe(final String topicFilter); @Override void stop(); @Override void close(); @Override void connectionLost(final Throwable throwable); @Override void deliveryComplete(final IMqttDeliveryToken token); @Override void messageArrived(final String topic, final MqttMessage message); MqttConnectOptions getMqttConnectOptions(); @Override void connectComplete(final boolean reconnect, final String serverUri); @Override void onFailure(final IMqttToken token, final Throwable throwable); @Override void onSuccess(final IMqttToken token); }
@Test public void testPublishConnectedEventNullSubscribedTopics() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("'subscribedTopics' must be set!"); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectedEvent(CLIENT_ID, SERVER_URI, null, applicationEventPublisher, this); }
public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } }
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } }
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } }
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishConnectedEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectedEvent(CLIENT_ID, SERVER_URI, SUBSCRIBED_TOPICS_EMPTY, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttClientConnectedEvent.class)); }
public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } }
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } }
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } }
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectedEvent(clientId, serverUri, subscribedTopics, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishConnectionFailureEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishConnectionFailureEvent(CLIENT_ID, true, new Exception(), null, this); }
public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishConnectionFailureEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectionFailureEvent(null, true, new Exception(), applicationEventPublisher, this); }
public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishConnectionFailureEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectionFailureEvent(CLIENT_ID, true, new Exception(), applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttClientConnectionFailureEvent.class)); }
public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttClientConnectionFailureEvent(clientId, autoReconnect, throwable, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishConnectionLostEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishConnectionLostEvent(CLIENT_ID, true, null, this); }
public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishConnectionLostEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectionLostEvent(null, true, applicationEventPublisher, this); }
public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishConnectionLostEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishConnectionLostEvent(CLIENT_ID, true, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttClientConnectionLostEvent.class)); }
public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientConnectionLostEvent(clientId, autoReconnect, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishDisconnectedEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishDisconnectedEvent(CLIENT_ID, null, this); }
public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishDisconnectedEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishDisconnectedEvent(null, applicationEventPublisher, this); }
public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testConstructionNullConnectionType() throws MqttException { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("'connectionType' must be set!"); new PahoAsyncMqttClientService(BrokerHelper.getBrokerUri(), BrokerHelper.getClientId(), null, null); }
@Override public String getClientId() { return mqttClient.getClientId(); }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } PahoAsyncMqttClientService(final String serverUri, final String clientId, final MqttClientConnectionType connectionType, final MqttClientPersistence clientPersistence); }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } PahoAsyncMqttClientService(final String serverUri, final String clientId, final MqttClientConnectionType connectionType, final MqttClientPersistence clientPersistence); @Override /** * Publishes a {@link Message} to the MQTT Broker. * * @param message the {@link Message} to send * @throws IllegalArgumentException if the {@code message} is null * @throws MessagingException if the {@code message} could not be sent */ void handleMessage(final Message<?> message); @Override String getClientId(); @Override boolean start(); @Override boolean isConnected(); @Override String getConnectedServerUri(); @Override void subscribe(final String topicFilter, final MqttQualityOfService qualityOfService); @Override void unsubscribe(final String topicFilter); @Override void stop(); @Override void close(); @Override void connectionLost(final Throwable throwable); @Override void deliveryComplete(final IMqttDeliveryToken token); @Override void messageArrived(final String topic, final MqttMessage message); MqttConnectOptions getMqttConnectOptions(); @Override void connectComplete(final boolean reconnect, final String serverUri); @Override void onFailure(final IMqttToken token, final Throwable throwable); @Override void onSuccess(final IMqttToken token); }
PahoAsyncMqttClientService extends AbstractMqttClientService implements MqttClientService, MqttCallbackExtended, IMqttActionListener { @Override public String getClientId() { return mqttClient.getClientId(); } PahoAsyncMqttClientService(final String serverUri, final String clientId, final MqttClientConnectionType connectionType, final MqttClientPersistence clientPersistence); @Override /** * Publishes a {@link Message} to the MQTT Broker. * * @param message the {@link Message} to send * @throws IllegalArgumentException if the {@code message} is null * @throws MessagingException if the {@code message} could not be sent */ void handleMessage(final Message<?> message); @Override String getClientId(); @Override boolean start(); @Override boolean isConnected(); @Override String getConnectedServerUri(); @Override void subscribe(final String topicFilter, final MqttQualityOfService qualityOfService); @Override void unsubscribe(final String topicFilter); @Override void stop(); @Override void close(); @Override void connectionLost(final Throwable throwable); @Override void deliveryComplete(final IMqttDeliveryToken token); @Override void messageArrived(final String topic, final MqttMessage message); MqttConnectOptions getMqttConnectOptions(); @Override void connectComplete(final boolean reconnect, final String serverUri); @Override void onFailure(final IMqttToken token, final Throwable throwable); @Override void onSuccess(final IMqttToken token); }
@Test public void testPublishDisconnectedEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishDisconnectedEvent(CLIENT_ID, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttClientDisconnectedEvent.class)); }
public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttClientDisconnectedEvent(clientId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishMessageDeliveredEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishMessageDeliveredEvent(CLIENT_ID, MESSAGE_ID, null, this); }
public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishMessageDeliveredEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessageDeliveredEvent(null, MESSAGE_ID, applicationEventPublisher, this); }
public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishMessageDeliveredEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessageDeliveredEvent(CLIENT_ID, MESSAGE_ID, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttMessageDeliveredEvent.class)); }
public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher .publishEvent(new MqttMessageDeliveredEvent(clientId, messageIdentifier, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishMessagePublishedEventNullApplicationEventPublisher() { mqttClientEventPublisher.publishMessagePublishedEvent(CLIENT_ID, MESSAGE_ID, CORRELATION_ID, null, this); }
public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishMessagePublishedEventNullClientId() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(EXCEPTION_MESSAGE_CLIENT_ID); ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessagePublishedEvent(null, MESSAGE_ID, CORRELATION_ID, applicationEventPublisher, this); }
public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishMessagePublishedEventNullCorrelationId() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessagePublishedEvent(CLIENT_ID, MESSAGE_ID, null, applicationEventPublisher, this); }
public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublishMessagePublishedEvent() { ApplicationEventPublisher applicationEventPublisher = Mockito .mock(ApplicationEventPublisher.class); mqttClientEventPublisher.publishMessagePublishedEvent(CLIENT_ID, MESSAGE_ID, CORRELATION_ID, applicationEventPublisher, this); Mockito.verify(applicationEventPublisher, Mockito.atLeast(1)) .publishEvent(Mockito.any(MqttMessagePublishedEvent.class)); }
public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
MqttClientEventPublisher { public void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source) { if (applicationEventPublisher != null) { applicationEventPublisher.publishEvent( new MqttMessagePublishedEvent(clientId, messageIdentifier, correlationId, source)); } } void publishConnectedEvent(String clientId, String serverUri, String[] subscribedTopics, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionFailureEvent(String clientId, boolean autoReconnect, Throwable throwable, ApplicationEventPublisher applicationEventPublisher, Object source); void publishConnectionLostEvent(String clientId, boolean autoReconnect, ApplicationEventPublisher applicationEventPublisher, Object source); void publishDisconnectedEvent(String clientId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessageDeliveredEvent(String clientId, int messageIdentifier, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishedEvent(String clientId, int messageIdentifier, String correlationId, ApplicationEventPublisher applicationEventPublisher, Object source); void publishMessagePublishFailureEvent(String clientId, MessagingException exception, ApplicationEventPublisher applicationEventPublisher, Object source); }
@Test public void testPublisherSetInboundMessageChannel() { AbstractMqttClientService clientService = Mockito.mock(AbstractMqttClientService.class, Mockito.withSettings().useConstructor(MqttClientConnectionType.PUBLISHER) .defaultAnswer(Mockito.CALLS_REAL_METHODS)); Assert.assertNull(clientService.inboundMessageChannel); thrown.expect(IllegalStateException.class); thrown.expectMessage( "Client ID null is setup as a PUBLISHER and cannot receive messages from the Broker!"); clientService.setInboundMessageChannel(Mockito.mock(MessageChannel.class)); }
public void setInboundMessageChannel(MessageChannel inboundMessageChannel) { if (MqttClientConnectionType.PUBLISHER == connectionType) { throw new IllegalStateException(String.format( "Client ID %s is setup as a PUBLISHER and cannot receive messages from the Broker!", getClientId())); } Assert.notNull(inboundMessageChannel, "'inboundMessageChannel' must be set!"); this.inboundMessageChannel = inboundMessageChannel; }
AbstractMqttClientService implements MqttClientService { public void setInboundMessageChannel(MessageChannel inboundMessageChannel) { if (MqttClientConnectionType.PUBLISHER == connectionType) { throw new IllegalStateException(String.format( "Client ID %s is setup as a PUBLISHER and cannot receive messages from the Broker!", getClientId())); } Assert.notNull(inboundMessageChannel, "'inboundMessageChannel' must be set!"); this.inboundMessageChannel = inboundMessageChannel; } }
AbstractMqttClientService implements MqttClientService { public void setInboundMessageChannel(MessageChannel inboundMessageChannel) { if (MqttClientConnectionType.PUBLISHER == connectionType) { throw new IllegalStateException(String.format( "Client ID %s is setup as a PUBLISHER and cannot receive messages from the Broker!", getClientId())); } Assert.notNull(inboundMessageChannel, "'inboundMessageChannel' must be set!"); this.inboundMessageChannel = inboundMessageChannel; } protected AbstractMqttClientService(final MqttClientConnectionType connectionType); }
AbstractMqttClientService implements MqttClientService { public void setInboundMessageChannel(MessageChannel inboundMessageChannel) { if (MqttClientConnectionType.PUBLISHER == connectionType) { throw new IllegalStateException(String.format( "Client ID %s is setup as a PUBLISHER and cannot receive messages from the Broker!", getClientId())); } Assert.notNull(inboundMessageChannel, "'inboundMessageChannel' must be set!"); this.inboundMessageChannel = inboundMessageChannel; } protected AbstractMqttClientService(final MqttClientConnectionType connectionType); @Override MqttClientConnectionType getConnectionType(); abstract String getClientId(); @Override boolean isStarted(); MqttClientConfiguration getMqttClientConfiguration(); @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); void setInboundMessageChannel(MessageChannel inboundMessageChannel); void setReconnectDetails(ReconnectService reconnectService, TaskScheduler taskScheduler); @Override List<TopicSubscription> getTopicSubscriptions(); @Override void subscribe(String topicFilter); abstract void subscribe(String topicFilter, MqttQualityOfService qualityOfService); }
AbstractMqttClientService implements MqttClientService { public void setInboundMessageChannel(MessageChannel inboundMessageChannel) { if (MqttClientConnectionType.PUBLISHER == connectionType) { throw new IllegalStateException(String.format( "Client ID %s is setup as a PUBLISHER and cannot receive messages from the Broker!", getClientId())); } Assert.notNull(inboundMessageChannel, "'inboundMessageChannel' must be set!"); this.inboundMessageChannel = inboundMessageChannel; } protected AbstractMqttClientService(final MqttClientConnectionType connectionType); @Override MqttClientConnectionType getConnectionType(); abstract String getClientId(); @Override boolean isStarted(); MqttClientConfiguration getMqttClientConfiguration(); @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); void setInboundMessageChannel(MessageChannel inboundMessageChannel); void setReconnectDetails(ReconnectService reconnectService, TaskScheduler taskScheduler); @Override List<TopicSubscription> getTopicSubscriptions(); @Override void subscribe(String topicFilter); abstract void subscribe(String topicFilter, MqttQualityOfService qualityOfService); }
@Test public void testClone() { TopicSubscription topic = new TopicSubscription(TOPIC_FILTER, MqttQualityOfService.QOS_0); TopicSubscription clone = topic.clone(); Assert.assertEquals(topic.getTopicFilter(), clone.getTopicFilter()); Assert.assertEquals(topic.getQualityOfService(), clone.getQualityOfService()); Assert.assertThat(topic.isSubscribed(), Is.is(CoreMatchers.equalTo(clone.isSubscribed()))); topic.setSubscribed(true); Assert.assertThat(topic.isSubscribed(), Is.is(CoreMatchers.not(clone.isSubscribed()))); clone = topic.clone(); Assert.assertEquals(topic.getTopicFilter(), clone.getTopicFilter()); Assert.assertEquals(topic.getQualityOfService(), clone.getQualityOfService()); Assert.assertThat(topic.isSubscribed(), Is.is(CoreMatchers.equalTo(clone.isSubscribed()))); }
@Override public TopicSubscription clone() { TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService); record.setSubscribed(this.subscribed); return record; }
TopicSubscription { @Override public TopicSubscription clone() { TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService); record.setSubscribed(this.subscribed); return record; } }
TopicSubscription { @Override public TopicSubscription clone() { TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService); record.setSubscribed(this.subscribed); return record; } TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService); }
TopicSubscription { @Override public TopicSubscription clone() { TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService); record.setSubscribed(this.subscribed); return record; } TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService); String getTopicFilter(); MqttQualityOfService getQualityOfService(); boolean isSubscribed(); void setSubscribed(boolean subscribed); @Override TopicSubscription clone(); }
TopicSubscription { @Override public TopicSubscription clone() { TopicSubscription record = new TopicSubscription(this.topicFilter, this.qualityOfService); record.setSubscribed(this.subscribed); return record; } TopicSubscription(final String topicFilter, final MqttQualityOfService qualityOfService); String getTopicFilter(); MqttQualityOfService getQualityOfService(); boolean isSubscribed(); void setSubscribed(boolean subscribed); @Override TopicSubscription clone(); }
@Test public void testDefaultQualityOfServiceNull() { MqttClientConfiguration configuration = new MqttClientConfiguration(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("'defaultQualityOfService' must be set!"); configuration.setDefaultQualityOfService(null); }
public void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService) { Assert.notNull(defaultQualityOfService, "'defaultQualityOfService' must be set!"); this.defaultQualityOfService = defaultQualityOfService; }
MqttClientConfiguration { public void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService) { Assert.notNull(defaultQualityOfService, "'defaultQualityOfService' must be set!"); this.defaultQualityOfService = defaultQualityOfService; } }
MqttClientConfiguration { public void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService) { Assert.notNull(defaultQualityOfService, "'defaultQualityOfService' must be set!"); this.defaultQualityOfService = defaultQualityOfService; } MqttClientConfiguration(); }
MqttClientConfiguration { public void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService) { Assert.notNull(defaultQualityOfService, "'defaultQualityOfService' must be set!"); this.defaultQualityOfService = defaultQualityOfService; } MqttClientConfiguration(); MqttQualityOfService getDefaultQualityOfService(); void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService); long getSubscribeWaitMilliseconds(); void setSubscribeWaitMilliseconds(long subscribeWaitMilliseconds); long getTopicUnsubscribeWaitTimeoutMilliseconds(); void setTopicUnsubscribeWaitTimeoutMilliseconds( long topicUnsubscribeWaitTimeoutMilliseconds); long getDisconnectWaitMilliseconds(); void setDisconnectWaitMilliseconds(long disconnectWaitMilliseconds); MqttClientConnectionStatusPublisher getMqttClientConnectionStatusPublisher(); void setMqttClientConnectionStatusPublisher( MqttClientConnectionStatusPublisher mqttClientConnectionStatusPublisher); }
MqttClientConfiguration { public void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService) { Assert.notNull(defaultQualityOfService, "'defaultQualityOfService' must be set!"); this.defaultQualityOfService = defaultQualityOfService; } MqttClientConfiguration(); MqttQualityOfService getDefaultQualityOfService(); void setDefaultQualityOfService(MqttQualityOfService defaultQualityOfService); long getSubscribeWaitMilliseconds(); void setSubscribeWaitMilliseconds(long subscribeWaitMilliseconds); long getTopicUnsubscribeWaitTimeoutMilliseconds(); void setTopicUnsubscribeWaitTimeoutMilliseconds( long topicUnsubscribeWaitTimeoutMilliseconds); long getDisconnectWaitMilliseconds(); void setDisconnectWaitMilliseconds(long disconnectWaitMilliseconds); MqttClientConnectionStatusPublisher getMqttClientConnectionStatusPublisher(); void setMqttClientConnectionStatusPublisher( MqttClientConnectionStatusPublisher mqttClientConnectionStatusPublisher); }
@Test public void test() { final Message<String> message = MessageBuilder.withPayload(PAYLOAD).build(); final MessagingException exception = new MessagingException(message, String.format( "Client ID '%s' could not publish this message because either the topic or payload isn't set, or the payload could not be converted.", CLIENT_ID)); final MqttMessagePublishFailureEvent event = new MqttMessagePublishFailureEvent(CLIENT_ID, exception, this); Assert.assertEquals(PAYLOAD, event.getException().getFailedMessage().getPayload()); }
public MessagingException getException() { return exception; }
MqttMessagePublishFailureEvent extends MqttMessageStatusEvent { public MessagingException getException() { return exception; } }
MqttMessagePublishFailureEvent extends MqttMessageStatusEvent { public MessagingException getException() { return exception; } MqttMessagePublishFailureEvent(final String clientId, final MessagingException exception, final Object source); }
MqttMessagePublishFailureEvent extends MqttMessageStatusEvent { public MessagingException getException() { return exception; } MqttMessagePublishFailureEvent(final String clientId, final MessagingException exception, final Object source); MessagingException getException(); }
MqttMessagePublishFailureEvent extends MqttMessageStatusEvent { public MessagingException getException() { return exception; } MqttMessagePublishFailureEvent(final String clientId, final MessagingException exception, final Object source); MessagingException getException(); }
@Test public void test() { MqttMessageDeliveredEvent event = new MqttMessageDeliveredEvent(CLIENT_ID, MESSAGE_ID, this); Assert.assertEquals(MESSAGE_ID, event.getMessageIdentifier()); }
public int getMessageIdentifier() { return messageIdentifier; }
MqttMessageDeliveredEvent extends MqttMessageStatusEvent { public int getMessageIdentifier() { return messageIdentifier; } }
MqttMessageDeliveredEvent extends MqttMessageStatusEvent { public int getMessageIdentifier() { return messageIdentifier; } MqttMessageDeliveredEvent(String clientId, int messageIdentifier, Object source); }
MqttMessageDeliveredEvent extends MqttMessageStatusEvent { public int getMessageIdentifier() { return messageIdentifier; } MqttMessageDeliveredEvent(String clientId, int messageIdentifier, Object source); int getMessageIdentifier(); }
MqttMessageDeliveredEvent extends MqttMessageStatusEvent { public int getMessageIdentifier() { return messageIdentifier; } MqttMessageDeliveredEvent(String clientId, int messageIdentifier, Object source); int getMessageIdentifier(); }
@Test public void test() { MqttStatusEvent event = new MqttStatusEvent(CLIENT_ID, this); Assert.assertEquals(CLIENT_ID, event.getClientId()); }
public String getClientId() { return clientId; }
MqttStatusEvent extends ApplicationEvent { public String getClientId() { return clientId; } }
MqttStatusEvent extends ApplicationEvent { public String getClientId() { return clientId; } MqttStatusEvent(String clientId, Object source); }
MqttStatusEvent extends ApplicationEvent { public String getClientId() { return clientId; } MqttStatusEvent(String clientId, Object source); String getClientId(); }
MqttStatusEvent extends ApplicationEvent { public String getClientId() { return clientId; } MqttStatusEvent(String clientId, Object source); String getClientId(); }
@Test public void test() { MqttClientConnectionLostEvent event = new MqttClientConnectionLostEvent(CLIENT_ID, true, this); Assert.assertTrue(event.isAutoReconnect()); event = new MqttClientConnectionLostEvent(CLIENT_ID, false, this); Assert.assertFalse(event.isAutoReconnect()); }
public boolean isAutoReconnect() { return autoReconnect; }
MqttClientConnectionLostEvent extends MqttConnectionStatusEvent { public boolean isAutoReconnect() { return autoReconnect; } }
MqttClientConnectionLostEvent extends MqttConnectionStatusEvent { public boolean isAutoReconnect() { return autoReconnect; } MqttClientConnectionLostEvent(String clientId, boolean autoReconnect, Object source); }
MqttClientConnectionLostEvent extends MqttConnectionStatusEvent { public boolean isAutoReconnect() { return autoReconnect; } MqttClientConnectionLostEvent(String clientId, boolean autoReconnect, Object source); boolean isAutoReconnect(); }
MqttClientConnectionLostEvent extends MqttConnectionStatusEvent { public boolean isAutoReconnect() { return autoReconnect; } MqttClientConnectionLostEvent(String clientId, boolean autoReconnect, Object source); boolean isAutoReconnect(); }
@Test public void testFindMatch() { Assert.assertNotNull( TopicSubscriptionHelper.findByTopicFilter(TOPIC_FILTER_1, topicSubscriptions)); }
public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
@Test public void testFindNoMatchNoTopicFilter() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter("test", topicSubscriptions)); }
public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
@Test public void testFindNoMatchWrongCase() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter(TOPIC_FILTER_1.toUpperCase(), topicSubscriptions)); }
public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
@Test public void testFindNullTopicFilter() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter(null, topicSubscriptions)); }
public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
@Test public void testFindEmptyTopicSubscriptions() { Assert.assertNull(TopicSubscriptionHelper.findByTopicFilter(TOPIC_FILTER_1.toUpperCase(), new ArrayList<TopicSubscription>())); }
public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
TopicSubscriptionHelper { public static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions) { TopicSubscription record = null; if (StringUtils.hasText(topicFilter) && !CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.getTopicFilter().equals(topicFilter)) { record = topicSubscription; break; } } } return record; } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
@Test public void testGetSubscribedEmptyTopicSubscriptions() { Assert.assertArrayEquals(new String[0], TopicSubscriptionHelper.getSubscribedTopicFilters(new ArrayList<TopicSubscription>())); }
public static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions) { List<String> records = new ArrayList<String>(); if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.isSubscribed()) { records.add(topicSubscription.getTopicFilter()); } } } return records.toArray(new String[records.size()]); }
TopicSubscriptionHelper { public static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions) { List<String> records = new ArrayList<String>(); if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.isSubscribed()) { records.add(topicSubscription.getTopicFilter()); } } } return records.toArray(new String[records.size()]); } }
TopicSubscriptionHelper { public static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions) { List<String> records = new ArrayList<String>(); if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.isSubscribed()) { records.add(topicSubscription.getTopicFilter()); } } } return records.toArray(new String[records.size()]); } }
TopicSubscriptionHelper { public static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions) { List<String> records = new ArrayList<String>(); if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.isSubscribed()) { records.add(topicSubscription.getTopicFilter()); } } } return records.toArray(new String[records.size()]); } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
TopicSubscriptionHelper { public static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions) { List<String> records = new ArrayList<String>(); if (!CollectionUtils.isEmpty(topicSubscriptions)) { for (TopicSubscription topicSubscription : topicSubscriptions) { if (topicSubscription.isSubscribed()) { records.add(topicSubscription.getTopicFilter()); } } } return records.toArray(new String[records.size()]); } static TopicSubscription findByTopicFilter(final String topicFilter, List<TopicSubscription> topicSubscriptions); static String[] getSubscribedTopicFilters(List<TopicSubscription> topicSubscriptions); static void markUnsubscribed(List<TopicSubscription> topicSubscriptions); }
@Test public void testNonString() { final Object in = new Object(); final Object out = new JuelTransform().transform(in, new MappingContext()); assertEquals(in, out); }
@Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } }
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } }
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } JuelTransform(); }
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
@Test public void testMap() { assertEquals(singletonMap(Arrays.asList(8_000_000_000L)), singletonMap(FixDoubles.fix(Arrays.asList(8_000_000_000.0)))); }
static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
@Test public void test() throws IOException { final LogConfig config = new MappingContext() .withParser(new SnakeyamlParser()) .fromStream(LogConfigTest.class.getClassLoader().getResourceAsStream("sample-inline.yaml")) .map(LogConfig.class); assertNotNull(config.getLogger()); assertEquals("org.myproject.MyLogger", config.getLogger().getName()); }
public Logger getLogger() { return logger; }
LogConfig { public Logger getLogger() { return logger; } }
LogConfig { public Logger getLogger() { return logger; } }
LogConfig { public Logger getLogger() { return logger; } Logger getLogger(); }
LogConfig { public Logger getLogger() { return logger; } Logger getLogger(); }
@Test public void testPlainString() { final Object in = "Hello"; final Object out = new JuelTransform().transform(in, new MappingContext()); assertEquals(in, out); }
@Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } }
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } }
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } JuelTransform(); }
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
JuelTransform implements DomTransform { @Override public Object transform(Object dom, MappingContext context) { if (dom instanceof String) { final String str = (String) dom; if (str.contains("${")) { final boolean assigned = session.setLocalContext(context); try { final ValueExpression expr = factory.createValueExpression(elContext, str, Object.class); return expr.getValue(elContext); } finally { if (assigned) session.clearLocalContext(); } } else { return dom; } } else { return dom; } } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
@Test(expected=RuntimeException.class) public void testConfiguratorException() { new JuelTransform().configure(t -> { throw new Exception(); }); }
public void configure(Configurator c) { Exceptions.wrap(() -> c.apply(this), RuntimeException::new); }
JuelTransform implements DomTransform { public void configure(Configurator c) { Exceptions.wrap(() -> c.apply(this), RuntimeException::new); } }
JuelTransform implements DomTransform { public void configure(Configurator c) { Exceptions.wrap(() -> c.apply(this), RuntimeException::new); } JuelTransform(); }
JuelTransform implements DomTransform { public void configure(Configurator c) { Exceptions.wrap(() -> c.apply(this), RuntimeException::new); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
JuelTransform implements DomTransform { public void configure(Configurator c) { Exceptions.wrap(() -> c.apply(this), RuntimeException::new); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
@Test public void testGetEnvExisting() { final String value = JuelTransform.getEnv("HOME", null); assertNotNull(value); }
public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } JuelTransform(); }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
@Test public void testGetEnvNonExistent() { final String defaultValue = "someDefaultValue"; final String value = JuelTransform.getEnv("GIBB_BB_BBERISH", defaultValue); assertSame(defaultValue, value); }
public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } JuelTransform(); }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
JuelTransform implements DomTransform { public static String getEnv(String key, String defaultValue) { final String existingValue = nullCoerce(System.getenv(key)); return ifAbsent(existingValue, give(defaultValue)); } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
@Test public void testNullCoerce() { assertEquals("nonNullString", JuelTransform.nullCoerce("nonNullString")); assertNull(JuelTransform.nullCoerce(null)); assertNull(JuelTransform.nullCoerce("")); }
static String nullCoerce(String str) { return str != null && ! str.isEmpty() ? str : null; }
JuelTransform implements DomTransform { static String nullCoerce(String str) { return str != null && ! str.isEmpty() ? str : null; } }
JuelTransform implements DomTransform { static String nullCoerce(String str) { return str != null && ! str.isEmpty() ? str : null; } JuelTransform(); }
JuelTransform implements DomTransform { static String nullCoerce(String str) { return str != null && ! str.isEmpty() ? str : null; } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
JuelTransform implements DomTransform { static String nullCoerce(String str) { return str != null && ! str.isEmpty() ? str : null; } JuelTransform(); void configure(Configurator c); static String getEnv(String key, String defaultValue); JuelTransform withFunction(String name, Method method); JuelTransform withFunction(String namespace, String name, Method method); JuelTransform withVariable(String name, Object val); @Override Object transform(Object dom, MappingContext context); }
@Test public void testDouble() { assertEquals(123.4, FixDoubles.fix(123.4)); }
static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
@Test public void testInt() { assertEquals(123, FixDoubles.fix(123.0)); }
static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
@Test public void testLong() { assertEquals(8_000_000_000L, FixDoubles.fix(8_000_000_000.0)); }
static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
@Test public void testList() { assertEquals(Arrays.asList(8_000_000_000L), FixDoubles.fix(Arrays.asList(8_000_000_000.0))); }
static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
FixDoubles { static Object fix(Object orig) { if (orig instanceof List) { final List<?> list = MappingContext.cast(orig); final List<Object> copy = new ArrayList<>(list.size()); for (Object obj : list) { copy.add(fix(obj)); } return copy; } else if (orig instanceof Map) { final Map<?, ?> map = MappingContext.cast(orig); final Map<Object, Object> copy = new LinkedHashMap<>(map.size()); for (Map.Entry<?, ?> entry : map.entrySet()) { copy.put(entry.getKey(), fix(entry.getValue())); } return copy; } else if (orig instanceof Double) { final Double d = (Double) orig; if (d.intValue() == d) { return d.intValue(); } else if (d.longValue() == d) { return d.longValue(); } else { return d; } } else { return orig; } } private FixDoubles(); }
@Test public void shouldSendMessage() { ChannelMapping channelMapping = mock(ChannelMapping.class); MessageProducerImplementation implementation = mock(MessageProducerImplementation.class); MessageProducerImpl mp = new MessageProducerImpl(new MessageInterceptor[0], channelMapping, implementation); String transformedDestination = "TransformedDestination"; String messageID = "1"; doAnswer((Answer<Void>) invocation -> { ((Runnable)invocation.getArgument(0)).run(); return null; }).when(implementation).withContext(any(Runnable.class)); when(channelMapping.transform("Destination")).thenReturn(transformedDestination); when(implementation.generateMessageId()).thenReturn(messageID); mp.send("Destination", MessageBuilder.withPayload("x").build()); ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class); verify(implementation).send(messageArgumentCaptor.capture()); Message sendMessage = messageArgumentCaptor.getValue(); assertEquals(messageID, sendMessage.getRequiredHeader(Message.ID)); assertEquals(transformedDestination, sendMessage.getRequiredHeader(Message.DESTINATION)); assertNotNull(sendMessage.getRequiredHeader(Message.DATE)); }
@Override public void send(String destination, Message message) { prepareMessageHeaders(destination, message); implementation.withContext(() -> send(message)); }
MessageProducerImpl implements MessageProducer { @Override public void send(String destination, Message message) { prepareMessageHeaders(destination, message); implementation.withContext(() -> send(message)); } }
MessageProducerImpl implements MessageProducer { @Override public void send(String destination, Message message) { prepareMessageHeaders(destination, message); implementation.withContext(() -> send(message)); } MessageProducerImpl(MessageInterceptor[] messageInterceptors, ChannelMapping channelMapping, MessageProducerImplementation implementation); }
MessageProducerImpl implements MessageProducer { @Override public void send(String destination, Message message) { prepareMessageHeaders(destination, message); implementation.withContext(() -> send(message)); } MessageProducerImpl(MessageInterceptor[] messageInterceptors, ChannelMapping channelMapping, MessageProducerImplementation implementation); @Override void send(String destination, Message message); }
MessageProducerImpl implements MessageProducer { @Override public void send(String destination, Message message) { prepareMessageHeaders(destination, message); implementation.withContext(() -> send(message)); } MessageProducerImpl(MessageInterceptor[] messageInterceptors, ChannelMapping channelMapping, MessageProducerImplementation implementation); @Override void send(String destination, Message message); }
@Test public void shouldFormatDateNow() { Assert.assertNotNull((HttpDateHeaderFormatUtil.nowAsHttpDateString())); }
public static String nowAsHttpDateString() { return timeAsHttpDateString(ZonedDateTime.now(ZoneId.of("GMT"))); }
HttpDateHeaderFormatUtil { public static String nowAsHttpDateString() { return timeAsHttpDateString(ZonedDateTime.now(ZoneId.of("GMT"))); } }
HttpDateHeaderFormatUtil { public static String nowAsHttpDateString() { return timeAsHttpDateString(ZonedDateTime.now(ZoneId.of("GMT"))); } }
HttpDateHeaderFormatUtil { public static String nowAsHttpDateString() { return timeAsHttpDateString(ZonedDateTime.now(ZoneId.of("GMT"))); } static String nowAsHttpDateString(); static String timeAsHttpDateString(ZonedDateTime gmtTime); }
HttpDateHeaderFormatUtil { public static String nowAsHttpDateString() { return timeAsHttpDateString(ZonedDateTime.now(ZoneId.of("GMT"))); } static String nowAsHttpDateString(); static String timeAsHttpDateString(ZonedDateTime gmtTime); }
@Test public void shouldFormatDate() { String expected = "Tue, 15 Nov 1994 08:12:31 GMT"; ZonedDateTime time = ZonedDateTime.parse(expected, DateTimeFormatter.RFC_1123_DATE_TIME); assertEquals(expected, HttpDateHeaderFormatUtil.timeAsHttpDateString(time)); }
public static String timeAsHttpDateString(ZonedDateTime gmtTime) { return gmtTime.format(DateTimeFormatter.RFC_1123_DATE_TIME); }
HttpDateHeaderFormatUtil { public static String timeAsHttpDateString(ZonedDateTime gmtTime) { return gmtTime.format(DateTimeFormatter.RFC_1123_DATE_TIME); } }
HttpDateHeaderFormatUtil { public static String timeAsHttpDateString(ZonedDateTime gmtTime) { return gmtTime.format(DateTimeFormatter.RFC_1123_DATE_TIME); } }
HttpDateHeaderFormatUtil { public static String timeAsHttpDateString(ZonedDateTime gmtTime) { return gmtTime.format(DateTimeFormatter.RFC_1123_DATE_TIME); } static String nowAsHttpDateString(); static String timeAsHttpDateString(ZonedDateTime gmtTime); }
HttpDateHeaderFormatUtil { public static String timeAsHttpDateString(ZonedDateTime gmtTime) { return gmtTime.format(DateTimeFormatter.RFC_1123_DATE_TIME); } static String nowAsHttpDateString(); static String timeAsHttpDateString(ZonedDateTime gmtTime); }
@Test public void shouldDispatchCommand() { String commandDispatcherId = "fooId"; CommandDispatcherTestTarget target = spy(new CommandDispatcherTestTarget()); ChannelMapping channelMapping = mock(ChannelMapping.class); MessageConsumer messageConsumer = mock(MessageConsumer.class); MessageProducer messageProducer = mock(MessageProducer.class); CommandDispatcher dispatcher = new CommandDispatcher(commandDispatcherId, defineCommandHandlers(target), messageConsumer, messageProducer); String customerId = "customer0"; String resource = "/customers/" + customerId; Command command = new TestCommand(); String replyTo = "replyTo-xxx"; String channel = "myChannel"; Message message = CommandProducerImpl.makeMessage(channel, resource, command, replyTo, singletonMap(Message.ID, "999")); dispatcher.messageHandler(message); verify(target).reserveCredit(any(CommandMessage.class), any(PathVariables.class)); verify(messageProducer).send(any(), any()); verifyNoMoreInteractions(messageProducer, target); }
public void messageHandler(Message message) { logger.trace("Received message {} {}", commandDispatcherId, message); Optional<CommandHandler> possibleMethod = commandHandlers.findTargetMethod(message); if (!possibleMethod.isPresent()) { throw new RuntimeException("No method for " + message); } CommandHandler m = possibleMethod.get(); Object param = convertPayload(m, message.getPayload()); Map<String, String> correlationHeaders = correlationHeaders(message.getHeaders()); Map<String, String> pathVars = getPathVars(message, m); Optional<String> defaultReplyChannel = message.getHeader(CommandMessageHeaders.REPLY_TO); List<Message> replies; try { CommandMessage cm = new CommandMessage(message.getId(), param, correlationHeaders, message); replies = invoke(m, cm, pathVars); logger.trace("Generated replies {} {} {}", commandDispatcherId, message, replies); } catch (Exception e) { logger.error("Generated error {} {} {}", commandDispatcherId, message, e.getClass().getName()); logger.error("Generated error", e); handleException(message, param, m, e, pathVars, defaultReplyChannel); return; } if (replies != null) { sendReplies(correlationHeaders, replies, defaultReplyChannel); } else { logger.trace("Null replies - not publishling"); } }
CommandDispatcher { public void messageHandler(Message message) { logger.trace("Received message {} {}", commandDispatcherId, message); Optional<CommandHandler> possibleMethod = commandHandlers.findTargetMethod(message); if (!possibleMethod.isPresent()) { throw new RuntimeException("No method for " + message); } CommandHandler m = possibleMethod.get(); Object param = convertPayload(m, message.getPayload()); Map<String, String> correlationHeaders = correlationHeaders(message.getHeaders()); Map<String, String> pathVars = getPathVars(message, m); Optional<String> defaultReplyChannel = message.getHeader(CommandMessageHeaders.REPLY_TO); List<Message> replies; try { CommandMessage cm = new CommandMessage(message.getId(), param, correlationHeaders, message); replies = invoke(m, cm, pathVars); logger.trace("Generated replies {} {} {}", commandDispatcherId, message, replies); } catch (Exception e) { logger.error("Generated error {} {} {}", commandDispatcherId, message, e.getClass().getName()); logger.error("Generated error", e); handleException(message, param, m, e, pathVars, defaultReplyChannel); return; } if (replies != null) { sendReplies(correlationHeaders, replies, defaultReplyChannel); } else { logger.trace("Null replies - not publishling"); } } }
CommandDispatcher { public void messageHandler(Message message) { logger.trace("Received message {} {}", commandDispatcherId, message); Optional<CommandHandler> possibleMethod = commandHandlers.findTargetMethod(message); if (!possibleMethod.isPresent()) { throw new RuntimeException("No method for " + message); } CommandHandler m = possibleMethod.get(); Object param = convertPayload(m, message.getPayload()); Map<String, String> correlationHeaders = correlationHeaders(message.getHeaders()); Map<String, String> pathVars = getPathVars(message, m); Optional<String> defaultReplyChannel = message.getHeader(CommandMessageHeaders.REPLY_TO); List<Message> replies; try { CommandMessage cm = new CommandMessage(message.getId(), param, correlationHeaders, message); replies = invoke(m, cm, pathVars); logger.trace("Generated replies {} {} {}", commandDispatcherId, message, replies); } catch (Exception e) { logger.error("Generated error {} {} {}", commandDispatcherId, message, e.getClass().getName()); logger.error("Generated error", e); handleException(message, param, m, e, pathVars, defaultReplyChannel); return; } if (replies != null) { sendReplies(correlationHeaders, replies, defaultReplyChannel); } else { logger.trace("Null replies - not publishling"); } } CommandDispatcher(String commandDispatcherId, CommandHandlers commandHandlers, MessageConsumer messageConsumer, MessageProducer messageProducer); }
CommandDispatcher { public void messageHandler(Message message) { logger.trace("Received message {} {}", commandDispatcherId, message); Optional<CommandHandler> possibleMethod = commandHandlers.findTargetMethod(message); if (!possibleMethod.isPresent()) { throw new RuntimeException("No method for " + message); } CommandHandler m = possibleMethod.get(); Object param = convertPayload(m, message.getPayload()); Map<String, String> correlationHeaders = correlationHeaders(message.getHeaders()); Map<String, String> pathVars = getPathVars(message, m); Optional<String> defaultReplyChannel = message.getHeader(CommandMessageHeaders.REPLY_TO); List<Message> replies; try { CommandMessage cm = new CommandMessage(message.getId(), param, correlationHeaders, message); replies = invoke(m, cm, pathVars); logger.trace("Generated replies {} {} {}", commandDispatcherId, message, replies); } catch (Exception e) { logger.error("Generated error {} {} {}", commandDispatcherId, message, e.getClass().getName()); logger.error("Generated error", e); handleException(message, param, m, e, pathVars, defaultReplyChannel); return; } if (replies != null) { sendReplies(correlationHeaders, replies, defaultReplyChannel); } else { logger.trace("Null replies - not publishling"); } } CommandDispatcher(String commandDispatcherId, CommandHandlers commandHandlers, MessageConsumer messageConsumer, MessageProducer messageProducer); @PostConstruct void initialize(); void messageHandler(Message message); }
CommandDispatcher { public void messageHandler(Message message) { logger.trace("Received message {} {}", commandDispatcherId, message); Optional<CommandHandler> possibleMethod = commandHandlers.findTargetMethod(message); if (!possibleMethod.isPresent()) { throw new RuntimeException("No method for " + message); } CommandHandler m = possibleMethod.get(); Object param = convertPayload(m, message.getPayload()); Map<String, String> correlationHeaders = correlationHeaders(message.getHeaders()); Map<String, String> pathVars = getPathVars(message, m); Optional<String> defaultReplyChannel = message.getHeader(CommandMessageHeaders.REPLY_TO); List<Message> replies; try { CommandMessage cm = new CommandMessage(message.getId(), param, correlationHeaders, message); replies = invoke(m, cm, pathVars); logger.trace("Generated replies {} {} {}", commandDispatcherId, message, replies); } catch (Exception e) { logger.error("Generated error {} {} {}", commandDispatcherId, message, e.getClass().getName()); logger.error("Generated error", e); handleException(message, param, m, e, pathVars, defaultReplyChannel); return; } if (replies != null) { sendReplies(correlationHeaders, replies, defaultReplyChannel); } else { logger.trace("Null replies - not publishling"); } } CommandDispatcher(String commandDispatcherId, CommandHandlers commandHandlers, MessageConsumer messageConsumer, MessageProducer messageProducer); @PostConstruct void initialize(); void messageHandler(Message message); }
@Test public void shouldReplacePlaceholders() { ResourcePathPattern rpp = new ResourcePathPattern("/foo/{bar}"); ResourcePath rp = rpp.replacePlaceholders(new SingleValuePlaceholderValueProvider("baz")); assertEquals("/foo/baz", rp.toPath()); }
public ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider) { return new ResourcePath(Arrays.stream(splits).map(s -> isPlaceholder(s) ? placeholderValueProvider.get(placeholderName(s)).orElseGet(() -> { throw new RuntimeException("Placeholder not found: " + placeholderName(s) + " in " + s + ", params=" + placeholderValueProvider.getParams()); }) : s).collect(toList()).toArray(new String[splits.length])); }
ResourcePathPattern { public ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider) { return new ResourcePath(Arrays.stream(splits).map(s -> isPlaceholder(s) ? placeholderValueProvider.get(placeholderName(s)).orElseGet(() -> { throw new RuntimeException("Placeholder not found: " + placeholderName(s) + " in " + s + ", params=" + placeholderValueProvider.getParams()); }) : s).collect(toList()).toArray(new String[splits.length])); } }
ResourcePathPattern { public ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider) { return new ResourcePath(Arrays.stream(splits).map(s -> isPlaceholder(s) ? placeholderValueProvider.get(placeholderName(s)).orElseGet(() -> { throw new RuntimeException("Placeholder not found: " + placeholderName(s) + " in " + s + ", params=" + placeholderValueProvider.getParams()); }) : s).collect(toList()).toArray(new String[splits.length])); } ResourcePathPattern(String pathPattern); }
ResourcePathPattern { public ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider) { return new ResourcePath(Arrays.stream(splits).map(s -> isPlaceholder(s) ? placeholderValueProvider.get(placeholderName(s)).orElseGet(() -> { throw new RuntimeException("Placeholder not found: " + placeholderName(s) + " in " + s + ", params=" + placeholderValueProvider.getParams()); }) : s).collect(toList()).toArray(new String[splits.length])); } ResourcePathPattern(String pathPattern); static ResourcePathPattern parse(String pathPattern); int length(); boolean isSatisfiedBy(ResourcePath mr); Map<String, String> getPathVariableValues(ResourcePath mr); ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider); ResourcePath replacePlaceholders(Object[] pathParams); }
ResourcePathPattern { public ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider) { return new ResourcePath(Arrays.stream(splits).map(s -> isPlaceholder(s) ? placeholderValueProvider.get(placeholderName(s)).orElseGet(() -> { throw new RuntimeException("Placeholder not found: " + placeholderName(s) + " in " + s + ", params=" + placeholderValueProvider.getParams()); }) : s).collect(toList()).toArray(new String[splits.length])); } ResourcePathPattern(String pathPattern); static ResourcePathPattern parse(String pathPattern); int length(); boolean isSatisfiedBy(ResourcePath mr); Map<String, String> getPathVariableValues(ResourcePath mr); ResourcePath replacePlaceholders(PlaceholderValueProvider placeholderValueProvider); ResourcePath replacePlaceholders(Object[] pathParams); }
@Test public void getUserByApi() throws Exception { User user =userService.getUserByApi("bee1a09b-9867-4f1a-9886-c25d8b0e42b1"); System.out.println(user); }
@Override public User getUserByApi(String token) { String s = HttpClientUtils.doGet(api_getUserByToken + token); QuarkResult quarkResult = JsonUtils.jsonToQuarkResult(s, User.class); User data= (User) quarkResult.getData(); return data; }
UserServiceImpl implements UserService { @Override public User getUserByApi(String token) { String s = HttpClientUtils.doGet(api_getUserByToken + token); QuarkResult quarkResult = JsonUtils.jsonToQuarkResult(s, User.class); User data= (User) quarkResult.getData(); return data; } }
UserServiceImpl implements UserService { @Override public User getUserByApi(String token) { String s = HttpClientUtils.doGet(api_getUserByToken + token); QuarkResult quarkResult = JsonUtils.jsonToQuarkResult(s, User.class); User data= (User) quarkResult.getData(); return data; } }
UserServiceImpl implements UserService { @Override public User getUserByApi(String token) { String s = HttpClientUtils.doGet(api_getUserByToken + token); QuarkResult quarkResult = JsonUtils.jsonToQuarkResult(s, User.class); User data= (User) quarkResult.getData(); return data; } @Override User getUserByApi(String token); }
UserServiceImpl implements UserService { @Override public User getUserByApi(String token) { String s = HttpClientUtils.doGet(api_getUserByToken + token); QuarkResult quarkResult = JsonUtils.jsonToQuarkResult(s, User.class); User data= (User) quarkResult.getData(); return data; } @Override User getUserByApi(String token); }
@Test void test() { PartlyCovered partlyCovered = new PartlyCovered(); String string = partlyCovered.partlyCovered("THIS IS A STRING", false); assertThat(string).isEqualTo("THIS IS A STRING"); }
String partlyCovered(String string, boolean trigger){ if(trigger){ string = string.toLowerCase(); } return string; }
PartlyCovered { String partlyCovered(String string, boolean trigger){ if(trigger){ string = string.toLowerCase(); } return string; } }
PartlyCovered { String partlyCovered(String string, boolean trigger){ if(trigger){ string = string.toLowerCase(); } return string; } }
PartlyCovered { String partlyCovered(String string, boolean trigger){ if(trigger){ string = string.toLowerCase(); } return string; } }
PartlyCovered { String partlyCovered(String string, boolean trigger){ if(trigger){ string = string.toLowerCase(); } return string; } }
@Test void staticQuotesAreLoaded() { assertThat(quotesProperties.getQuotes()).hasSize(2); }
List<Quote> getQuotes() { return this.quotes; }
QuotesProperties { List<Quote> getQuotes() { return this.quotes; } }
QuotesProperties { List<Quote> getQuotes() { return this.quotes; } QuotesProperties(List<Quote> quotes); }
QuotesProperties { List<Quote> getQuotes() { return this.quotes; } QuotesProperties(List<Quote> quotes); }
QuotesProperties { List<Quote> getQuotes() { return this.quotes; } QuotesProperties(List<Quote> quotes); }
@Test void putGet() throws Exception { String number = "BO5489"; Car car = Car.builder() .number(number) .name("VW") .build(); String content = objectMapper.writeValueAsString(car); mockMvc.perform( post("/cars/" + number) .content(content) .contentType(MediaType.APPLICATION_JSON_VALUE) ).andExpect(status().isCreated()); String json = mockMvc.perform( get("/cars/" + number)) .andExpect(status().isOk() ).andReturn().getResponse().getContentAsString(); Car response = objectMapper.readValue(json, Car.class); assertThat(response).isEqualToComparingFieldByField(car); }
@GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); @PostMapping(path = "/{number}", produces= MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(code = HttpStatus.CREATED) Car put(@RequestBody Car car, @PathVariable String number); @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) Car get(@PathVariable String number); }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); @PostMapping(path = "/{number}", produces= MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(code = HttpStatus.CREATED) Car put(@RequestBody Car car, @PathVariable String number); @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) Car get(@PathVariable String number); }
@Test void putGet() throws Exception { String number = "BO5489"; Car car = Car.builder().color(number).name("VW").build(); String content = objectMapper.writeValueAsString(car); mockMvc .perform( post("/cars/" + number).content(content).contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isCreated()); String json = mockMvc .perform(get("/cars/" + number)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); Car response = objectMapper.readValue(json, Car.class); assertThat(response).isEqualToComparingFieldByField(car); }
@GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); @PostMapping(value = "/{number}",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(code = HttpStatus.CREATED) Car put(@RequestBody Car car, @PathVariable String number); @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) Car get(@PathVariable String number); }
Controller { @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) public Car get(@PathVariable String number) { return cacheClient.get(number); } Controller(CacheClient cacheClient); @PostMapping(value = "/{number}",produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(code = HttpStatus.CREATED) Car put(@RequestBody Car car, @PathVariable String number); @GetMapping(value = "/{number}", produces = MediaType.APPLICATION_JSON_VALUE) Car get(@PathVariable String number); }
@Test void sendMessageSynchronously() { ThrowableAssert.ThrowingCallable send = () -> statefulBlockingClient.send(); assertThatCode(send).doesNotThrowAnyException(); }
@Scheduled(fixedDelay = 3000) public void send() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); RegistrationDto registrationDto = template.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); }
StatefulBlockingClient { @Scheduled(fixedDelay = 3000) public void send() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); RegistrationDto registrationDto = template.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); } }
StatefulBlockingClient { @Scheduled(fixedDelay = 3000) public void send() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); RegistrationDto registrationDto = template.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); } StatefulBlockingClient(DirectExchange directExchange, RabbitTemplate template); }
StatefulBlockingClient { @Scheduled(fixedDelay = 3000) public void send() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); RegistrationDto registrationDto = template.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); } StatefulBlockingClient(DirectExchange directExchange, RabbitTemplate template); @Scheduled(fixedDelay = 3000) void send(); }
StatefulBlockingClient { @Scheduled(fixedDelay = 3000) public void send() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); RegistrationDto registrationDto = template.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); } StatefulBlockingClient(DirectExchange directExchange, RabbitTemplate template); @Scheduled(fixedDelay = 3000) void send(); static final String ROUTING_KEY; }
@Test void sendAsynchronouslyWithCallback() { ThrowableAssert.ThrowingCallable send = () -> statefulCallbackClient.sendAsynchronouslyWithCallback(); assertThatCode(send).doesNotThrowAnyException(); }
@Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendAsynchronouslyWithCallback() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); RabbitConverterFuture<RegistrationDto> rabbitConverterFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() {}); rabbitConverterFuture.addCallback(new ListenableFutureCallback<>() { @Override public void onFailure(Throwable ex) { LOGGER.error("Cannot get response for: {}", carDto.getId(), ex); } @Override public void onSuccess(RegistrationDto registrationDto) { LOGGER.info("Registration received {}", registrationDto); } }); }
StatefulCallbackClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendAsynchronouslyWithCallback() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); RabbitConverterFuture<RegistrationDto> rabbitConverterFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() {}); rabbitConverterFuture.addCallback(new ListenableFutureCallback<>() { @Override public void onFailure(Throwable ex) { LOGGER.error("Cannot get response for: {}", carDto.getId(), ex); } @Override public void onSuccess(RegistrationDto registrationDto) { LOGGER.info("Registration received {}", registrationDto); } }); } }
StatefulCallbackClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendAsynchronouslyWithCallback() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); RabbitConverterFuture<RegistrationDto> rabbitConverterFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() {}); rabbitConverterFuture.addCallback(new ListenableFutureCallback<>() { @Override public void onFailure(Throwable ex) { LOGGER.error("Cannot get response for: {}", carDto.getId(), ex); } @Override public void onSuccess(RegistrationDto registrationDto) { LOGGER.info("Registration received {}", registrationDto); } }); } StatefulCallbackClient(AsyncRabbitTemplate asyncRabbitTemplate, DirectExchange directExchange); }
StatefulCallbackClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendAsynchronouslyWithCallback() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); RabbitConverterFuture<RegistrationDto> rabbitConverterFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() {}); rabbitConverterFuture.addCallback(new ListenableFutureCallback<>() { @Override public void onFailure(Throwable ex) { LOGGER.error("Cannot get response for: {}", carDto.getId(), ex); } @Override public void onSuccess(RegistrationDto registrationDto) { LOGGER.info("Registration received {}", registrationDto); } }); } StatefulCallbackClient(AsyncRabbitTemplate asyncRabbitTemplate, DirectExchange directExchange); @Scheduled(fixedDelay = 3000, initialDelay = 1500) void sendAsynchronouslyWithCallback(); }
StatefulCallbackClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendAsynchronouslyWithCallback() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); RabbitConverterFuture<RegistrationDto> rabbitConverterFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() {}); rabbitConverterFuture.addCallback(new ListenableFutureCallback<>() { @Override public void onFailure(Throwable ex) { LOGGER.error("Cannot get response for: {}", carDto.getId(), ex); } @Override public void onSuccess(RegistrationDto registrationDto) { LOGGER.info("Registration received {}", registrationDto); } }); } StatefulCallbackClient(AsyncRabbitTemplate asyncRabbitTemplate, DirectExchange directExchange); @Scheduled(fixedDelay = 3000, initialDelay = 1500) void sendAsynchronouslyWithCallback(); static final Logger LOGGER; static final String ROUTING_KEY; }
@Test void sendAsynchronously() { ThrowableAssert.ThrowingCallable send = () -> statefulFutureClient.sendWithFuture(); assertThatCode(send) .doesNotThrowAnyException(); }
@Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendWithFuture() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); ListenableFuture<RegistrationDto> listenableFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); try { RegistrationDto registrationDto = listenableFuture.get(); LOGGER.info("Message received: {}", registrationDto); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Cannot get response.", e); } }
StatefulFutureClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendWithFuture() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); ListenableFuture<RegistrationDto> listenableFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); try { RegistrationDto registrationDto = listenableFuture.get(); LOGGER.info("Message received: {}", registrationDto); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Cannot get response.", e); } } }
StatefulFutureClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendWithFuture() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); ListenableFuture<RegistrationDto> listenableFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); try { RegistrationDto registrationDto = listenableFuture.get(); LOGGER.info("Message received: {}", registrationDto); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Cannot get response.", e); } } StatefulFutureClient(AsyncRabbitTemplate asyncRabbitTemplate, DirectExchange directExchange); }
StatefulFutureClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendWithFuture() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); ListenableFuture<RegistrationDto> listenableFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); try { RegistrationDto registrationDto = listenableFuture.get(); LOGGER.info("Message received: {}", registrationDto); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Cannot get response.", e); } } StatefulFutureClient(AsyncRabbitTemplate asyncRabbitTemplate, DirectExchange directExchange); @Scheduled(fixedDelay = 3000, initialDelay = 1500) void sendWithFuture(); }
StatefulFutureClient { @Scheduled(fixedDelay = 3000, initialDelay = 1500) public void sendWithFuture() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("black") .name("bmw") .build(); ListenableFuture<RegistrationDto> listenableFuture = asyncRabbitTemplate.convertSendAndReceiveAsType( directExchange.getName(), ROUTING_KEY, carDto, new ParameterizedTypeReference<>() { }); try { RegistrationDto registrationDto = listenableFuture.get(); LOGGER.info("Message received: {}", registrationDto); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Cannot get response.", e); } } StatefulFutureClient(AsyncRabbitTemplate asyncRabbitTemplate, DirectExchange directExchange); @Scheduled(fixedDelay = 3000, initialDelay = 1500) void sendWithFuture(); static final Logger LOGGER; static final String ROUTING_KEY; }
@Test void sendAndForget() { ThrowableAssert.ThrowingCallable send = () -> statelessClient.sendAndForget(); assertThatCode(send).doesNotThrowAnyException(); }
@Scheduled(fixedDelay = 3000) public void sendAndForget() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); UUID correlationId = UUID.randomUUID(); registrationService.saveCar(carDto, correlationId); MessagePostProcessor messagePostProcessor = message -> { MessageProperties messageProperties = message.getMessageProperties(); messageProperties.setReplyTo(replyQueue.getName()); messageProperties.setCorrelationId(correlationId.toString()); return message; }; template.convertAndSend(directExchange.getName(), "old.car", carDto, messagePostProcessor); }
StatelessClient { @Scheduled(fixedDelay = 3000) public void sendAndForget() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); UUID correlationId = UUID.randomUUID(); registrationService.saveCar(carDto, correlationId); MessagePostProcessor messagePostProcessor = message -> { MessageProperties messageProperties = message.getMessageProperties(); messageProperties.setReplyTo(replyQueue.getName()); messageProperties.setCorrelationId(correlationId.toString()); return message; }; template.convertAndSend(directExchange.getName(), "old.car", carDto, messagePostProcessor); } }
StatelessClient { @Scheduled(fixedDelay = 3000) public void sendAndForget() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); UUID correlationId = UUID.randomUUID(); registrationService.saveCar(carDto, correlationId); MessagePostProcessor messagePostProcessor = message -> { MessageProperties messageProperties = message.getMessageProperties(); messageProperties.setReplyTo(replyQueue.getName()); messageProperties.setCorrelationId(correlationId.toString()); return message; }; template.convertAndSend(directExchange.getName(), "old.car", carDto, messagePostProcessor); } StatelessClient(RabbitTemplate template, DirectExchange directExchange, Queue replyQueue, RegistrationService registrationService); }
StatelessClient { @Scheduled(fixedDelay = 3000) public void sendAndForget() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); UUID correlationId = UUID.randomUUID(); registrationService.saveCar(carDto, correlationId); MessagePostProcessor messagePostProcessor = message -> { MessageProperties messageProperties = message.getMessageProperties(); messageProperties.setReplyTo(replyQueue.getName()); messageProperties.setCorrelationId(correlationId.toString()); return message; }; template.convertAndSend(directExchange.getName(), "old.car", carDto, messagePostProcessor); } StatelessClient(RabbitTemplate template, DirectExchange directExchange, Queue replyQueue, RegistrationService registrationService); @Scheduled(fixedDelay = 3000) void sendAndForget(); }
StatelessClient { @Scheduled(fixedDelay = 3000) public void sendAndForget() { CarDto carDto = CarDto.builder() .id(UUID.randomUUID()) .color("white") .name("vw") .build(); UUID correlationId = UUID.randomUUID(); registrationService.saveCar(carDto, correlationId); MessagePostProcessor messagePostProcessor = message -> { MessageProperties messageProperties = message.getMessageProperties(); messageProperties.setReplyTo(replyQueue.getName()); messageProperties.setCorrelationId(correlationId.toString()); return message; }; template.convertAndSend(directExchange.getName(), "old.car", carDto, messagePostProcessor); } StatelessClient(RabbitTemplate template, DirectExchange directExchange, Queue replyQueue, RegistrationService registrationService); @Scheduled(fixedDelay = 3000) void sendAndForget(); }
@Test @Sql("/insert_car.sql") void updateCar() throws Exception { CarDto carDto = CarDto.builder() .id(UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80")) .name("vw") .color("white") .build(); mockMvc.perform( put("/cars") .content(objectMapper.writeValueAsString(carDto)) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk()); }
@PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); }
CarResource { @PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); } }
CarResource { @PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
CarResource { @PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
CarResource { @PutMapping private CarDto updateCar(@RequestBody CarDto carDto) { Car car = carMapper.toCar(carDto); return carMapper.toCarDto(carService.update(car)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
@Test @Sql("/insert_car.sql") void getCar() throws Exception { UUID id = UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80"); mockMvc.perform( get("/cars/" + id) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isOk()); }
@GetMapping(value = "/{uuid}") private CarDto get(@PathVariable UUID uuid){ return carMapper.toCarDto(carService.get(uuid)); }
CarResource { @GetMapping(value = "/{uuid}") private CarDto get(@PathVariable UUID uuid){ return carMapper.toCarDto(carService.get(uuid)); } }
CarResource { @GetMapping(value = "/{uuid}") private CarDto get(@PathVariable UUID uuid){ return carMapper.toCarDto(carService.get(uuid)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
CarResource { @GetMapping(value = "/{uuid}") private CarDto get(@PathVariable UUID uuid){ return carMapper.toCarDto(carService.get(uuid)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
CarResource { @GetMapping(value = "/{uuid}") private CarDto get(@PathVariable UUID uuid){ return carMapper.toCarDto(carService.get(uuid)); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
@Test @Sql("/insert_car.sql") void deleteCar() throws Exception { UUID id = UUID.fromString("1b104b1a-8539-4e06-aea7-9d77f2193b80"); mockMvc.perform( delete("/cars/" + id) ) .andExpect(status().isNoContent()); }
@DeleteMapping(value = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) private void delete(@PathVariable UUID uuid){ carService.delete(uuid); }
CarResource { @DeleteMapping(value = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) private void delete(@PathVariable UUID uuid){ carService.delete(uuid); } }
CarResource { @DeleteMapping(value = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) private void delete(@PathVariable UUID uuid){ carService.delete(uuid); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
CarResource { @DeleteMapping(value = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) private void delete(@PathVariable UUID uuid){ carService.delete(uuid); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
CarResource { @DeleteMapping(value = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) private void delete(@PathVariable UUID uuid){ carService.delete(uuid); } CarResource(CarService carService, CarMapper carMapper, CacheManager cacheManager); }
@Test void testSimple() { PartlyCovered fullyCovered = new PartlyCovered(); String string = fullyCovered.covered("THIS IS A STRING"); assertThat(string).isEqualTo("this is a string"); }
String covered(String string) { string = string.toLowerCase(); return string; }
PartlyCovered { String covered(String string) { string = string.toLowerCase(); return string; } }
PartlyCovered { String covered(String string) { string = string.toLowerCase(); return string; } }
PartlyCovered { String covered(String string) { string = string.toLowerCase(); return string; } }
PartlyCovered { String covered(String string) { string = string.toLowerCase(); return string; } }
@Test void toUserDetails() { UserCredentials userCredentials = UserCredentials.builder() .enabled(true) .password("password") .username("user") .roles(Set.of("USER", "ADMIN")) .build(); UserDetails userDetails = userDetailsMapper.toUserDetails(userCredentials); assertThat(userDetails.getUsername()).isEqualTo("user"); assertThat(userDetails.getPassword()).isEqualTo("password"); assertThat(userDetails.isEnabled()).isTrue(); }
UserDetails toUserDetails(UserCredentials userCredentials) { return User.withUsername(userCredentials.getUsername()) .password(userCredentials.getPassword()) .roles(userCredentials.getRoles().toArray(String[]::new)) .build(); }
UserDetailsMapper { UserDetails toUserDetails(UserCredentials userCredentials) { return User.withUsername(userCredentials.getUsername()) .password(userCredentials.getPassword()) .roles(userCredentials.getRoles().toArray(String[]::new)) .build(); } }
UserDetailsMapper { UserDetails toUserDetails(UserCredentials userCredentials) { return User.withUsername(userCredentials.getUsername()) .password(userCredentials.getPassword()) .roles(userCredentials.getRoles().toArray(String[]::new)) .build(); } }
UserDetailsMapper { UserDetails toUserDetails(UserCredentials userCredentials) { return User.withUsername(userCredentials.getUsername()) .password(userCredentials.getPassword()) .roles(userCredentials.getRoles().toArray(String[]::new)) .build(); } }
UserDetailsMapper { UserDetails toUserDetails(UserCredentials userCredentials) { return User.withUsername(userCredentials.getUsername()) .password(userCredentials.getPassword()) .roles(userCredentials.getRoles().toArray(String[]::new)) .build(); } }
@Test void encode() { String plainPassword = "password"; String encoded = bcryptExample.encode(plainPassword); assertThat(encoded).startsWith("$2a$10"); }
public String encode(String plainPassword) { int strength = 10; BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(strength, new SecureRandom()); return bCryptPasswordEncoder.encode(plainPassword); }
BCryptExample { public String encode(String plainPassword) { int strength = 10; BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(strength, new SecureRandom()); return bCryptPasswordEncoder.encode(plainPassword); } }
BCryptExample { public String encode(String plainPassword) { int strength = 10; BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(strength, new SecureRandom()); return bCryptPasswordEncoder.encode(plainPassword); } }
BCryptExample { public String encode(String plainPassword) { int strength = 10; BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(strength, new SecureRandom()); return bCryptPasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
BCryptExample { public String encode(String plainPassword) { int strength = 10; BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(strength, new SecureRandom()); return bCryptPasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
@Test void encode() { String plainPassword = "plainPassword"; String actual = pbkdf2Example.encode(plainPassword); assertThat(actual).hasSize(80); }
public String encode(String plainPassword) { String pepper = "pepper"; int iterations = 200000; int hashWidth = 256; Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth); return pbkdf2PasswordEncoder.encode(plainPassword); }
Pbkdf2Example { public String encode(String plainPassword) { String pepper = "pepper"; int iterations = 200000; int hashWidth = 256; Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth); return pbkdf2PasswordEncoder.encode(plainPassword); } }
Pbkdf2Example { public String encode(String plainPassword) { String pepper = "pepper"; int iterations = 200000; int hashWidth = 256; Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth); return pbkdf2PasswordEncoder.encode(plainPassword); } }
Pbkdf2Example { public String encode(String plainPassword) { String pepper = "pepper"; int iterations = 200000; int hashWidth = 256; Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth); return pbkdf2PasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
Pbkdf2Example { public String encode(String plainPassword) { String pepper = "pepper"; int iterations = 200000; int hashWidth = 256; Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(pepper, iterations, hashWidth); return pbkdf2PasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
@Test void encode() { String plainPassword = "password"; String actual = argon2Example.encode(plainPassword); assertThat(actual).startsWith("$argon2id$v=19$m=4096,t=3,p=1"); }
public String encode(String plainPassword) { int saltLength = 16; int hashLength = 32; int parallelism = 1; int memory = 4096; int iterations = 3; Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder(saltLength, hashLength, parallelism, memory, iterations); return argon2PasswordEncoder.encode(plainPassword); }
Argon2Example { public String encode(String plainPassword) { int saltLength = 16; int hashLength = 32; int parallelism = 1; int memory = 4096; int iterations = 3; Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder(saltLength, hashLength, parallelism, memory, iterations); return argon2PasswordEncoder.encode(plainPassword); } }
Argon2Example { public String encode(String plainPassword) { int saltLength = 16; int hashLength = 32; int parallelism = 1; int memory = 4096; int iterations = 3; Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder(saltLength, hashLength, parallelism, memory, iterations); return argon2PasswordEncoder.encode(plainPassword); } }
Argon2Example { public String encode(String plainPassword) { int saltLength = 16; int hashLength = 32; int parallelism = 1; int memory = 4096; int iterations = 3; Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder(saltLength, hashLength, parallelism, memory, iterations); return argon2PasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
Argon2Example { public String encode(String plainPassword) { int saltLength = 16; int hashLength = 32; int parallelism = 1; int memory = 4096; int iterations = 3; Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder(saltLength, hashLength, parallelism, memory, iterations); return argon2PasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
@Test void encode() { String plainPassword = "password"; String actual = sCryptExample.encode(plainPassword); assertThat(actual).hasSize(140); assertThat(actual).startsWith("$e0801"); }
public String encode(String plainPassword) { int cpuCost = (int) Math.pow(2, 14); int memoryCost = 8; int parallelization = 1; int keyLength = 32; int saltLength = 64; SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder(cpuCost, memoryCost, parallelization, keyLength, saltLength); return sCryptPasswordEncoder.encode(plainPassword); }
SCryptExample { public String encode(String plainPassword) { int cpuCost = (int) Math.pow(2, 14); int memoryCost = 8; int parallelization = 1; int keyLength = 32; int saltLength = 64; SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder(cpuCost, memoryCost, parallelization, keyLength, saltLength); return sCryptPasswordEncoder.encode(plainPassword); } }
SCryptExample { public String encode(String plainPassword) { int cpuCost = (int) Math.pow(2, 14); int memoryCost = 8; int parallelization = 1; int keyLength = 32; int saltLength = 64; SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder(cpuCost, memoryCost, parallelization, keyLength, saltLength); return sCryptPasswordEncoder.encode(plainPassword); } }
SCryptExample { public String encode(String plainPassword) { int cpuCost = (int) Math.pow(2, 14); int memoryCost = 8; int parallelization = 1; int keyLength = 32; int saltLength = 64; SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder(cpuCost, memoryCost, parallelization, keyLength, saltLength); return sCryptPasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
SCryptExample { public String encode(String plainPassword) { int cpuCost = (int) Math.pow(2, 14); int memoryCost = 8; int parallelization = 1; int keyLength = 32; int saltLength = 64; SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder(cpuCost, memoryCost, parallelization, keyLength, saltLength); return sCryptPasswordEncoder.encode(plainPassword); } String encode(String plainPassword); }
@Test void calculateStrength() { int strength = bcCryptWorkFactorService.calculateStrength(); assertThat(strength).isBetween(4, 31); }
public int calculateStrength() { for (int strength = MIN_STRENGTH; strength <= MAX_STRENGTH; strength++) { long duration = calculateDuration(strength); if (duration >= GOAL_MILLISECONDS_PER_PASSWORD) { return strength; } } throw new RuntimeException( String.format( "Could not find suitable round number for bcrypt encoding. The encoding with %d rounds" + " takes less than %d ms.", MAX_STRENGTH, GOAL_MILLISECONDS_PER_PASSWORD)); }
BcCryptWorkFactorService { public int calculateStrength() { for (int strength = MIN_STRENGTH; strength <= MAX_STRENGTH; strength++) { long duration = calculateDuration(strength); if (duration >= GOAL_MILLISECONDS_PER_PASSWORD) { return strength; } } throw new RuntimeException( String.format( "Could not find suitable round number for bcrypt encoding. The encoding with %d rounds" + " takes less than %d ms.", MAX_STRENGTH, GOAL_MILLISECONDS_PER_PASSWORD)); } }
BcCryptWorkFactorService { public int calculateStrength() { for (int strength = MIN_STRENGTH; strength <= MAX_STRENGTH; strength++) { long duration = calculateDuration(strength); if (duration >= GOAL_MILLISECONDS_PER_PASSWORD) { return strength; } } throw new RuntimeException( String.format( "Could not find suitable round number for bcrypt encoding. The encoding with %d rounds" + " takes less than %d ms.", MAX_STRENGTH, GOAL_MILLISECONDS_PER_PASSWORD)); } }
BcCryptWorkFactorService { public int calculateStrength() { for (int strength = MIN_STRENGTH; strength <= MAX_STRENGTH; strength++) { long duration = calculateDuration(strength); if (duration >= GOAL_MILLISECONDS_PER_PASSWORD) { return strength; } } throw new RuntimeException( String.format( "Could not find suitable round number for bcrypt encoding. The encoding with %d rounds" + " takes less than %d ms.", MAX_STRENGTH, GOAL_MILLISECONDS_PER_PASSWORD)); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
BcCryptWorkFactorService { public int calculateStrength() { for (int strength = MIN_STRENGTH; strength <= MAX_STRENGTH; strength++) { long duration = calculateDuration(strength); if (duration >= GOAL_MILLISECONDS_PER_PASSWORD) { return strength; } } throw new RuntimeException( String.format( "Could not find suitable round number for bcrypt encoding. The encoding with %d rounds" + " takes less than %d ms.", MAX_STRENGTH, GOAL_MILLISECONDS_PER_PASSWORD)); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void findCloserToShouldReturnNumber1IfItCloserToGoalThanNumber2() { int number1 = 950; int number2 = 1051; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isTrue(); }
boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void findCloserToShouldReturnNUmber2IfItCloserToGoalThanNumber1() { int number1 = 1002; int number2 = 999; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isFalse(); }
boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void findCloserToShouldReturnGoalIfNumber2IsEqualGoal() { int number1 = 999; int number2 = 1000; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isFalse(); }
boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void findCloserToShouldReturnGoalIfNumber1IsEqualGoal() { int number1 = 1000; int number2 = 1001; boolean actual = bcCryptWorkFactorService.isPreviousDurationCloserToGoal(number1, number2); assertThat(actual).isTrue(); }
boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
BcCryptWorkFactorService { boolean isPreviousDurationCloserToGoal(long previousDuration, long currentDuration) { return Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - previousDuration) < Math.abs(GOAL_MILLISECONDS_PER_PASSWORD - currentDuration); } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void test() { FullyCovered fullyCovered = new FullyCovered(); String string = fullyCovered.lowercase("THIS IS A STRING"); assertThat(string).isEqualTo("this is a string"); }
String lowercase(String string) { string = string.toLowerCase(); return string; }
FullyCovered { String lowercase(String string) { string = string.toLowerCase(); return string; } }
FullyCovered { String lowercase(String string) { string = string.toLowerCase(); return string; } }
FullyCovered { String lowercase(String string) { string = string.toLowerCase(); return string; } }
FullyCovered { String lowercase(String string) { string = string.toLowerCase(); return string; } }
@Test void getStrengthShouldReturn4IfStrengthIs4() { int currentStrength = 4; int actual = bcCryptWorkFactorService.getStrength(0, 0, currentStrength); assertThat(actual).isEqualTo(4); }
int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void getStrengthShouldReturnPreviousStrengthIfPreviousDurationCloserToGoal() { int actual = bcCryptWorkFactorService.getStrength(980, 1021, 5); assertThat(actual).isEqualTo(4); }
int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void getStrengthShouldReturnCurrentStrengthIfCurrentDurationCloserToGoal() { int actual = bcCryptWorkFactorService.getStrength(960, 1021, 5); assertThat(actual).isEqualTo(5); }
int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
BcCryptWorkFactorService { int getStrength(long previousDuration, long currentDuration, int strength) { if (isPreviousDurationCloserToGoal(previousDuration, currentDuration)) { return strength - 1; } else { return strength; } } BcryptWorkFactor calculateStrengthDivideAndConquer(); int calculateStrength(); }
@Test void calculateIteration() { int iterationNumber = pbkdf2WorkFactorService.calculateIteration(); assertThat(iterationNumber).isGreaterThanOrEqualTo(150000); }
public int calculateIteration() { int iterationNumber = 150000; while (true) { Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(NO_ADDITIONAL_SECRET, iterationNumber, HASH_WIDTH); Stopwatch stopwatch = Stopwatch.createStarted(); pbkdf2PasswordEncoder.encode(TEST_PASSWORD); stopwatch.stop(); long duration = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (duration > GOAL_MILLISECONDS_PER_PASSWORD) { return iterationNumber; } iterationNumber += ITERATION_STEP; } }
Pbkdf2WorkFactorService { public int calculateIteration() { int iterationNumber = 150000; while (true) { Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(NO_ADDITIONAL_SECRET, iterationNumber, HASH_WIDTH); Stopwatch stopwatch = Stopwatch.createStarted(); pbkdf2PasswordEncoder.encode(TEST_PASSWORD); stopwatch.stop(); long duration = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (duration > GOAL_MILLISECONDS_PER_PASSWORD) { return iterationNumber; } iterationNumber += ITERATION_STEP; } } }
Pbkdf2WorkFactorService { public int calculateIteration() { int iterationNumber = 150000; while (true) { Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(NO_ADDITIONAL_SECRET, iterationNumber, HASH_WIDTH); Stopwatch stopwatch = Stopwatch.createStarted(); pbkdf2PasswordEncoder.encode(TEST_PASSWORD); stopwatch.stop(); long duration = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (duration > GOAL_MILLISECONDS_PER_PASSWORD) { return iterationNumber; } iterationNumber += ITERATION_STEP; } } }
Pbkdf2WorkFactorService { public int calculateIteration() { int iterationNumber = 150000; while (true) { Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(NO_ADDITIONAL_SECRET, iterationNumber, HASH_WIDTH); Stopwatch stopwatch = Stopwatch.createStarted(); pbkdf2PasswordEncoder.encode(TEST_PASSWORD); stopwatch.stop(); long duration = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (duration > GOAL_MILLISECONDS_PER_PASSWORD) { return iterationNumber; } iterationNumber += ITERATION_STEP; } } int calculateIteration(); }
Pbkdf2WorkFactorService { public int calculateIteration() { int iterationNumber = 150000; while (true) { Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder(NO_ADDITIONAL_SECRET, iterationNumber, HASH_WIDTH); Stopwatch stopwatch = Stopwatch.createStarted(); pbkdf2PasswordEncoder.encode(TEST_PASSWORD); stopwatch.stop(); long duration = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (duration > GOAL_MILLISECONDS_PER_PASSWORD) { return iterationNumber; } iterationNumber += ITERATION_STEP; } } int calculateIteration(); }
@Test @PactVerification("userCreatedMessagePact") public void verifyCreatePersonPact() throws IOException { messageConsumer.consumeStringMessage(new String(this.currentMessage)); }
public void consumeStringMessage(String messageString) throws IOException { logger.info("Consuming message '{}'", messageString); UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<UserCreatedMessage>> violations = validator.validate(message); if(!violations.isEmpty()){ throw new ConstraintViolationException(violations); } }
MessageConsumer { public void consumeStringMessage(String messageString) throws IOException { logger.info("Consuming message '{}'", messageString); UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<UserCreatedMessage>> violations = validator.validate(message); if(!violations.isEmpty()){ throw new ConstraintViolationException(violations); } } }
MessageConsumer { public void consumeStringMessage(String messageString) throws IOException { logger.info("Consuming message '{}'", messageString); UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<UserCreatedMessage>> violations = validator.validate(message); if(!violations.isEmpty()){ throw new ConstraintViolationException(violations); } } MessageConsumer(ObjectMapper objectMapper); }
MessageConsumer { public void consumeStringMessage(String messageString) throws IOException { logger.info("Consuming message '{}'", messageString); UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<UserCreatedMessage>> violations = validator.validate(message); if(!violations.isEmpty()){ throw new ConstraintViolationException(violations); } } MessageConsumer(ObjectMapper objectMapper); void consumeStringMessage(String messageString); }
MessageConsumer { public void consumeStringMessage(String messageString) throws IOException { logger.info("Consuming message '{}'", messageString); UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Set<ConstraintViolation<UserCreatedMessage>> violations = validator.validate(message); if(!violations.isEmpty()){ throw new ConstraintViolationException(violations); } } MessageConsumer(ObjectMapper objectMapper); void consumeStringMessage(String messageString); }
@Test void allMessagesAreProcessedOnMultipleThreads() { int batches = 10; int batchSize = 3; int threads = 2; int threadPoolQueueSize = 10; MessageSource messageSource = new TestMessageSource(batches, batchSize); TestMessageHandler messageHandler = new TestMessageHandler(); ReactiveBatchProcessor processor = new ReactiveBatchProcessor( messageSource, messageHandler, threads, threadPoolQueueSize); processor.start(); await() .atMost(10, TimeUnit.SECONDS) .pollInterval(1, TimeUnit.SECONDS) .untilAsserted(() -> assertEquals(batches * batchSize, messageHandler.getProcessedMessages())); assertEquals(threads, messageHandler.threadNames().size()); }
void start() { Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize); messageSource.getMessageBatches() .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor())) .doOnNext(batch -> logger.log(batch.toString())) .flatMap(batch -> Flowable.fromIterable(batch.getMessages())) .flatMapSingle(m -> Single.defer(() -> Single.just(m) .map(messageHandler::handleMessage)) .subscribeOn(scheduler)) .subscribeWith(new SimpleSubscriber<>(threads, 1)); }
ReactiveBatchProcessor { void start() { Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize); messageSource.getMessageBatches() .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor())) .doOnNext(batch -> logger.log(batch.toString())) .flatMap(batch -> Flowable.fromIterable(batch.getMessages())) .flatMapSingle(m -> Single.defer(() -> Single.just(m) .map(messageHandler::handleMessage)) .subscribeOn(scheduler)) .subscribeWith(new SimpleSubscriber<>(threads, 1)); } }
ReactiveBatchProcessor { void start() { Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize); messageSource.getMessageBatches() .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor())) .doOnNext(batch -> logger.log(batch.toString())) .flatMap(batch -> Flowable.fromIterable(batch.getMessages())) .flatMapSingle(m -> Single.defer(() -> Single.just(m) .map(messageHandler::handleMessage)) .subscribeOn(scheduler)) .subscribeWith(new SimpleSubscriber<>(threads, 1)); } ReactiveBatchProcessor( MessageSource messageSource, MessageHandler messageHandler, int threads, int threadPoolQueueSize); }
ReactiveBatchProcessor { void start() { Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize); messageSource.getMessageBatches() .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor())) .doOnNext(batch -> logger.log(batch.toString())) .flatMap(batch -> Flowable.fromIterable(batch.getMessages())) .flatMapSingle(m -> Single.defer(() -> Single.just(m) .map(messageHandler::handleMessage)) .subscribeOn(scheduler)) .subscribeWith(new SimpleSubscriber<>(threads, 1)); } ReactiveBatchProcessor( MessageSource messageSource, MessageHandler messageHandler, int threads, int threadPoolQueueSize); }
ReactiveBatchProcessor { void start() { Scheduler scheduler = threadPoolScheduler(threads, threadPoolQueueSize); messageSource.getMessageBatches() .subscribeOn(Schedulers.from(Executors.newSingleThreadExecutor())) .doOnNext(batch -> logger.log(batch.toString())) .flatMap(batch -> Flowable.fromIterable(batch.getMessages())) .flatMapSingle(m -> Single.defer(() -> Single.just(m) .map(messageHandler::handleMessage)) .subscribeOn(scheduler)) .subscribeWith(new SimpleSubscriber<>(threads, 1)); } ReactiveBatchProcessor( MessageSource messageSource, MessageHandler messageHandler, int threads, int threadPoolQueueSize); }
@Test void test(){ IpAddressValidator validator = new IpAddressValidator(); assertTrue(validator.isValid("111.111.111.111", null)); assertFalse(validator.isValid("111.foo.111.111", null)); assertFalse(validator.isValid("111.111.256.111", null)); }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { Pattern pattern = Pattern.compile("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$"); Matcher matcher = pattern.matcher(value); try { if (!matcher.matches()) { return false; } else { for (int i = 1; i <= 4; i++) { int octet = Integer.valueOf(matcher.group(i)); if (octet > 255) { return false; } } return true; } } catch (Exception e) { return false; } }
IpAddressValidator implements ConstraintValidator<IpAddress, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { Pattern pattern = Pattern.compile("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$"); Matcher matcher = pattern.matcher(value); try { if (!matcher.matches()) { return false; } else { for (int i = 1; i <= 4; i++) { int octet = Integer.valueOf(matcher.group(i)); if (octet > 255) { return false; } } return true; } } catch (Exception e) { return false; } } }
IpAddressValidator implements ConstraintValidator<IpAddress, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { Pattern pattern = Pattern.compile("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$"); Matcher matcher = pattern.matcher(value); try { if (!matcher.matches()) { return false; } else { for (int i = 1; i <= 4; i++) { int octet = Integer.valueOf(matcher.group(i)); if (octet > 255) { return false; } } return true; } } catch (Exception e) { return false; } } }
IpAddressValidator implements ConstraintValidator<IpAddress, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { Pattern pattern = Pattern.compile("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$"); Matcher matcher = pattern.matcher(value); try { if (!matcher.matches()) { return false; } else { for (int i = 1; i <= 4; i++) { int octet = Integer.valueOf(matcher.group(i)); if (octet > 255) { return false; } } return true; } } catch (Exception e) { return false; } } @Override boolean isValid(String value, ConstraintValidatorContext context); }
IpAddressValidator implements ConstraintValidator<IpAddress, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { Pattern pattern = Pattern.compile("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$"); Matcher matcher = pattern.matcher(value); try { if (!matcher.matches()) { return false; } else { for (int i = 1; i <= 4; i++) { int octet = Integer.valueOf(matcher.group(i)); if (octet > 255) { return false; } } return true; } } catch (Exception e) { return false; } } @Override boolean isValid(String value, ConstraintValidatorContext context); }
@Test void whenInputIsInvalidForCreate_thenThrowsException() { InputWithCustomValidator input = validInput(); input.setId(42L); assertThrows(ConstraintViolationException.class, () -> { service.validateForCreate(input); }); }
@Validated(OnCreate.class) void validateForCreate(@Valid InputWithCustomValidator input){ }
ValidatingServiceWithGroups { @Validated(OnCreate.class) void validateForCreate(@Valid InputWithCustomValidator input){ } }
ValidatingServiceWithGroups { @Validated(OnCreate.class) void validateForCreate(@Valid InputWithCustomValidator input){ } }
ValidatingServiceWithGroups { @Validated(OnCreate.class) void validateForCreate(@Valid InputWithCustomValidator input){ } }
ValidatingServiceWithGroups { @Validated(OnCreate.class) void validateForCreate(@Valid InputWithCustomValidator input){ } }
@Test void whenInputIsInvalidForUpdate_thenThrowsException() { InputWithCustomValidator input = validInput(); input.setId(null); assertThrows(ConstraintViolationException.class, () -> { service.validateForUpdate(input); }); }
@Validated(OnUpdate.class) void validateForUpdate(@Valid InputWithCustomValidator input){ }
ValidatingServiceWithGroups { @Validated(OnUpdate.class) void validateForUpdate(@Valid InputWithCustomValidator input){ } }
ValidatingServiceWithGroups { @Validated(OnUpdate.class) void validateForUpdate(@Valid InputWithCustomValidator input){ } }
ValidatingServiceWithGroups { @Validated(OnUpdate.class) void validateForUpdate(@Valid InputWithCustomValidator input){ } }
ValidatingServiceWithGroups { @Validated(OnUpdate.class) void validateForUpdate(@Valid InputWithCustomValidator input){ } }
@Test void whenInputIsValid_thenThrowsNoException(){ Input input = new Input(); input.setNumberBetweenOneAndTen(5); input.setIpAddress("111.111.111.111"); service.validateInput(input); }
void validateInput(@Valid Input input){ }
ValidatingService { void validateInput(@Valid Input input){ } }
ValidatingService { void validateInput(@Valid Input input){ } }
ValidatingService { void validateInput(@Valid Input input){ } }
ValidatingService { void validateInput(@Valid Input input){ } }
@Test void whenInputIsInvalid_thenThrowsException(){ Input input = new Input(); input.setNumberBetweenOneAndTen(0); input.setIpAddress("invalid"); assertThrows(ConstraintViolationException.class, () -> { service.validateInput(input); }); }
void validateInput(@Valid Input input){ }
ValidatingService { void validateInput(@Valid Input input){ } }
ValidatingService { void validateInput(@Valid Input input){ } }
ValidatingService { void validateInput(@Valid Input input){ } }
ValidatingService { void validateInput(@Valid Input input){ } }
@Test public void logTrace() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.TRACE); logger.log(LogLevel.TRACE, "logger name", "trace message"); assertThat(capture.toString(), containsString("TRACE logger name - trace message")); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void logFatal() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.FATAL); logger.log(LogLevel.FATAL, "logger name", "fatal message"); assertThat(capture.toString(), containsString("ERROR logger name - fatal message")); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void logFatalError() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.FATAL); logger.log(LogLevel.FATAL, "logger name", "fatal message", new Exception("error message")); Pattern pattern = Pattern.compile("ERROR logger name - fatal message.*java.lang.Exception: error message", Pattern.DOTALL | Pattern.MULTILINE); assertTrue(pattern.matcher(capture.toString()).find()); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void logTraceErrorOff() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.OFF); logger.log(LogLevel.TRACE, "logger name", "trace message", new Exception("error message")); Pattern pattern = Pattern.compile("TRACE logger name - trace message.*java.lang.Exception: error message", Pattern.DOTALL | Pattern.MULTILINE); assertFalse(pattern.matcher(capture.toString()).find()); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void isLogTraceEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.TRACE); assertTrue(logger.isEnabled(LogLevel.TRACE, "logger name")); }
private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void isLogDebugEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.DEBUG); assertTrue(logger.isEnabled(LogLevel.DEBUG, "logger name")); }
private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void isLogInfoEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.INFO); assertTrue(logger.isEnabled(LogLevel.INFO, "logger name")); }
private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void isLogErrorEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.ERROR); assertTrue(logger.isEnabled(LogLevel.ERROR, "logger name")); }
private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void isLogFatalEnabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.FATAL); assertTrue(logger.isEnabled(LogLevel.FATAL, "logger name")); }
private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void isLogTraceDisabled() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.OFF); assertFalse(logger.isEnabled(LogLevel.TRACE, "logger name")); }
private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private boolean isEnabled(org.slf4j.Logger logger, LogLevel level) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: return logger.isTraceEnabled(); case DEBUG: return logger.isDebugEnabled(); case INFO: return logger.isInfoEnabled(); case WARN: return logger.isWarnEnabled(); case ERROR: case FATAL: return logger.isErrorEnabled(); default: throw new IllegalArgumentException("LogLevel must be one of the enabled levels."); } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void logTraceError() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.TRACE); logger.log(LogLevel.TRACE, "logger name", "trace message", new Exception("error message")); Pattern pattern = Pattern.compile("TRACE logger name - trace message.*java.lang.Exception: error message", Pattern.DOTALL | Pattern.MULTILINE); assertTrue(pattern.matcher(capture.toString()).find()); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void logDebug() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.DEBUG); logger.log(LogLevel.DEBUG, "logger name", "debug message"); assertThat(capture.toString(), containsString("DEBUG logger name - debug message")); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void logDebugError() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.DEBUG); logger.log(LogLevel.DEBUG, "logger name", "debug message", new Exception("error message")); Pattern pattern = Pattern.compile("DEBUG logger name - debug message.*java.lang.Exception: error message", Pattern.DOTALL | Pattern.MULTILINE); assertTrue(pattern.matcher(capture.toString()).find()); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void logInfo() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.INFO); logger.log(LogLevel.INFO, "logger name", "info message"); assertThat(capture.toString(), containsString("INFO logger name - info message")); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
@Test public void logInfoError() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.INFO); logger.log(LogLevel.INFO, "logger name", "info message", new Exception("error message")); Pattern pattern = Pattern.compile("INFO logger name - info message.*java.lang.Exception: error message", Pattern.DOTALL | Pattern.MULTILINE); assertTrue(pattern.matcher(capture.toString()).find()); }
private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }
Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); }