Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to use JDBC #14

Merged
merged 8 commits into from Sep 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Expand Up @@ -11,5 +11,5 @@ before_install:

install: true

script: mvn install
script: mvn install -DboostRuntime=ol -Dboost.db.serverName=localhost -Dboost.db.portNumber=5432 -Dboost.db.password=test -Dboost.db.databaseName=test -Dboost.db.user=test

2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -95,7 +95,7 @@ import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;

5. Disconnect the debugger.

#### JPA support with Boost
#### Database support with Boost

1. ...

Expand Down
34 changes: 29 additions & 5 deletions pom.xml
Expand Up @@ -79,11 +79,25 @@
<groupId>org.microshed.boost.boosters</groupId>
<artifactId>bean-validation</artifactId>
</dependency>
<dependency>
<groupId>org.microshed.boost.boosters</groupId>
<artifactId>jpa</artifactId>
</dependency>
<dependency>
<groupId>org.microshed.boost.boosters</groupId>
<artifactId>jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.6</version>
</dependency>


<dependency>
<artifactId>microshed-testing-liberty</artifactId>
<groupId>com.github.microshed.microshed-testing</groupId>
<artifactId>microshed-testing-liberty</artifactId>
<version>v0.4-beta</version>
<version>0.4.1-beta</version>
<scope>test</scope>
</dependency>

Expand All @@ -93,6 +107,14 @@
<version>5.4.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.12.1</version>
<scope>test</scope>
</dependency>

</dependencies>

<build>
Expand All @@ -106,10 +128,11 @@
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<!-- Allows plugin prefix, e.g. `mvn liberty:dev` -->
<plugin>
<groupId>io.openliberty.tools</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>3.0</version>
<groupId>io.openliberty.tools</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>3.0.1</version>
</plugin>
<plugin>
<groupId>org.microshed.boost</groupId>
Expand Down Expand Up @@ -154,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
Expand Up @@ -18,19 +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.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 @@ -45,57 +53,97 @@
@Consumes(MediaType.APPLICATION_JSON)
public class PersonService {

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

//@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 = personRepo.get(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);
personRepo.put(p.id, 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);
if (toUpdate == null)
personNotFound(id);
personRepo.put(id, 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 = personRepo.get(id);
if (toDelete == null)
personNotFound(id);
personRepo.remove(id);
}

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);
}
}

}
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2019 IBM Corporation and others
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed 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.eclipse.microprofile.system.test.app;

import org.microshed.testing.SharedContainerConfiguration;
import org.microshed.testing.testcontainers.MicroProfileApplication;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;

public class AppContainerConfig implements SharedContainerConfiguration {

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

@Container
public static MicroProfileApplication app = new MicroProfileApplication()
.withEnv("POSTGRES_HOSTNAME", "testpostgres")
.withEnv("boost_db_portNumber", "5432")
.withEnv("boost_db_databaseName", "test")
.withEnv("boost_db_username", "test")
.withEnv("boost_db_password", "test")
.withAppContextRoot("/myservice");

@Override
public void startContainers() {
postgres.start();
app.start();
}

}
Expand Up @@ -29,21 +29,14 @@
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
@@ -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
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