Skip to content

Commit

Permalink
JAMES-2433 Implement EventStore for a JPA backend
Browse files Browse the repository at this point in the history
  • Loading branch information
amichair committed Oct 16, 2024
1 parent 5a62ece commit 3f8f587
Show file tree
Hide file tree
Showing 9 changed files with 617 additions and 0 deletions.
128 changes: 128 additions & 0 deletions event-sourcing/event-store-jpa/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.apache.james</groupId>
<artifactId>event-sourcing</artifactId>
<version>3.9.0-SNAPSHOT</version>
</parent>

<artifactId>event-sourcing-event-store-jpa</artifactId>

<name>Apache James :: Event sourcing :: Event Store :: JPA</name>
<description>JPA implementation for James Event Store</description>

<dependencies>
<dependency>
<groupId>${james.groupId}</groupId>
<artifactId>apache-james-backends-jpa</artifactId>
</dependency>
<dependency>
<groupId>${james.groupId}</groupId>
<artifactId>apache-james-backends-jpa</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${james.groupId}</groupId>
<artifactId>event-sourcing-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${james.groupId}</groupId>
<artifactId>event-sourcing-core</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${james.groupId}</groupId>
<artifactId>event-sourcing-event-store-api</artifactId>
</dependency>
<dependency>
<groupId>${james.groupId}</groupId>
<artifactId>event-sourcing-event-store-api</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${james.groupId}</groupId>
<artifactId>event-sourcing-pojo</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${james.groupId}</groupId>
<artifactId>testing-base</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>${apache.openjpa.version}</version>
<configuration>
<includes>org/apache/james/eventsourcing/eventstore/jpa/model/JPAEvent.class</includes>
<addDefaultConstructor>true</addDefaultConstructor>
<enforcePropertyRestrictions>true</enforcePropertyRestrictions>
<toolProperties>
<property>
<name>log</name>
<value>TOOL=TRACE</value>
</property>
<property>
<name>metaDataFactory</name>
<value>jpa(Types=org.apache.james.eventsourcing.eventstore.jpa.model.JPAEvent)</value>
</property>
</toolProperties>
<persistenceXmlFile>${basedir}/src/test/resources/persistence.xml</persistenceXmlFile>
</configuration>
<executions>
<execution>
<id>enhancer</id>
<goals>
<goal>enhance</goal>
</goals>
<phase>process-classes</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.eventsourcing.eventstore.jpa;


import static org.apache.james.eventsourcing.eventstore.jpa.model.JPAEvent.DELETE_AGGREGATE_QUERY;
import static org.apache.james.eventsourcing.eventstore.jpa.model.JPAEvent.SELECT_AGGREGATE_QUERY;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.PersistenceUnit;

import org.apache.james.backends.jpa.EntityManagerUtils;
import org.apache.james.eventsourcing.AggregateId;
import org.apache.james.eventsourcing.Event;
import org.apache.james.eventsourcing.eventstore.EventStore;
import org.apache.james.eventsourcing.eventstore.EventStoreFailedException;
import org.apache.james.eventsourcing.eventstore.History;
import org.apache.james.eventsourcing.eventstore.JsonEventSerializer;
import org.apache.james.eventsourcing.eventstore.jpa.model.JPAEvent;
import org.reactivestreams.Publisher;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;

import reactor.core.publisher.Mono;
import scala.collection.Iterable;


public class JPAEventStore implements EventStore {

/**
* The entity manager to access the database.
*/
private EntityManagerFactory entityManagerFactory;

/**
* The JSON serializer to serialize the event data.
*/
private JsonEventSerializer jsonEventSerializer;

/**
* Set the serializer to use.
*/
@Inject
public void setJsonEventSerializer(JsonEventSerializer jsonEventSerializer) {
this.jsonEventSerializer = jsonEventSerializer;
}

/**
* Set the entity manager to use.
*/
@Inject
@PersistenceUnit(unitName = "James")
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}

@Override
public Publisher<Void> appendAll(Iterable<Event> events) {
if (events.isEmpty()) {
return Mono.empty();
}
Preconditions.checkArgument(Event.belongsToSameAggregate(events));
AggregateId aggregateId = events.head().getAggregateId();
EntityManager entityManager = entityManagerFactory.createEntityManager();
final EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
events.foreach(e -> {
try {
JPAEvent jpaEvent = new JPAEvent(aggregateId, e.eventId(), jsonEventSerializer.serialize(e));
entityManager.persist(jpaEvent);
} catch (JsonProcessingException ex) {
throw new RuntimeException(ex);
}
return e;
});
transaction.commit();
} catch (PersistenceException e) {
if (transaction.isActive()) {
transaction.rollback();
}
EventStoreFailedException esfe = new EventStoreFailedException("Unable to add events");
esfe.initCause(e);
throw esfe;
} finally {
EntityManagerUtils.safelyClose(entityManager);
}
return Mono.empty();
}

@Override
@SuppressWarnings("unchecked")
public Publisher<History> getEventsOfAggregate(AggregateId aggregateId) {
Preconditions.checkNotNull(aggregateId);
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
List<Event> events = (List<Event>) entityManager.createNamedQuery(SELECT_AGGREGATE_QUERY)
.setParameter("aggregateId", aggregateId.asAggregateKey())
.getResultStream()
.map(e -> {
try {
return jsonEventSerializer.deserialize(((JPAEvent) e).getEvent());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
})
.collect(Collectors.toList());
return Mono.fromSupplier(() -> History.of(events.toArray(new Event[0])));
} catch (PersistenceException e) {
throw new RuntimeException("Unable to get events", e);
} finally {
EntityManagerUtils.safelyClose(entityManager);
}
}

@Override
public Publisher<Void> remove(AggregateId aggregateId) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
final EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
entityManager.createNamedQuery(DELETE_AGGREGATE_QUERY)
.setParameter("aggregateId", aggregateId.asAggregateKey())
.executeUpdate();
transaction.commit();
} catch (PersistenceException e) {
if (transaction.isActive()) {
transaction.rollback();
}
throw new RuntimeException("Unable to remove events", e);
} finally {
EntityManagerUtils.safelyClose(entityManager);
}
return Mono.empty();
}

@VisibleForTesting
protected void removeAll() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
final EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
entityManager.createQuery("DELETE FROM JPAEvent").executeUpdate();
transaction.commit();
} catch (PersistenceException e) {
throw new RuntimeException("Unable to clear table", e);
} finally {
EntityManagerUtils.safelyClose(entityManager);
}
}
}
Loading

0 comments on commit 3f8f587

Please sign in to comment.