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

4.x: Fix Mongo Dbclient + related example #8130

Merged
merged 2 commits into from
Dec 19, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,8 @@ private static CharClass charClass(char c) {
},
// Transitions from STRING state
{
//LETTER: regular part of the JSON string, keep processing it
State.STRING,
// NUMBER: regular part of the JSON string, keep processing it
State.STRING,
// QUOTE: end of JSON string processing, go back to STATEMENT state
Expand Down
11 changes: 11 additions & 0 deletions dependencies/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@
<version.lib.slf4j>2.0.9</version.lib.slf4j>
<version.lib.smallrye-openapi>3.3.4</version.lib.smallrye-openapi>
<version.lib.snakeyaml>2.0</version.lib.snakeyaml>
<version.lib.testcontainers>1.19.3</version.lib.testcontainers>
<version.lib.typesafe-config>1.4.2</version.lib.typesafe-config>
<version.lib.tyrus>2.1.4</version.lib.tyrus>
<version.lib.weld-api>5.0.SP3</version.lib.weld-api>
Expand Down Expand Up @@ -1265,6 +1266,16 @@
<artifactId>hamcrest-core</artifactId>
<version>${version.lib.hamcrest}</version>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${version.lib.testcontainers}</version>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mongodb</artifactId>
<version>${version.lib.testcontainers}</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-kahadb-store</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ private void getPokemon(ServerRequest req, ServerResponse res) {
private void listPokemons(ServerRequest req, ServerResponse res) {
res.send(dbClient.execute()
.namedQuery("select-all")
.map(it -> it.as(JsonObject.class)));
.map(it -> it.as(JsonObject.class))
.toList());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion examples/dbclient/mongodb/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ The query operation adds database trace.
`curl` commands:

- `curl http://localhost:8079/db` - list all Pokemon in the database
- `curl -i -X PUT -d '{"name":"Squirtle","type":"water"}' http://localhost:8079/db` - add a new pokemon
- `curl -i -X PUT -H 'Content-type: application/json' -d '{"name":"Squirtle","type":"water"}' http://localhost:8079/db` - add a new pokemon
- `curl http://localhost:8079/db/Squirtle` - get a single pokemon
- `curl -i -X DELETE http://localhost:8079/db/Squirtle` - delete a single pokemon
- `curl -i -X DELETE http://localhost:8079/db` - delete all pokemon
Expand Down
32 changes: 32 additions & 0 deletions examples/dbclient/mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,26 @@
<artifactId>helidon-examples-dbclient-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.helidon.logging</groupId>
<artifactId>helidon-logging-jul</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mongodb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.webserver.testing.junit5</groupId>
<artifactId>helidon-webserver-testing-junit5</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand All @@ -118,6 +138,18 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import io.helidon.dbclient.tracing.DbClientTracing;
import io.helidon.logging.common.LogConfig;
import io.helidon.webserver.WebServer;
import io.helidon.webserver.WebServerConfig;
import io.helidon.webserver.http.HttpRouting;

/**
Expand Down Expand Up @@ -55,17 +56,20 @@ static WebServer startServer() {
// load logging configuration
LogConfig.configureRuntime();

WebServer server = setupServer(WebServer.builder());

System.out.println("WEB server is up! http://localhost:" + server.port() + "/");
return server;
}

static WebServer setupServer(WebServerConfig.Builder builder) {
// By default, this will pick up application.yaml from the classpath
Config config = Config.create();

WebServer server = WebServer.builder()
.routing(routing -> routing(routing, config))
return builder.routing(routing -> routing(routing, config))
.config(config.get("server"))
.build()
.start();

System.out.println("WEB server is up! http://localhost:" + server.port() + "/");
return server;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/*
* Copyright (c) 2023 Oracle and/or its affiliates.
*
* 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 io.helidon.examples.dbclient.mongo;

import java.util.List;
import java.util.Map;

import io.helidon.config.Config;
import io.helidon.http.Status;
import io.helidon.http.media.jsonb.JsonbSupport;
import io.helidon.http.media.jsonp.JsonpSupport;
import io.helidon.webclient.api.ClientResponseTyped;
import io.helidon.webclient.api.WebClient;
import io.helidon.webserver.WebServer;

import jakarta.json.Json;
import jakarta.json.JsonArray;
import jakarta.json.JsonBuilderFactory;
import jakarta.json.JsonObject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.MongoDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

@Testcontainers(disabledWithoutDocker = true)
public class MainIT {

@Container
static final MongoDBContainer container = new MongoDBContainer("mongo")
.withExposedPorts(27017);

private static final JsonBuilderFactory JSON_FACTORY = Json.createBuilderFactory(Map.of());
private static final String CONNECTION_URL_KEY = "db.connection.url";

private static WebServer server;
private static WebClient client;

@BeforeAll
static void beforeAll() {
String url = String.format("mongodb://127.0.0.1:%s/pokemon", container.getMappedPort(27017));
System.setProperty(CONNECTION_URL_KEY, url);
server = MongoDbExampleMain.setupServer(WebServer.builder());
client = WebClient.create(config -> config.baseUri("http://localhost:" + server.port())
.addMediaSupport(JsonbSupport.create(Config.create()))
.addMediaSupport(JsonpSupport.create()));
}

@AfterAll
static void afterAll() {
if (server != null && server.isRunning()) {
server.stop();
}
System.clearProperty(CONNECTION_URL_KEY);
}

@Test
void testListAndDeleteAllPokemons() {
List<String> names = listAllPokemons();
assertThat(names.isEmpty(), is(true));

String endpoint = String.format("/db/%s/type/%s", "Raticate", 1);
ClientResponseTyped<String> response = client.post(endpoint).request(String.class);
assertThat(response.status(), is(Status.OK_200));

names = listAllPokemons();
assertThat(names.size(), is(1));
assertThat(names.getFirst(), is("Raticate"));

response = client.delete("/db").request(String.class);
assertThat(response.status(), is(Status.OK_200));

names = listAllPokemons();
assertThat(names.isEmpty(), is(true));
}

@Test
void testAddUpdateDeletePokemon() {
ClientResponseTyped<String> response;
ClientResponseTyped<JsonObject> jsonResponse;
JsonObject pokemon = JSON_FACTORY.createObjectBuilder()
.add("type", 1)
.add("name", "Raticate")
.build();

// Add new pokemon
response = client.put("/db").submit(pokemon, String.class);
assertThat(response.entity(), is("Inserted: 1 values"));

// Get the new pokemon added
jsonResponse = client.get("/db/Raticate").request(JsonObject.class);
assertThat(jsonResponse.status(), is(Status.OK_200));
assertThat(jsonResponse.entity().getString("_id"), is("Raticate"));
assertThat(jsonResponse.entity().getString("type"), is("1"));

// Update pokemon
response = client.put("/db/Raticate/type/2").request(String.class);
assertThat(response.status(), is(Status.OK_200));

// Verify updated pokemon
jsonResponse = client.get("/db/Raticate").request(JsonObject.class);
assertThat(jsonResponse.status(), is(Status.OK_200));
assertThat(jsonResponse.entity().getString("_id"), is("Raticate"));
assertThat(jsonResponse.entity().getString("type"), is("2"));

// Delete Pokemon
response = client.delete("/db/Raticate").request(String.class);
assertThat(response.status(), is(Status.OK_200));

// Verify pokemon is correctly deleted
response = client.get("/db/Raticate").request(String.class);
assertThat(response.status(), is(Status.NOT_FOUND_404));
}

private List<String> listAllPokemons() {
ClientResponseTyped<JsonArray> response = client.get("/db").request(JsonArray.class);
assertThat(response.status(), is(Status.OK_200));
return response.entity().stream().map(e -> e.asJsonObject().getString("_id")).toList();
}
}
4 changes: 2 additions & 2 deletions examples/dbclient/pokemons/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,10 @@ curl http://localhost:8080/db/pokemon/2
curl http://localhost:8080/db/pokemon/name/Squirtle

# Add a new Pokémon Rattata
curl -i -X POST -d '{"id":7,"name":"Rattata","idType":1}' http://localhost:8080/db/pokemon
curl -i -X POST -H 'Content-type: application/json' -d '{"id":7,"name":"Rattata","idType":1}' http://localhost:8080/db/pokemon

# Rename Pokémon with id 7 to Raticate
curl -i -X PUT -d '{"id":7,"name":"Raticate","idType":2}' http://localhost:8080/db/pokemon
curl -i -X PUT -H 'Content-type: application/json' -d '{"id":7,"name":"Raticate","idType":2}' http://localhost:8080/db/pokemon

# Delete Pokémon with id 7
curl -i -X DELETE http://localhost:8080/db/pokemon/7
Expand Down
26 changes: 26 additions & 0 deletions examples/dbclient/pokemons/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,25 @@
<groupId>io.helidon.http.media</groupId>
<artifactId>helidon-http-media-jsonb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.logging</groupId>
<artifactId>helidon-logging-jul</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mongodb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.webclient</groupId>
<artifactId>helidon-webclient</artifactId>
Expand Down Expand Up @@ -158,6 +172,18 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import io.helidon.dbclient.health.DbClientHealthCheck;
import io.helidon.logging.common.LogConfig;
import io.helidon.webserver.WebServer;
import io.helidon.webserver.WebServerConfig;
import io.helidon.webserver.http.HttpRouting;
import io.helidon.webserver.observe.ObserveFeature;
import io.helidon.webserver.observe.health.HealthObserver;
Expand Down Expand Up @@ -73,25 +74,29 @@ private static void startServer() {
Config config = mongo ? Config.create(ConfigSources.classpath(MONGO_CFG)) : Config.create();
Config.global(config);

WebServer server = setupServer(WebServer.builder());

System.out.println("WEB server is up! http://localhost:" + server.port() + "/");
}

static WebServer setupServer(WebServerConfig.Builder builder) {

Config config = Config.global();
// Client services are added through a service loader - see mongoDB example for explicit services
DbClient dbClient = DbClient.create(config.get("db"));
Contexts.globalContext().register(dbClient);

ObserveFeature observe = ObserveFeature.builder()
.config(config.get("server.features.observe"))
.addObserver(HealthObserver.builder()
.addCheck(DbClientHealthCheck.create(dbClient, config.get("db.health-check")))
.build())
.addCheck(DbClientHealthCheck.create(dbClient, config.get("db.health-check")))
.build())
.build();

WebServer server = WebServer.builder()
.config(config.get("server"))
return builder.config(config.get("server"))
.addFeature(observe)
.routing(Main::routing)
.build()
.start();

System.out.println("WEB server is up! http://localhost:" + server.port() + "/");
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import io.helidon.dbclient.DbRow;

/**
* Maps database statements to {@link io.helidon.examples.dbclient.common.Pokemon} class.
* Maps database statements to {@link io.helidon.examples.dbclient.pokemons.Pokemon} class.
*/
public class PokemonMapper implements DbMapper<Pokemon> {

Expand Down