Search in sources :

Example 6 with EventStoreException

use of com.kloia.eventapis.exception.EventStoreException 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 7 with EventStoreException

use of com.kloia.eventapis.exception.EventStoreException in project eventapis by kloiasoft.

the class CassandraViewQuery method queryEntityInternal.

private E queryEntityInternal(String entityId, Select select) throws EventStoreException {
    E initialInstance;
    E result = null;
    try {
        initialInstance = entityType.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        log.error(e.getMessage(), e);
        throw new EventStoreException(e);
    }
    List<Row> entityEventDatas = cassandraSession.execute(select, PagingIterable::all);
    for (Row entityEventData : entityEventDatas) {
        EntityEvent entityEvent = convertToEntityEvent(entityEventData);
        if (entityEvent.getStatus() == EventState.CREATED) {
            EntityFunctionSpec<E, ?> functionSpec = functionMap.get(entityEvent.getEventType());
            if (functionSpec != null) {
                EntityEventWrapper eventWrapper = new EntityEventWrapper<>(functionSpec.getQueryType(), objectMapper, entityEvent);
                EntityFunction<E, ?> entityFunction = functionSpec.getEntityFunction();
                result = (E) entityFunction.apply(result == null ? initialInstance : result, eventWrapper);
            } else
                log.trace("Function Spec is not available for " + entityEvent.getEventType() + " EntityId:" + entityId + " Table:" + tableName);
        }
        if (result != null) {
            result.setId(entityId);
            result.setVersion(entityEvent.getEventKey().getVersion());
        }
    }
    return (result == null || result.getId() == null) ? null : result;
}
Also used : EventStoreException(com.kloia.eventapis.exception.EventStoreException) PagingIterable(com.datastax.driver.core.PagingIterable) EntityEventWrapper(com.kloia.eventapis.view.EntityEventWrapper) Row(com.datastax.driver.core.Row)

Example 8 with EventStoreException

use of com.kloia.eventapis.exception.EventStoreException 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 9 with EventStoreException

use of com.kloia.eventapis.exception.EventStoreException in project eventapis by kloiasoft.

the class StockReservedEventHandler method execute.

@Override
@KafkaListener(topics = "StockReservedEvent", containerFactory = "eventsKafkaListenerContainerFactory")
public EventKey execute(StockReservedEvent dto) throws EventStoreException, ConcurrentEventException {
    Orders order = orderQuery.queryEntity(dto.getOrderId());
    if (order.getState() == OrderState.RESERVING_STOCK) {
        PaymentProcessEvent paymentProcessEvent = new PaymentProcessEvent(order.getId(), dto.getSender().getVersion(), new PaymentInformation(order.getPaymentAddress(), order.getAmount(), order.getCardInformation()));
        log.info("Payment is processing : " + dto);
        return eventRepository.recordAndPublish(order, paymentProcessEvent);
    } 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) PaymentProcessEvent(com.kloia.sample.dto.event.PaymentProcessEvent) PaymentInformation(com.kloia.sample.model.PaymentInformation) KafkaListener(org.springframework.kafka.annotation.KafkaListener)

Example 10 with EventStoreException

use of com.kloia.eventapis.exception.EventStoreException 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

EventStoreException (com.kloia.eventapis.exception.EventStoreException)10 EventKey (com.kloia.eventapis.common.EventKey)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 Views (com.kloia.eventapis.api.Views)4 Orders (com.kloia.sample.model.Orders)4 Row (com.datastax.driver.core.Row)2 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 DefaultConcurrencyResolver (com.kloia.eventapis.cassandra.DefaultConcurrencyResolver)2 EntityEvent (com.kloia.eventapis.cassandra.EntityEvent)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