Skip to content

Commit

Permalink
Update to use JDBC
Browse files Browse the repository at this point in the history
  • Loading branch information
aguibert committed Sep 13, 2019
1 parent bd67aac commit aff8fcc
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 88 deletions.
11 changes: 3 additions & 8 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
<groupId>org.microshed.boost.boosters</groupId>
<artifactId>jpa</artifactId>
</dependency>
<dependency>
<dependency>
<groupId>org.microshed.boost.boosters</groupId>
<artifactId>jdbc</artifactId>
</dependency>
Expand All @@ -95,8 +95,8 @@


<dependency>
<artifactId>microshed-testing-liberty</artifactId>
<groupId>com.github.microshed.microshed-testing</groupId>
<artifactId>microshed-testing-liberty</artifactId>
<version>v0.4-beta</version>
<scope>test</scope>
</dependency>
Expand All @@ -108,12 +108,6 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.eclipse.microprofile.sandbox</groupId>
<artifactId>system-test-testcontainers</artifactId>
<version>0.1-SNAPSHOT</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
Expand Down Expand Up @@ -183,6 +177,7 @@
<systemProperties>
<microshed_hostname>localhost</microshed_hostname>
<microshed_http_port>9080</microshed_http_port>
<WLP_USR_DIR>${project.build.directory}/liberty/wlp/usr</WLP_USR_DIR>
</systemProperties>
</configuration>
</execution>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,27 @@
*/
package org.eclipse.microprofile.system.test.app;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
//import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.PositiveOrZero;
import javax.validation.constraints.Size;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
Expand All @@ -41,63 +47,103 @@
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;


@Path("/people")
@ApplicationScoped
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class PersonService {

private final Map<Long, Person> personRepo = new HashMap<>();

@PersistenceContext(unitName = "person-unit")
EntityManager entityManager;

//@PostConstruct
@Resource
DataSource defaultDataSource;

@PostConstruct
public void initPeople() {
System.out.println("Seeding database with sample data");
try (Connection conn = defaultDataSource.getConnection()){
conn.prepareStatement("CREATE TABLE IF NOT EXISTS people (id bigint, name text, age integer)").execute();
} catch (SQLException e) {
e.printStackTrace(System.out);
}
createPerson("Sample Person A", 25);
createPerson("Sample Person B", 26);
createPerson("Sample Person B", 26);
}

@GET
public Collection<Person> getAllPeople() {
return personRepo.values();
public Collection<Person> getAllPeople(){
Set<Person> allPeople = new HashSet<>();

try (Connection conn = defaultDataSource.getConnection();
ResultSet rs = conn.prepareStatement("SELECT name, age, id FROM people").executeQuery()){
while (rs.next()) {
allPeople.add(new Person(rs.getString("name"),rs.getInt("age"),rs.getLong("id")));
}
return allPeople;
} catch (SQLException e) {
throw new InternalServerErrorException("Could not get all people", e);
}
}

@GET
@Path("/{personId}")
public Person getPerson(@PathParam("personId") long id) {
Person foundPerson = entityManager.find(Person.class, id);
if (foundPerson == null)
personNotFound(id);
return foundPerson;
try (Connection conn = defaultDataSource.getConnection();
ResultSet rs = conn.prepareStatement("SELECT name, age FROM people WHERE id = "+id).executeQuery()){
if (rs.next()) {
return new Person(rs.getString("name"),rs.getInt("age"),id);
}
throw new NotFoundException("Person with id " + id + " not found.");
} catch (SQLException e) {
throw new InternalServerErrorException("Could not get person", e);
}
}

@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
@QueryParam("age") @PositiveOrZero int age){
Person p = new Person(name, age);
entityManager.persist(p);
return p.id;

try (Connection conn = defaultDataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO people VALUES(?,?,?)")){
ps.setLong(1, p.id);
ps.setString(2, name);
ps.setInt(3, age);
ps.execute();
return p.id;
} catch (SQLException e) {
throw new InternalServerErrorException("Could not create new person", e);
}
}

@POST
@Path("/{personId}")
public void updatePerson(@PathParam("personId") long id, @Valid Person p) {
Person toUpdate = getPerson(id);
entityManager.merge(p);
try (Connection conn = defaultDataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("UPDATE people SET name = ?, age = ? WHERE id = ?")){
ps.setString(1, p.name);
ps.setInt(2, p.age);
ps.setLong(3, p.id);
if (ps.executeUpdate() > 0) {
return;
};
throw new NotFoundException("Person with id " + id + " not found.");
} catch (SQLException e) {
throw new InternalServerErrorException("Could not update person", e);
}
}

@DELETE
@Path("/{personId}")
public void removePerson(@PathParam("personId") long id) {
Person toDelete = getPerson(id);
entityManager.remove(toDelete);
}

private void personNotFound(long id) {
throw new NotFoundException("Person with id " + id + " not found.");
try (Connection conn = defaultDataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("DELETE FROM people WHERE id = ?")){
ps.setLong(1,id);
if (ps.executeUpdate() > 0) {
return;
};
throw new NotFoundException("Person with id " + id + " not found.");
} catch (SQLException e) {
throw new InternalServerErrorException("Could not delete person", e);
}
}

}
32 changes: 0 additions & 32 deletions src/main/resources/META-INF/persistence.xml

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,28 @@
*/
package org.eclipse.microprofile.system.test.app;

import org.eclipse.microprofile.system.test.SharedContainerConfiguration;
import org.microshed.testing.SharedContainerConfiguration;
import org.microshed.testing.testcontainers.MicroProfileApplication;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.containers.microprofile.MicroProfileApplication;
import org.testcontainers.junit.jupiter.Container;

public class AppContainerConfig implements SharedContainerConfiguration {

@Container
public static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>()
.withNetworkAliases("testpostgres")
.withDatabaseName("testdb");
.withDatabaseName("test")
.withExposedPorts(5432)
.withInitScript("init.sql");

@Container
public static MicroProfileApplication<?> app = new MicroProfileApplication<>()
public static MicroProfileApplication app = new MicroProfileApplication()
.withEnv("POSTGRES_HOSTNAME", "testpostgres")
.withEnv("POSTGRES_PORT", "5432")
.withEnv("boost_db_portNumber", "5432")
.withEnv("boost_db_databaseName", "test")
.withEnv("boost_db_username", "test")
.withEnv("boost_db_password", "test")
.withAppContextRoot("/myservice");
//.dependsOn(postgres); intermittent bugs, see: https://github.com/testcontainers/testcontainers-java/issues/1722

@Override
public void startContainers() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,31 +22,21 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.eclipse.microprofile.system.test.SharedContainerConfig;


import java.util.Collection;

import javax.inject.Inject;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;

import org.eclipse.microprofile.system.test.app.Person;
import org.eclipse.microprofile.system.test.app.PersonService;
import org.junit.jupiter.api.Test;
import org.microshed.testing.SharedContainerConfig;
import org.microshed.testing.jupiter.MicroShedTest;
import org.microshed.testing.testcontainers.MicroProfileApplication;
import org.testcontainers.junit.jupiter.Container;

@MicroShedTest
@SharedContainerConfig(AppContainerConfig.class)
public class JaxrsJsonIT {

@Container
public static MicroProfileApplication app = new MicroProfileApplication()
.withAppContextRoot("/myservice")
.withReadinessPath("/myservice/people");

@Inject
public static PersonService personSvc;

Expand Down
1 change: 1 addition & 0 deletions src/test/resources/init.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CREATE TABLE IF NOT EXISTS people (id bigint, name text, age integer)
2 changes: 1 addition & 1 deletion src/test/resources/log4j.properties
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%r %p %c %x - %m%n

log4j.logger.org.eclipse.microprofile.system.test=DEBUG
log4j.logger.org.microshed=DEBUG

0 comments on commit aff8fcc

Please sign in to comment.