Skip to content
This repository has been archived by the owner on Aug 13, 2020. It is now read-only.

Commit

Permalink
Support pojo in enveloper
Browse files Browse the repository at this point in the history
  • Loading branch information
mapingo committed Mar 27, 2018
1 parent 45912cb commit c460325
Show file tree
Hide file tree
Showing 12 changed files with 117 additions and 126 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@
@ApplicationScoped
public class DefaultEnveloper implements Enveloper {

static Clock clock;
//TODO: Take a look at the setting of clock and objectToJsonValueConverter
private Clock clock;

static ObjectToJsonValueConverter objectToJsonValueConverter;
private ObjectToJsonValueConverter objectToJsonValueConverter;

public DefaultEnveloper() {
}
Expand All @@ -68,23 +69,23 @@ public void register(@Observes final EventFoundEvent event) {
}

public Function<Object, JsonEnvelope> withMetadataFrom(final JsonEnvelope envelope) {
return x -> envelopeFrom(buildMetaData(x, envelope.metadata()), objectToJsonValueConverter.convert(x));
return x -> envelopeFrom(buildMetaData(x, envelope.metadata(), clock), objectToJsonValueConverter.convert(x));
}

public Function<Object, JsonEnvelope> withMetadataFrom(final JsonEnvelope envelope, final String name) {
return x -> envelopeFrom(buildMetaData(envelope.metadata(), name), x == null ? JsonValue.NULL : objectToJsonValueConverter.convert(x));
return x -> envelopeFrom(buildMetaData(envelope.metadata(), name, clock), x == null ? JsonValue.NULL : objectToJsonValueConverter.convert(x));
}

public Function<Object, JsonEnvelope> toEnvelopeWithMetadataFrom(final Envelope<?> envelope) {
return x -> envelopeFrom(buildMetaData(x, envelope.metadata()), objectToJsonValueConverter.convert(envelope.payload()));
return x -> envelopeFrom(buildMetaData(x, envelope.metadata(), clock), objectToJsonValueConverter.convert(x));
}

public <T> EnveloperBuilder<T> envelop(final T payload) {
return new DefaultEnveloperBuilder<T>(payload);

}

private static Metadata buildMetaData(final Object eventObject, final Metadata metadata) {
private static Metadata buildMetaData(final Object eventObject, final Metadata metadata, final Clock clock) {
if (eventObject == null) {
throw new IllegalArgumentException("Event object should not be null");
}
Expand All @@ -93,10 +94,10 @@ private static Metadata buildMetaData(final Object eventObject, final Metadata m
throw new InvalidEventException(format("Failed to map event. No event registered for %s", eventObject.getClass()));
}

return buildMetaData(metadata, eventMap.get(eventObject.getClass()));
return buildMetaData(metadata, eventMap.get(eventObject.getClass()), clock);
}

private static Metadata buildMetaData(final Metadata metadata, final String name) {
private static Metadata buildMetaData(final Metadata metadata, final String name, final Clock clock) {

JsonObjectBuilder metadataBuilder = JsonObjects.createObjectBuilderWithFilter(metadata.asJsonObject(),
x -> !Arrays.asList(ID, NAME, CAUSATION, STREAM).contains(x));
Expand All @@ -112,7 +113,7 @@ private static Metadata buildMetaData(final Metadata metadata, final String name
}

private static JsonArray createCausation(final Metadata metadata) {
JsonArrayBuilder causation = Json.createArrayBuilder();
final JsonArrayBuilder causation = Json.createArrayBuilder();
if (metadata.asJsonObject().containsKey(CAUSATION)) {
metadata.asJsonObject().getJsonArray(CAUSATION).forEach(causation::add);
}
Expand All @@ -121,7 +122,7 @@ private static JsonArray createCausation(final Metadata metadata) {
return causation.build();
}

private static class DefaultEnveloperBuilder<T> implements EnveloperBuilder {
private class DefaultEnveloperBuilder<T> implements EnveloperBuilder {

private String name;
private T payload;
Expand All @@ -142,7 +143,7 @@ public EnveloperBuilder withName(final String name) {

@Override
public Envelope withMetadataFrom(final Envelope envelope) {
return new DefaultEnvelope(buildMetaData(envelope.metadata(), this.name), this.payload);
return new DefaultEnvelope(buildMetaData(envelope.metadata(), this.name, clock), this.payload);
}

}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package uk.gov.justice.services.core.enveloper.spi;

import static javax.enterprise.inject.spi.CDI.current;

import uk.gov.justice.services.common.converter.ObjectToJsonValueConverter;
import uk.gov.justice.services.common.converter.jackson.ObjectMapperProducer;
import uk.gov.justice.services.common.util.UtcClock;
import uk.gov.justice.services.core.enveloper.DefaultEnveloper;
import uk.gov.justice.services.core.enveloper.Enveloper;
import uk.gov.justice.services.messaging.Envelope;
Expand All @@ -9,14 +14,39 @@

public class DefaultEnveloperProvider implements EnveloperProvider {

private DefaultEnveloper defaultEnveloper;

@Override
public <T> Enveloper.EnveloperBuilder<T> envelop(final T payload) {
return new DefaultEnveloper().envelop(payload);
return getDefaultEnveloper().envelop(payload);
}

@Override
public Function<Object, JsonEnvelope> toEnvelopeWithMetadataFrom(final Envelope<?> envelope) {
return new DefaultEnveloper().toEnvelopeWithMetadataFrom(envelope);
return getDefaultEnveloper().toEnvelopeWithMetadataFrom(envelope);
}

private DefaultEnveloper getDefaultEnveloper() {

if (defaultEnveloper == null) {
if (isCdiAvailable()) {
defaultEnveloper = current().select(DefaultEnveloper.class).get();
} else {
defaultEnveloper = new DefaultEnveloper(new UtcClock(), new ObjectToJsonValueConverter(new ObjectMapperProducer().objectMapper()));
}
}

return defaultEnveloper;
}

private boolean isCdiAvailable() {

try {
current();
} catch (IllegalStateException e) {
return false;
}

return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.function.Function;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.openejb.OpenEjbContainer;
import org.junit.Before;
import org.junit.Test;

Expand All @@ -32,9 +33,11 @@ public class DefaultEnveloperProviderTest {

@Before
public void setup() throws JsonProcessingException {
OpenEjbContainer.createEJBContainer();
enveloper = new DefaultEnveloper(
new UtcClock(),
new ObjectToJsonValueConverter(new ObjectMapperProducer().objectMapper()));

}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import uk.gov.justice.services.core.enveloper.Enveloper;
import uk.gov.justice.services.eventsourcing.source.core.EventSource;
import uk.gov.justice.services.eventsourcing.source.core.EventStream;
import uk.gov.justice.services.eventsourcing.source.core.Tolerance;
import uk.gov.justice.services.eventsourcing.source.core.exception.EventStreamException;
import uk.gov.justice.services.example.cakeshop.domain.aggregate.Recipe;
import uk.gov.justice.services.messaging.JsonEnvelope;
Expand All @@ -35,9 +34,6 @@ public class MakeCakeCommandHandler {
@Inject
AggregateService aggregateService;

@Inject
Enveloper enveloper;

@Handles("example.command.make-cake")
public void makeCake(final JsonEnvelope command) throws EventStreamException {
LOGGER.info("=============> Inside make-cake Command Handler");
Expand All @@ -51,9 +47,7 @@ public void makeCake(final JsonEnvelope command) throws EventStreamException {

eventStream.append(
recipe.makeCake(cakeId)
.map(enveloper.withMetadataFrom(command)),
Tolerance.CONSECUTIVE);

.map(Enveloper.toEnvelopeWithMetadataFrom(command)));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import static org.slf4j.LoggerFactory.getLogger;
import static uk.gov.justice.services.core.annotation.Component.COMMAND_HANDLER;
import static uk.gov.justice.services.core.enveloper.Enveloper.toEnvelopeWithMetadataFrom;
import static uk.gov.justice.services.eventsourcing.source.core.Events.streamOf;

import uk.gov.justice.services.core.annotation.Handles;
import uk.gov.justice.services.core.annotation.ServiceComponent;
import uk.gov.justice.services.core.enveloper.Enveloper;
import uk.gov.justice.services.eventsourcing.source.core.EventSource;
import uk.gov.justice.services.eventsourcing.source.core.exception.EventStreamException;
import uk.gov.justice.services.messaging.JsonEnvelope;
Expand All @@ -30,9 +30,6 @@ public class OrderCakeCommandHandler {
@Inject
EventFactory eventFactory;

@Inject
Enveloper enveloper;

@Handles("example.command.order-cake")
public void handle(final JsonEnvelope command) throws EventStreamException {

Expand All @@ -42,7 +39,7 @@ public void handle(final JsonEnvelope command) throws EventStreamException {

final Stream<Object> events = streamOf(eventFactory.cakeOrderedEventFrom(command));

eventSource.getStreamById(streamId).append(events.map(enveloper.withMetadataFrom(command)));
eventSource.getStreamById(streamId).append(events.map(toEnvelopeWithMetadataFrom(command)));

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import uk.gov.justice.services.core.aggregate.AggregateService;
import uk.gov.justice.services.core.annotation.Handles;
import uk.gov.justice.services.core.annotation.ServiceComponent;
import uk.gov.justice.services.core.enveloper.Enveloper;
import uk.gov.justice.services.eventsourcing.source.core.EventSource;
import uk.gov.justice.services.eventsourcing.source.core.EventStream;
import uk.gov.justice.services.eventsourcing.source.core.Tolerance;
Expand Down Expand Up @@ -44,9 +43,6 @@ public class RecipeCommandHandler {
@Inject
AggregateService aggregateService;

@Inject
Enveloper enveloper;

@Handles("example.command.add-recipe")
public void addRecipe(final JsonEnvelope command) throws EventStreamException {
LOGGER.trace("=============> Inside add-recipe Command Handler. RecipeId: " + command.payloadAsJsonObject().getString(FIELD_RECIPE_ID));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,38 @@
import static com.jayway.jsonpath.matchers.JsonPathMatchers.withJsonPath;
import static java.util.Collections.EMPTY_LIST;
import static java.util.UUID.randomUUID;
import static javax.json.Json.createObjectBuilder;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static uk.gov.justice.services.core.annotation.Component.COMMAND_HANDLER;
import static uk.gov.justice.services.messaging.JsonEnvelope.envelopeFrom;
import static uk.gov.justice.services.test.utils.core.enveloper.EnveloperFactory.createEnveloperWithEvents;
import static uk.gov.justice.services.test.utils.core.matchers.EventStreamMatcher.eventStreamAppendedWith;
import static uk.gov.justice.services.test.utils.core.matchers.HandlerMatcher.isHandler;
import static uk.gov.justice.services.test.utils.core.matchers.HandlerMethodMatcher.method;
import static uk.gov.justice.services.test.utils.core.matchers.JsonEnvelopeMatcher.jsonEnvelope;
import static uk.gov.justice.services.test.utils.core.matchers.JsonEnvelopeMetadataMatcher.withMetadataEnvelopedFrom;
import static uk.gov.justice.services.test.utils.core.matchers.JsonEnvelopePayloadMatcher.payloadIsJson;
import static uk.gov.justice.services.test.utils.core.matchers.JsonEnvelopeStreamMatcher.streamContaining;
import static uk.gov.justice.services.test.utils.core.messaging.JsonEnvelopeBuilder.envelope;
import static uk.gov.justice.services.test.utils.core.messaging.MetadataBuilderFactory.metadataWithRandomUUID;
import static uk.gov.justice.services.test.utils.core.messaging.MetadataBuilderFactory.metadataOf;

import uk.gov.justice.services.core.aggregate.AggregateService;
import uk.gov.justice.services.core.enveloper.Enveloper;
import uk.gov.justice.services.core.enveloper.Enveloper;
import uk.gov.justice.services.eventsourcing.source.core.EventSource;
import uk.gov.justice.services.eventsourcing.source.core.EventStream;
import uk.gov.justice.services.eventsourcing.source.core.Tolerance;
import uk.gov.justice.services.example.cakeshop.domain.aggregate.Recipe;
import uk.gov.justice.services.example.cakeshop.domain.event.CakeMade;
import uk.gov.justice.services.example.cakeshop.domain.event.RecipeAdded;
import uk.gov.justice.services.messaging.JsonEnvelope;

import java.util.UUID;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
Expand All @@ -58,12 +54,14 @@ public class MakeCakeCommandHandlerTest {
@Mock
private AggregateService aggregateService;

@Spy
private Enveloper enveloper = createEnveloperWithEvents(CakeMade.class);

@InjectMocks
private MakeCakeCommandHandler makeCakeCommandHandler;

@Before
public void setup() throws Exception {
createEnveloperWithEvents(CakeMade.class);
}

@Test
public void shouldHaveCorrectHandlesAnnotation() throws Exception {
assertThat(makeCakeCommandHandler, isHandler(COMMAND_HANDLER)
Expand All @@ -73,22 +71,24 @@ public void shouldHaveCorrectHandlesAnnotation() throws Exception {
@Test
public void shouldHandleMakeCakeCommand() throws Exception {

when(eventSource.getStreamById(RECIPE_ID)).thenReturn(eventStream);
final Recipe recipe = new Recipe();
final String cakeName = "Chocolate cake";
recipe.apply(new RecipeAdded(RECIPE_ID, cakeName, false, EMPTY_LIST));

when(eventSource.getStreamById(RECIPE_ID)).thenReturn(eventStream);
when(aggregateService.get(eventStream, Recipe.class)).thenReturn(recipe);

final JsonEnvelope command = envelope()
.with(metadataWithRandomUUID(COMMAND_NAME))
.withPayloadOf(CAKE_ID, "cakeId")
.withPayloadOf(RECIPE_ID, "recipeId")
.build();
final JsonEnvelope command = envelopeFrom(
metadataOf(randomUUID(), COMMAND_NAME),
createObjectBuilder()
.add("recipeId", RECIPE_ID.toString())
.add("cakeId", CAKE_ID.toString())
.build());

makeCakeCommandHandler.makeCake(command);

verify(eventStream).append(
argThat(streamContaining(
assertThat(eventStream, eventStreamAppendedWith(
streamContaining(
jsonEnvelope(
withMetadataEnvelopedFrom(command)
.withName(EVENT_NAME),
Expand All @@ -97,7 +97,7 @@ public void shouldHandleMakeCakeCommand() throws Exception {
withJsonPath("$.name", equalTo(cakeName))
)))
.thatMatchesSchema()
)), eq(Tolerance.CONSECUTIVE));
)));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
import static uk.gov.justice.services.test.utils.core.messaging.MetadataBuilderFactory.metadataWithRandomUUID;

import uk.gov.justice.services.core.aggregate.AggregateService;
import uk.gov.justice.services.core.enveloper.Enveloper;
import uk.gov.justice.services.core.enveloper.Enveloper;
import uk.gov.justice.services.eventsourcing.source.core.EventSource;
import uk.gov.justice.services.eventsourcing.source.core.EventStream;
import uk.gov.justice.services.example.cakeshop.domain.event.CakeOrdered;
Expand All @@ -29,11 +27,11 @@
import java.time.ZonedDateTime;
import java.util.UUID;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
Expand All @@ -56,12 +54,14 @@ public class OrderCakeCommandHandlerTest {
@Mock
private EventFactory eventFactory;

@Spy
private Enveloper enveloper = createEnveloperWithEvents(CakeOrdered.class);

@InjectMocks
private OrderCakeCommandHandler orderCakeCommandHandler;

@Before
public void setup() throws Exception {
createEnveloperWithEvents(CakeOrdered.class);
}

@Test
public void shouldHaveCorrectHandlesAnnotation() throws Exception {
assertThat(orderCakeCommandHandler, isHandler(COMMAND_HANDLER)
Expand Down
Loading

0 comments on commit c460325

Please sign in to comment.