Search in sources :

Example 6 with EventKey

use of com.kloia.eventapis.common.EventKey in project eventapis by kloiasoft.

the class CompositeRepositoryImpl method recordAndPublishInternal.

private <P extends PublishedEvent, T extends Exception> EventKey recordAndPublishInternal(P publishedEvent, Optional<EventKey> previousEventKey, Function<EntityEvent, ConcurrencyResolver<T>> concurrencyResolverFactory) throws EventStoreException, T {
    long opDate = System.currentTimeMillis();
    EventKey eventKey = eventRecorder.recordEntityEvent(publishedEvent, opDate, previousEventKey, concurrencyResolverFactory);
    publishedEvent.setSender(eventKey);
    String event;
    try {
        event = objectMapper.writerWithView(Views.PublishedOnly.class).writeValueAsString(publishedEvent);
    } catch (JsonProcessingException e) {
        throw new EventStoreException(e.getMessage(), e);
    }
    operationRepository.publishEvent(publishedEvent.getClass().getSimpleName(), event, opDate);
    checkOperationFinalStates(publishedEvent);
    return publishedEvent.getSender();
}
Also used : EventStoreException(com.kloia.eventapis.exception.EventStoreException) Views(com.kloia.eventapis.api.Views) EventKey(com.kloia.eventapis.common.EventKey) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 7 with EventKey

use of com.kloia.eventapis.common.EventKey in project eventapis by kloiasoft.

the class CassandraEventRecorder method recordEntityEvent.

/*    private EntityEvent convertToEntityEvent(Row entityEventData) throws EventStoreException {
        EventKey eventKey = new EventKey(entityEventData.getString(ENTITY_ID), entityEventData.getInt(VERSION));
        String opId = entityEventData.getString(OP_ID);
        String eventData = entityEventData.getString("eventData");
        return new EntityEvent(eventKey, opId, entityEventData.getTimestamp(OP_DATE), entityEventData.getString("eventType"), entityEventData.getString("status"), eventData);
    }*/
// private ConcurrencyResolver concurrencyResolver = new DefaultConcurrencyResolver();
// private Function<E, ConcurrencyResolver> concurrencyResolverFactory;
@Override
public <T extends Exception> EventKey recordEntityEvent(RecordedEvent event, long opDate, Optional<EventKey> previousEventKey, Function<EntityEvent, ConcurrencyResolver<T>> concurrencyResolverFactory) throws EventStoreException, T {
    ConcurrencyResolver<T> concurrencyResolver = null;
    String eventData = null;
    try {
        eventData = objectMapper.writerWithView(Views.RecordedOnly.class).writeValueAsString(event);
    } catch (IllegalArgumentException | JsonProcessingException e) {
        throw new EventStoreException(e.getMessage(), e);
    }
    EventKey eventKey;
    if (previousEventKey.isPresent()) {
        eventKey = new EventKey(previousEventKey.get().getEntityId(), previousEventKey.get().getVersion() + 1);
    } else
        eventKey = new EventKey(idCreationStrategy.nextId(), 0);
    EntityEvent entityEvent = new EntityEvent(eventKey, operationContext.getContextOpId(), new Date(opDate), event.getEventName(), EventState.CREATED, userContext.getAuditInfo(), eventData);
    while (true) {
        Insert insert = createInsertQuery(entityEvent);
        log.debug("Recording Event: " + insert.toString());
        ResultSet resultSet = cassandraSession.execute(insert);
        log.debug("Recorded Event: " + resultSet.toString());
        if (resultSet.wasApplied()) {
            return entityEvent.getEventKey();
        } else {
            Row one = resultSet.one();
            log.warn("!wasApplied: " + one.getBool("[applied]"));
            if (concurrencyResolver == null)
                concurrencyResolver = concurrencyResolverFactory.apply(entityEvent);
            // go on or finish
            concurrencyResolver.tryMore();
            Select select = QueryBuilder.select().max(VERSION).from(tableName);
            select.where(QueryBuilder.eq(ENTITY_ID, entityEvent.getEventKey().getEntityId()));
            ResultSet execute = cassandraSession.execute(select);
            int lastVersion = execute.one().getInt(0);
            entityEvent.setEventKey(concurrencyResolver.calculateNext(entityEvent.getEventKey(), lastVersion));
        }
    }
}
Also used : EventStoreException(com.kloia.eventapis.exception.EventStoreException) Views(com.kloia.eventapis.api.Views) EventKey(com.kloia.eventapis.common.EventKey) Insert(com.datastax.driver.core.querybuilder.Insert) Date(java.util.Date) ResultSet(com.datastax.driver.core.ResultSet) Select(com.datastax.driver.core.querybuilder.Select) Row(com.datastax.driver.core.Row) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 8 with EventKey

use of com.kloia.eventapis.common.EventKey in project eventapis by kloiasoft.

the class CassandraViewQuery method convertToEntityEvent.

static EntityEvent convertToEntityEvent(Row entityEventData) {
    EventKey eventKey = new EventKey(entityEventData.getString(CassandraEventRecorder.ENTITY_ID), entityEventData.getInt(CassandraEventRecorder.VERSION));
    String opId = entityEventData.getString(CassandraEventRecorder.OP_ID);
    String eventData = entityEventData.getString(CassandraEventRecorder.EVENT_DATA);
    return new EntityEvent(eventKey, opId, entityEventData.getTimestamp(CassandraEventRecorder.OP_DATE), entityEventData.getString(CassandraEventRecorder.EVENT_TYPE), EventState.valueOf(entityEventData.getString(CassandraEventRecorder.STATUS)), entityEventData.getString(CassandraEventRecorder.AUDIT_INFO), eventData);
}
Also used : EventKey(com.kloia.eventapis.common.EventKey)

Example 9 with EventKey

use of com.kloia.eventapis.common.EventKey in project eventapis by kloiasoft.

the class StockReleasedEventHandler method execute.

@KafkaListener(topics = "StockReleasedEvent", containerFactory = "eventsKafkaListenerContainerFactory")
public EventKey execute(StockReleasedEvent dto) throws EventStoreException, ConcurrentEventException {
    Orders order = orderQuery.queryEntity(dto.getOrderId());
    if (order.getState() == OrderState.RELEASING_STOCK) {
        OrderCancelledEvent orderCancelledEvent = new OrderCancelledEvent();
        log.info("Payment is processing : " + dto);
        EventKey eventKey = eventRepository.recordAndPublish(order, orderCancelledEvent);
        paymentClient.returnPaymentCommand(order.getPaymentId(), new ReturnPaymentCommandDto(order.getId()));
        return eventKey;
    } else
        throw new EventStoreException("Order state is not valid for this Operation: " + dto);
}
Also used : Orders(com.kloia.sample.model.Orders) EventStoreException(com.kloia.eventapis.exception.EventStoreException) OrderCancelledEvent(com.kloia.sample.dto.event.OrderCancelledEvent) ReturnPaymentCommandDto(com.kloia.sample.dto.command.ReturnPaymentCommandDto) EventKey(com.kloia.eventapis.common.EventKey) KafkaListener(org.springframework.kafka.annotation.KafkaListener)

Example 10 with EventKey

use of com.kloia.eventapis.common.EventKey in project eventapis by kloiasoft.

the class CompositeRepositoryImplTest method shouldRecordAndPublishWithPreviousEventAndPublishedEventAndConcurrencyResolverFactory.

@Test
public void shouldRecordAndPublishWithPreviousEventAndPublishedEventAndConcurrencyResolverFactory() throws JsonProcessingException, EventStoreException, ConcurrentEventException {
    mockCommon(intermediateEvent);
    Entity previousEntity = mock(Entity.class);
    EventKey previousEntityEventKey = new EventKey();
    when(previousEntity.getEventKey()).thenReturn(previousEntityEventKey);
    ConcurrencyResolver concurrencyResolver = mock(ConcurrencyResolver.class);
    Function<EntityEvent, ConcurrencyResolver<ConcurrentEventException>> factory = entityEvent -> concurrencyResolver;
    EventKey actual = compositeRepository.recordAndPublish(previousEntity, intermediateEvent, factory);
    assertCommon(intermediateEvent);
    assertThat(actual, equalTo(eventKey));
    assertThat(previousEventKeyCaptor.getValue().isPresent(), equalTo(true));
    assertThat(previousEventKeyCaptor.getValue().get(), equalTo(previousEntityEventKey));
    assertThat(concurrencyResolverFactoryCaptor.getValue(), equalTo(factory));
}
Also used : ConcurrencyResolver(com.kloia.eventapis.cassandra.ConcurrencyResolver) SerializableConsumer(com.kloia.eventapis.kafka.SerializableConsumer) IdCreationStrategy(com.kloia.eventapis.api.IdCreationStrategy) Mock(org.mockito.Mock) EventKey(com.kloia.eventapis.common.EventKey) Entity(com.kloia.eventapis.view.Entity) DefaultConcurrencyResolver(com.kloia.eventapis.cassandra.DefaultConcurrencyResolver) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) EventRecorder(com.kloia.eventapis.common.EventRecorder) IOperationRepository(com.kloia.eventapis.kafka.IOperationRepository) Captor(org.mockito.Captor) Function(java.util.function.Function) Assert.assertThat(org.junit.Assert.assertThat) Mockito.doThrow(org.mockito.Mockito.doThrow) ArgumentCaptor(org.mockito.ArgumentCaptor) Matchers.eq(org.mockito.Matchers.eq) Map(java.util.Map) Matchers.anyLong(org.mockito.Matchers.anyLong) UUIDCreationStrategy(com.kloia.eventapis.api.impl.UUIDCreationStrategy) ExpectedException(org.junit.rules.ExpectedException) EventStoreException(com.kloia.eventapis.exception.EventStoreException) Before(org.junit.Before) InjectMocks(org.mockito.InjectMocks) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) PublishedEvent(com.kloia.eventapis.common.PublishedEvent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConcurrentEventException(com.kloia.eventapis.cassandra.ConcurrentEventException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Test(org.junit.Test) EventState(com.kloia.eventapis.pojos.EventState) Mockito.when(org.mockito.Mockito.when) EventType(com.kloia.eventapis.common.EventType) Mockito.verify(org.mockito.Mockito.verify) Rule(org.junit.Rule) MockitoJUnitRunner(org.mockito.runners.MockitoJUnitRunner) Views(com.kloia.eventapis.api.Views) Matchers.equalTo(org.hamcrest.Matchers.equalTo) EntityEvent(com.kloia.eventapis.cassandra.EntityEvent) Event(com.kloia.eventapis.pojos.Event) Optional(java.util.Optional) Mockito.mock(org.mockito.Mockito.mock) Entity(com.kloia.eventapis.view.Entity) ConcurrencyResolver(com.kloia.eventapis.cassandra.ConcurrencyResolver) DefaultConcurrencyResolver(com.kloia.eventapis.cassandra.DefaultConcurrencyResolver) EntityEvent(com.kloia.eventapis.cassandra.EntityEvent) EventKey(com.kloia.eventapis.common.EventKey) Test(org.junit.Test)

Aggregations

EventKey (com.kloia.eventapis.common.EventKey)11 DefaultConcurrencyResolver (com.kloia.eventapis.cassandra.DefaultConcurrencyResolver)5 EntityEvent (com.kloia.eventapis.cassandra.EntityEvent)5 EventStoreException (com.kloia.eventapis.exception.EventStoreException)5 Test (org.junit.Test)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 Views (com.kloia.eventapis.api.Views)4 Entity (com.kloia.eventapis.view.Entity)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)2 Command (com.kloia.eventapis.api.Command)2 IdCreationStrategy (com.kloia.eventapis.api.IdCreationStrategy)2 UUIDCreationStrategy (com.kloia.eventapis.api.impl.UUIDCreationStrategy)2 ConcurrencyResolver (com.kloia.eventapis.cassandra.ConcurrencyResolver)2 ConcurrentEventException (com.kloia.eventapis.cassandra.ConcurrentEventException)2 EventRecorder (com.kloia.eventapis.common.EventRecorder)2 EventType (com.kloia.eventapis.common.EventType)2 PublishedEvent (com.kloia.eventapis.common.PublishedEvent)2 IOperationRepository (com.kloia.eventapis.kafka.IOperationRepository)2 SerializableConsumer (com.kloia.eventapis.kafka.SerializableConsumer)2