From e6fd4c090a4287d4154a118b2a6ccac7da06fc6c Mon Sep 17 00:00:00 2001 From: aserkes Date: Thu, 8 Jun 2023 10:55:57 +0200 Subject: [PATCH 1/6] OCI example - remove reactive from ATP Signed-off-by: aserkes --- .../oci/atp/reactive/OciAtpMain.java | 80 ----------- .../oci/atp/reactive/OciResponseHandler.java | 50 ------- .../META-INF/helidon/serial-config.properties | 17 --- .../oci/{atp-reactive => atp}/README.md | 4 +- .../oci/{atp-reactive => atp}/pom.xml | 12 +- .../integrations/oci/atp}/AtpService.java | 130 ++++++++++-------- .../integrations/oci/atp/OciAtpMain.java | 67 +++++++++ .../integrations/oci/atp}/package-info.java | 6 +- .../src/main/resources/application.yaml | 2 +- .../src/main/resources/logging.properties | 2 +- examples/integrations/oci/pom.xml | 2 +- 11 files changed, 154 insertions(+), 218 deletions(-) delete mode 100644 examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/OciAtpMain.java delete mode 100644 examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/OciResponseHandler.java delete mode 100644 examples/integrations/oci/atp-reactive/src/main/resources/META-INF/helidon/serial-config.properties rename examples/integrations/oci/{atp-reactive => atp}/README.md (91%) rename examples/integrations/oci/{atp-reactive => atp}/pom.xml (86%) rename examples/integrations/oci/{atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive => atp/src/main/java/io/helidon/examples/integrations/oci/atp}/AtpService.java (64%) create mode 100644 examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/OciAtpMain.java rename examples/integrations/oci/{atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive => atp/src/main/java/io/helidon/examples/integrations/oci/atp}/package-info.java (76%) rename examples/integrations/oci/{atp-reactive => atp}/src/main/resources/application.yaml (94%) rename examples/integrations/oci/{atp-reactive => atp}/src/main/resources/logging.properties (94%) diff --git a/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/OciAtpMain.java b/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/OciAtpMain.java deleted file mode 100644 index 91057ba8ed0..00000000000 --- a/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/OciAtpMain.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2021, 2022 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.integrations.oci.atp.reactive; - -import java.io.IOException; - -import io.helidon.logging.common.LogConfig; -import io.helidon.config.Config; -import io.helidon.reactive.webserver.Routing; -import io.helidon.reactive.webserver.WebServer; - -import com.oracle.bmc.ConfigFileReader; -import com.oracle.bmc.auth.AuthenticationDetailsProvider; -import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; -import com.oracle.bmc.database.DatabaseAsync; -import com.oracle.bmc.database.DatabaseAsyncClient; -import com.oracle.bmc.model.BmcException; - -/** - * Main class of the example. - * This example sets up a web server to serve REST API to retrieve ATP wallet. - */ -public final class OciAtpMain { - /** - * Cannot be instantiated. - */ - private OciAtpMain() { - } - - /** - * Application main entry point. - * - * @param args command line arguments. - */ - public static void main(String[] args) throws IOException { - // load logging configuration - LogConfig.configureRuntime(); - - // By default this will pick up application.yaml from the classpath - Config config = Config.create(); - - // this requires OCI configuration in the usual place - // ~/.oci/config - AuthenticationDetailsProvider authProvider = new ConfigFileAuthenticationDetailsProvider(ConfigFileReader.parseDefault()); - DatabaseAsync databaseAsyncClient = DatabaseAsyncClient.builder().build(authProvider); - - // Prepare routing for the server - WebServer server = WebServer.builder() - .config(config.get("server")) - .routing(Routing.builder() - .register("/atp", new AtpService(databaseAsyncClient, config)) - // OCI SDK error handling - .error(BmcException.class, (req, res, ex) -> res.status(ex.getStatusCode()) - .send(ex.getMessage()))) - .build(); - - // Start the server and print some info. - server.start().thenAccept(ws -> { - System.out.println( - "WEB server is up! http://localhost:" + ws.port() + "/"); - }); - - // Server threads are not daemon. NO need to block. Just react. - server.whenShutdown().thenRun(() -> System.out.println("WEB server is DOWN. Good bye!")); - } -} diff --git a/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/OciResponseHandler.java b/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/OciResponseHandler.java deleted file mode 100644 index 0eac2a44fa5..00000000000 --- a/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/OciResponseHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2022 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.integrations.oci.atp.reactive; - -import java.util.concurrent.CountDownLatch; - -import com.oracle.bmc.responses.AsyncHandler; - -final class OciResponseHandler implements AsyncHandler { - private OUT item; - private Throwable failed = null; - private CountDownLatch latch = new CountDownLatch(1); - - protected OUT waitForCompletion() throws Exception { - latch.await(); - if (failed != null) { - if (failed instanceof Exception) { - throw (Exception) failed; - } - throw (Error) failed; - } - return item; - } - - @Override - public void onSuccess(IN request, OUT response) { - item = response; - latch.countDown(); - } - - @Override - public void onError(IN request, Throwable error) { - failed = error; - latch.countDown(); - } -} diff --git a/examples/integrations/oci/atp-reactive/src/main/resources/META-INF/helidon/serial-config.properties b/examples/integrations/oci/atp-reactive/src/main/resources/META-INF/helidon/serial-config.properties deleted file mode 100644 index 2ef2caf1d93..00000000000 --- a/examples/integrations/oci/atp-reactive/src/main/resources/META-INF/helidon/serial-config.properties +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright (c) 2022 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. -# - -pattern=oracle.sql.converter.* diff --git a/examples/integrations/oci/atp-reactive/README.md b/examples/integrations/oci/atp/README.md similarity index 91% rename from examples/integrations/oci/atp-reactive/README.md rename to examples/integrations/oci/atp/README.md index 20b402558c1..bcba8b88a77 100644 --- a/examples/integrations/oci/atp-reactive/README.md +++ b/examples/integrations/oci/atp/README.md @@ -1,4 +1,4 @@ -# Helidon ATP Reactive Examples +# Helidon ATP Nima Examples This example demonstrates how user can easily retrieve wallet from their ATP instance running in OCI and use information from that wallet to setup DataSource to do Database operations. @@ -16,7 +16,7 @@ Once you have updated required properties, you can run the example: ```shell script mvn clean install -java -jar ./target/helidon-examples-integrations-oci-atp-reactive.jar +java -jar ./target/helidon-examples-integrations-oci-atp.jar ``` To verify that, you can retrieve wallet and do database operation: diff --git a/examples/integrations/oci/atp-reactive/pom.xml b/examples/integrations/oci/atp/pom.xml similarity index 86% rename from examples/integrations/oci/atp-reactive/pom.xml rename to examples/integrations/oci/atp/pom.xml index 90956f5db61..03856861c55 100644 --- a/examples/integrations/oci/atp-reactive/pom.xml +++ b/examples/integrations/oci/atp/pom.xml @@ -29,18 +29,18 @@ io.helidon.examples.integrations.oci - helidon-examples-integrations-oci-atp-reactive - Helidon Examples Integration OCI ATP Reactive - Reactive integration with OCI ATP. + helidon-examples-integrations-oci-atp + Helidon Examples Integration OCI ATP Nima + Nima integration with OCI ATP. - io.helidon.examples.integrations.oci.atp.reactive.OciAtpMain + io.helidon.examples.integrations.oci.atp.OciAtpMain - io.helidon.reactive.webserver - helidon-reactive-webserver + io.helidon.nima.webserver + helidon-nima-webserver io.helidon.reactive.dbclient diff --git a/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/AtpService.java b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java similarity index 64% rename from examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/AtpService.java rename to examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java index 9e0243c0cdc..ce02d141811 100644 --- a/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/AtpService.java +++ b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package io.helidon.examples.integrations.oci.atp.reactive; +package io.helidon.examples.integrations.oci.atp; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; @@ -22,6 +22,7 @@ import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.sql.SQLException; +import java.time.Duration; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; @@ -31,17 +32,21 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; +import com.oracle.bmc.ConfigFileReader; +import com.oracle.bmc.auth.AuthenticationDetailsProvider; +import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; +import com.oracle.bmc.database.Database; +import com.oracle.bmc.database.DatabaseClient; import io.helidon.common.http.Http; -import io.helidon.common.reactive.Single; import io.helidon.config.Config; +import io.helidon.config.ConfigException; +import io.helidon.nima.webserver.http.HttpRules; +import io.helidon.nima.webserver.http.HttpService; +import io.helidon.nima.webserver.http.ServerRequest; +import io.helidon.nima.webserver.http.ServerResponse; import io.helidon.reactive.dbclient.DbClient; import io.helidon.reactive.dbclient.jdbc.JdbcDbClientProvider; -import io.helidon.reactive.webserver.Routing; -import io.helidon.reactive.webserver.ServerRequest; -import io.helidon.reactive.webserver.ServerResponse; -import io.helidon.reactive.webserver.Service; -import com.oracle.bmc.database.DatabaseAsync; import com.oracle.bmc.database.model.GenerateAutonomousDatabaseWalletDetails; import com.oracle.bmc.database.requests.GenerateAutonomousDatabaseWalletRequest; import com.oracle.bmc.database.responses.GenerateAutonomousDatabaseWalletResponse; @@ -50,45 +55,48 @@ import oracle.ucp.jdbc.PoolDataSource; import oracle.ucp.jdbc.PoolDataSourceFactory; -class AtpService implements Service { +class AtpService implements HttpService { private static final Logger LOGGER = Logger.getLogger(AtpService.class.getName()); - private final DatabaseAsync databaseAsyncClient; + private final Database databaseAsyncClient; private final Config config; - AtpService(DatabaseAsync databaseAsyncClient, Config config) { - this.databaseAsyncClient = databaseAsyncClient; - this.config = config; + AtpService(Config config) { + try { + // this requires OCI configuration in the usual place + // ~/.oci/config + AuthenticationDetailsProvider authProvider = new ConfigFileAuthenticationDetailsProvider(ConfigFileReader.parseDefault()); + databaseAsyncClient = DatabaseClient.builder().build(authProvider); + this.config = config; + } catch (IOException e) { + throw new ConfigException("Failed to read configuration properties", e); + } } - @Override - public void update(Routing.Rules rules) { + /** + * A service registers itself by updating the routine rules. + * + * @param rules the routing rules. + */ + public void routing(HttpRules rules) { rules.get("/wallet", this::generateWallet); } /** * Generate wallet file for the configured ATP. + * + * @param req request + * @param res response */ private void generateWallet(ServerRequest req, ServerResponse res) { - OciResponseHandler walletHandler = - new OciResponseHandler<>(); - GenerateAutonomousDatabaseWalletResponse walletResponse = null; - try { - databaseAsyncClient.generateAutonomousDatabaseWallet( - GenerateAutonomousDatabaseWalletRequest.builder() - .autonomousDatabaseId(config.get("oci.atp.ocid").asString().get()) - .generateAutonomousDatabaseWalletDetails( - GenerateAutonomousDatabaseWalletDetails.builder() - .password(config.get("oci.atp.walletPassword").asString().get()) - .build()) - .build(), walletHandler); - walletResponse = walletHandler.waitForCompletion(); - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Error waiting for GenerateAutonomousDatabaseWalletResponse", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); - return; - } + GenerateAutonomousDatabaseWalletResponse walletResponse = databaseAsyncClient.generateAutonomousDatabaseWallet( + GenerateAutonomousDatabaseWalletRequest.builder() + .autonomousDatabaseId(config.get("oci.atp.ocid").asString().get()) + .generateAutonomousDatabaseWalletDetails( + GenerateAutonomousDatabaseWalletDetails.builder() + .password(config.get("oci.atp.walletPassword").asString().get()) + .build()) + .build()); if (walletResponse.getContentLength() == 0) { LOGGER.log(Level.SEVERE, "GenerateAutonomousDatabaseWalletResponse is empty"); @@ -101,20 +109,27 @@ private void generateWallet(ServerRequest req, ServerResponse res) { walletContent = walletResponse.getInputStream().readAllBytes(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error processing GenerateAutonomousDatabaseWalletResponse", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); + res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(e.getMessage()); return; } - createDbClient(walletContent) - .flatMap(dbClient -> dbClient.execute(exec -> exec.query("SELECT 'Hello world!!' FROM DUAL"))) - .first() - .map(dbRow -> dbRow.column(1).as(String.class)) - .ifEmpty(() -> res.status(404).send()) - .onError(res::send) - .forSingle(res::send); + try { + String result = createDbClient(walletContent) + .execute(exec -> exec.query("SELECT 'Hello world!!' FROM DUAL")) + .first() + .map(dbRow -> dbRow.column(1).as(String.class)) + .await(Duration.ofSeconds(60)); + if (result == null || result.isEmpty()) { + res.status(Http.Status.NOT_FOUND_404).send(); + } else { + res.send(result); + } + } catch (Exception e) { + res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(e.getMessage()); + } } - Single createDbClient(byte[] walletContent) { + DbClient createDbClient(byte[] walletContent) { PoolDataSource pds = PoolDataSourceFactory.getPoolDataSource(); try { pds.setSSLContext(getSSLContext(walletContent)); @@ -123,22 +138,23 @@ Single createDbClient(byte[] walletContent) { .orElseThrow(() -> new IllegalStateException("Missing tnsNetServiceName!!")))); pds.setUser(config.get("db.userName").as(String.class).orElse("ADMIN")); pds.setPassword(config.get("db.password") - .as(String.class) - .orElseThrow(() -> new IllegalStateException("Missing password!!"))); + .as(String.class) + .orElseThrow(() -> new IllegalStateException("Missing password!!"))); pds.setConnectionFactoryClassName(OracleDataSource.class.getName()); } catch (SQLException e) { LOGGER.log(Level.SEVERE, "Error setting up PoolDataSource", e); - return Single.error(e); + throw new RuntimeException(e); } - return Single.just(new JdbcDbClientProvider().builder() - .connectionPool(() -> { - try { - return pds.getConnection(); - } catch (SQLException e) { - throw new IllegalStateException("Error while setting up new connection", e); - } - }) - .build()); + + return new JdbcDbClientProvider().builder() + .connectionPool(() -> { + try { + return pds.getConnection(); + } catch (SQLException e) { + throw new IllegalStateException("Error while setting up new connection", e); + } + }) + .build(); } /** @@ -174,8 +190,8 @@ private static SSLContext getSSLContext(byte[] walletContent) throws IllegalStat /** * Returns JDBC URL with connection description for the given service based on tnsnames.ora in wallet. * - * @param walletContent - * @param tnsNetServiceName + * @param walletContent walletContent + * @param tnsNetServiceName tnsNetServiceName * @return String */ private static String getJdbcUrl(byte[] walletContent, String tnsNetServiceName) throws IllegalStateException { diff --git a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/OciAtpMain.java b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/OciAtpMain.java new file mode 100644 index 00000000000..e2aa3a3bb39 --- /dev/null +++ b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/OciAtpMain.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021, 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.integrations.oci.atp; + +import java.io.IOException; + +import io.helidon.logging.common.LogConfig; +import io.helidon.config.Config; +import io.helidon.nima.webserver.WebServer; +import io.helidon.nima.webserver.http.HttpRouting; + +/** + * Main class of the example. + * This example sets up a web server to serve REST API to retrieve ATP wallet. + */ +public final class OciAtpMain { + + private static Config config; + + /** + * Cannot be instantiated. + */ + private OciAtpMain() { + } + + /** + * Application main entry point. + * + * @param args command line arguments. + */ + public static void main(String[] args) throws IOException { + // load logging configuration + LogConfig.configureRuntime(); + + // By default this will pick up application.yaml from the classpath + config = Config.create(); + + WebServer server = WebServer.builder() + .routing(OciAtpMain::routing) + .port(config.get("server.port").asInt().orElse(8080)) + .start(); + + System.out.println("WEB server is up! http://localhost:" + server.port()); + } + + /** + * Updates HTTP Routing. + */ + static void routing(HttpRouting.Builder routing) { + AtpService atpService = new AtpService(config); + routing.register("/atp", atpService); + } +} diff --git a/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/package-info.java b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/package-info.java similarity index 76% rename from examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/package-info.java rename to examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/package-info.java index ee7800316ed..35e3363181b 100644 --- a/examples/integrations/oci/atp-reactive/src/main/java/io/helidon/examples/integrations/oci/atp/reactive/package-info.java +++ b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -15,6 +15,6 @@ */ /** - * Example of integration with OCI ATP in reactive application. + * Example of integration with OCI ATP in Nima application. */ -package io.helidon.examples.integrations.oci.atp.reactive; +package io.helidon.examples.integrations.oci.atp; diff --git a/examples/integrations/oci/atp-reactive/src/main/resources/application.yaml b/examples/integrations/oci/atp/src/main/resources/application.yaml similarity index 94% rename from examples/integrations/oci/atp-reactive/src/main/resources/application.yaml rename to examples/integrations/oci/atp/src/main/resources/application.yaml index 156f26ed159..b65d90eccd2 100644 --- a/examples/integrations/oci/atp-reactive/src/main/resources/application.yaml +++ b/examples/integrations/oci/atp/src/main/resources/application.yaml @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2022 Oracle and/or its affiliates. +# Copyright (c) 2021, 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. diff --git a/examples/integrations/oci/atp-reactive/src/main/resources/logging.properties b/examples/integrations/oci/atp/src/main/resources/logging.properties similarity index 94% rename from examples/integrations/oci/atp-reactive/src/main/resources/logging.properties rename to examples/integrations/oci/atp/src/main/resources/logging.properties index 43cd0f29d7d..c09e76d612c 100644 --- a/examples/integrations/oci/atp-reactive/src/main/resources/logging.properties +++ b/examples/integrations/oci/atp/src/main/resources/logging.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2022 Oracle and/or its affiliates. +# Copyright (c) 2021, 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. diff --git a/examples/integrations/oci/pom.xml b/examples/integrations/oci/pom.xml index 586da771869..a68e347d374 100644 --- a/examples/integrations/oci/pom.xml +++ b/examples/integrations/oci/pom.xml @@ -33,7 +33,7 @@ Examples of integration with OCI (Oracle Cloud). - atp-reactive + atp atp-cdi metrics-reactive objectstorage-reactive From 0b7be9fab1f6f2137c238e1c0905855c6cd0bdda Mon Sep 17 00:00:00 2001 From: aserkes Date: Thu, 8 Jun 2023 13:18:21 +0200 Subject: [PATCH 2/6] OCI example - remove reactive from Metrics Signed-off-by: aserkes --- .../oci/{metrics-reactive => metrics}/pom.xml | 12 +-- .../oci/telemetry}/OciMetricsMain.java | 80 +++++-------------- .../oci/telemetry}/package-info.java | 6 +- .../src/main/resources/application.yaml | 2 +- .../src/main/resources/logging.properties | 2 +- examples/integrations/oci/pom.xml | 2 +- 6 files changed, 32 insertions(+), 72 deletions(-) rename examples/integrations/oci/{metrics-reactive => metrics}/pom.xml (84%) rename examples/integrations/oci/{metrics-reactive/src/main/java/io/helidon/examples/integrations/oci/telemetry/reactive => metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry}/OciMetricsMain.java (65%) rename examples/integrations/oci/{metrics-reactive/src/main/java/io/helidon/examples/integrations/oci/telemetry/reactive => metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry}/package-info.java (78%) rename examples/integrations/oci/{metrics-reactive => metrics}/src/main/resources/application.yaml (92%) rename examples/integrations/oci/{metrics-reactive => metrics}/src/main/resources/logging.properties (94%) diff --git a/examples/integrations/oci/metrics-reactive/pom.xml b/examples/integrations/oci/metrics/pom.xml similarity index 84% rename from examples/integrations/oci/metrics-reactive/pom.xml rename to examples/integrations/oci/metrics/pom.xml index 84d18bb3c70..0acc6710b1a 100644 --- a/examples/integrations/oci/metrics-reactive/pom.xml +++ b/examples/integrations/oci/metrics/pom.xml @@ -29,19 +29,15 @@ - io.helidon.examples.integrations.oci.telemetry.reactive.OciMetricsMain + io.helidon.examples.integrations.oci.telemetry.OciMetricsMain io.helidon.examples.integrations.oci - helidon-examples-integrations-oci-metrics-reactive - Helidon Examples Integration OCI Metrics Reactive - Reactive integration with OCI Metrics. + helidon-examples-integrations-oci-metrics + Helidon Examples Integration OCI Metrics + Integration with OCI Metrics. - - io.helidon.reactive.webserver - helidon-reactive-webserver - io.helidon.config helidon-config-yaml diff --git a/examples/integrations/oci/metrics-reactive/src/main/java/io/helidon/examples/integrations/oci/telemetry/reactive/OciMetricsMain.java b/examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/OciMetricsMain.java similarity index 65% rename from examples/integrations/oci/metrics-reactive/src/main/java/io/helidon/examples/integrations/oci/telemetry/reactive/OciMetricsMain.java rename to examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/OciMetricsMain.java index a7073137da8..73a3181f23e 100644 --- a/examples/integrations/oci/metrics-reactive/src/main/java/io/helidon/examples/integrations/oci/telemetry/reactive/OciMetricsMain.java +++ b/examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/OciMetricsMain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package io.helidon.examples.integrations.oci.telemetry.reactive; +package io.helidon.examples.integrations.oci.telemetry; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -22,16 +22,15 @@ import java.util.Date; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.CountDownLatch; +import com.oracle.bmc.monitoring.Monitoring; +import com.oracle.bmc.monitoring.MonitoringClient; import io.helidon.logging.common.LogConfig; import io.helidon.config.Config; import com.oracle.bmc.ConfigFileReader; import com.oracle.bmc.auth.AuthenticationDetailsProvider; import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; -import com.oracle.bmc.monitoring.MonitoringAsync; -import com.oracle.bmc.monitoring.MonitoringAsyncClient; import com.oracle.bmc.monitoring.model.Datapoint; import com.oracle.bmc.monitoring.model.FailedMetricRecord; import com.oracle.bmc.monitoring.model.MetricDataDetails; @@ -39,7 +38,6 @@ import com.oracle.bmc.monitoring.model.PostMetricDataResponseDetails; import com.oracle.bmc.monitoring.requests.PostMetricDataRequest; import com.oracle.bmc.monitoring.responses.PostMetricDataResponse; -import com.oracle.bmc.responses.AsyncHandler; import static io.helidon.config.ConfigSources.classpath; import static io.helidon.config.ConfigSources.file; @@ -54,6 +52,7 @@ private OciMetricsMain() { /** * Main method. + * * @param args ignored */ public static void main(String[] args) throws Exception { @@ -67,29 +66,23 @@ public static void main(String[] args) throws Exception { // this requires OCI configuration in the usual place // ~/.oci/config AuthenticationDetailsProvider authProvider = new ConfigFileAuthenticationDetailsProvider(ConfigFileReader.parseDefault()); - MonitoringAsync monitoringAsyncClient = new MonitoringAsyncClient(authProvider); - monitoringAsyncClient.setEndpoint(monitoringAsyncClient.getEndpoint().replace("telemetry.", "telemetry-ingestion.")); - - PostMetricDataRequest postMetricDataRequest = PostMetricDataRequest.builder() - .postMetricDataDetails(getPostMetricDataDetails(config)) - .build(); - /* - * Invoke the API call. I use .await() to block the call, as otherwise our - * main method would finish without waiting for the response. - * In a real reactive application, this should not be done (as you would write the response - * to a server response or use other reactive/non-blocking APIs). - */ - ResponseHandler monitoringHandler = - new ResponseHandler<>(); - monitoringAsyncClient.postMetricData(postMetricDataRequest, monitoringHandler); - PostMetricDataResponse postMetricDataResponse = monitoringHandler.waitForCompletion(); - PostMetricDataResponseDetails postMetricDataResponseDetails = postMetricDataResponse.getPostMetricDataResponseDetails(); - int count = postMetricDataResponseDetails.getFailedMetricsCount(); - System.out.println("Failed count: " + count); - if (count > 0) { - System.out.println("Failed metrics:"); - for (FailedMetricRecord failedMetric : postMetricDataResponseDetails.getFailedMetrics()) { - System.out.println("\t" + failedMetric.getMessage() + ": " + failedMetric.getMetricData()); + try (Monitoring monitoringClient = MonitoringClient.builder().build(authProvider)) { + monitoringClient.setEndpoint(monitoringClient.getEndpoint().replace("telemetry.", "telemetry-ingestion.")); + + PostMetricDataRequest postMetricDataRequest = PostMetricDataRequest.builder() + .postMetricDataDetails(getPostMetricDataDetails(config)) + .build(); + + // Invoke the API call. + PostMetricDataResponse postMetricDataResponse = monitoringClient.postMetricData(postMetricDataRequest); + PostMetricDataResponseDetails postMetricDataResponseDetails = postMetricDataResponse.getPostMetricDataResponseDetails(); + int count = postMetricDataResponseDetails.getFailedMetricsCount(); + System.out.println("Failed count: " + count); + if (count > 0) { + System.out.println("Failed metrics:"); + for (FailedMetricRecord failedMetric : postMetricDataResponseDetails.getFailedMetrics()) { + System.out.println("\t" + failedMetric.getMessage() + ": " + failedMetric.getMetricData()); + } } } } @@ -143,33 +136,4 @@ private static Map makeMap(String... data) { } return map; } - - private static class ResponseHandler implements AsyncHandler { - private OUT item; - private Throwable failed = null; - private CountDownLatch latch = new CountDownLatch(1); - - private OUT waitForCompletion() throws Exception { - latch.await(); - if (failed != null) { - if (failed instanceof Exception) { - throw (Exception) failed; - } - throw (Error) failed; - } - return item; - } - - @Override - public void onSuccess(IN request, OUT response) { - item = response; - latch.countDown(); - } - - @Override - public void onError(IN request, Throwable error) { - failed = error; - latch.countDown(); - } - } } diff --git a/examples/integrations/oci/metrics-reactive/src/main/java/io/helidon/examples/integrations/oci/telemetry/reactive/package-info.java b/examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/package-info.java similarity index 78% rename from examples/integrations/oci/metrics-reactive/src/main/java/io/helidon/examples/integrations/oci/telemetry/reactive/package-info.java rename to examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/package-info.java index 5e3c842230a..3fc15dd7d8a 100644 --- a/examples/integrations/oci/metrics-reactive/src/main/java/io/helidon/examples/integrations/oci/telemetry/reactive/package-info.java +++ b/examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -15,6 +15,6 @@ */ /** - * Example using OCI metrics reactive API. + * Example using OCI metrics blocking API. */ -package io.helidon.examples.integrations.oci.telemetry.reactive; +package io.helidon.examples.integrations.oci.telemetry; diff --git a/examples/integrations/oci/metrics-reactive/src/main/resources/application.yaml b/examples/integrations/oci/metrics/src/main/resources/application.yaml similarity index 92% rename from examples/integrations/oci/metrics-reactive/src/main/resources/application.yaml rename to examples/integrations/oci/metrics/src/main/resources/application.yaml index d9304c7641e..c2c669e26ca 100644 --- a/examples/integrations/oci/metrics-reactive/src/main/resources/application.yaml +++ b/examples/integrations/oci/metrics/src/main/resources/application.yaml @@ -1,5 +1,5 @@ # -# Copyright (c) 2021 Oracle and/or its affiliates. +# Copyright (c) 2021, 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. diff --git a/examples/integrations/oci/metrics-reactive/src/main/resources/logging.properties b/examples/integrations/oci/metrics/src/main/resources/logging.properties similarity index 94% rename from examples/integrations/oci/metrics-reactive/src/main/resources/logging.properties rename to examples/integrations/oci/metrics/src/main/resources/logging.properties index f8802f90626..341cef8ce9e 100644 --- a/examples/integrations/oci/metrics-reactive/src/main/resources/logging.properties +++ b/examples/integrations/oci/metrics/src/main/resources/logging.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2022 Oracle and/or its affiliates. +# Copyright (c) 2021, 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. diff --git a/examples/integrations/oci/pom.xml b/examples/integrations/oci/pom.xml index a68e347d374..6a8ff21c520 100644 --- a/examples/integrations/oci/pom.xml +++ b/examples/integrations/oci/pom.xml @@ -35,7 +35,7 @@ atp atp-cdi - metrics-reactive + metrics objectstorage-reactive objectstorage-cdi vault-reactive From a0f806d0c573b7ef48bf9317c3f883f4491b55d7 Mon Sep 17 00:00:00 2001 From: aserkes Date: Thu, 8 Jun 2023 13:34:18 +0200 Subject: [PATCH 3/6] OCI example - remove reactive from ObjectStorage Signed-off-by: aserkes --- .../reactive/ObjectStorageService.java | 223 ------------------ .../reactive/OciObjectStorageMain.java | 86 ------- .../pom.xml | 12 +- .../objecstorage/ObjectStorageService.java | 170 +++++++++++++ .../objecstorage/OciObjectStorageMain.java | 79 +++++++ .../oci/objecstorage}/package-info.java | 6 +- .../src/main/resources/application.yaml | 2 +- .../src/main/resources/logging.properties | 2 +- examples/integrations/oci/pom.xml | 2 +- 9 files changed, 261 insertions(+), 321 deletions(-) delete mode 100644 examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/ObjectStorageService.java delete mode 100644 examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/OciObjectStorageMain.java rename examples/integrations/oci/{objectstorage-reactive => objectstorage}/pom.xml (85%) create mode 100644 examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java create mode 100644 examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/OciObjectStorageMain.java rename examples/integrations/oci/{objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive => objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage}/package-info.java (74%) rename examples/integrations/oci/{objectstorage-reactive => objectstorage}/src/main/resources/application.yaml (92%) rename examples/integrations/oci/{objectstorage-reactive => objectstorage}/src/main/resources/logging.properties (94%) diff --git a/examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/ObjectStorageService.java b/examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/ObjectStorageService.java deleted file mode 100644 index c4cbbe25694..00000000000 --- a/examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/ObjectStorageService.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2021, 2022 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.integrations.oci.objecstorage.reactive; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.concurrent.CountDownLatch; -import java.util.logging.Level; -import java.util.logging.Logger; - -import io.helidon.common.http.Http; -import io.helidon.reactive.webserver.Routing; -import io.helidon.reactive.webserver.ServerRequest; -import io.helidon.reactive.webserver.ServerResponse; -import io.helidon.reactive.webserver.Service; - -import com.oracle.bmc.objectstorage.ObjectStorageAsync; -import com.oracle.bmc.objectstorage.model.RenameObjectDetails; -import com.oracle.bmc.objectstorage.requests.DeleteObjectRequest; -import com.oracle.bmc.objectstorage.requests.GetNamespaceRequest; -import com.oracle.bmc.objectstorage.requests.GetObjectRequest; -import com.oracle.bmc.objectstorage.requests.PutObjectRequest; -import com.oracle.bmc.objectstorage.requests.RenameObjectRequest; -import com.oracle.bmc.objectstorage.responses.DeleteObjectResponse; -import com.oracle.bmc.objectstorage.responses.GetNamespaceResponse; -import com.oracle.bmc.objectstorage.responses.GetObjectResponse; -import com.oracle.bmc.objectstorage.responses.PutObjectResponse; -import com.oracle.bmc.objectstorage.responses.RenameObjectResponse; -import com.oracle.bmc.responses.AsyncHandler; - -class ObjectStorageService implements Service { - private static final Logger LOGGER = Logger.getLogger(ObjectStorageService.class.getName()); - private final ObjectStorageAsync objectStorageAsyncClient; - private final String bucketName; - private final String namespaceName; - - ObjectStorageService(ObjectStorageAsync objectStorageAsyncClient, String bucketName) throws Exception { - this.objectStorageAsyncClient = objectStorageAsyncClient; - this.bucketName = bucketName; - ResponseHandler namespaceHandler = - new ResponseHandler<>(); - this.objectStorageAsyncClient.getNamespace(GetNamespaceRequest.builder().build(), namespaceHandler); - GetNamespaceResponse namespaceResponse = namespaceHandler.waitForCompletion(); - this.namespaceName = namespaceResponse.getValue(); - } - - @Override - public void update(Routing.Rules rules) { - rules.get("/file/{file-name}", this::download) - .post("/file/{file-name}", this::upload) - .delete("/file/{file-name}", this::delete) - .get("/rename/{old-name}/{new-name}", this::rename); - } - - private void delete(ServerRequest req, ServerResponse res) { - String objectName = req.path().param("file-name"); - - ResponseHandler deleteObjectHandler = - new ResponseHandler<>(); - - objectStorageAsyncClient.deleteObject(DeleteObjectRequest.builder() - .namespaceName(namespaceName) - .bucketName(bucketName) - .objectName(objectName).build(), deleteObjectHandler); - try { - DeleteObjectResponse deleteObjectResponse = deleteObjectHandler.waitForCompletion(); - res.status(Http.Status.OK_200) - .send(); - return; - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Error deleting object", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); - return; - } - } - - private void rename(ServerRequest req, ServerResponse res) { - String oldName = req.path().param("old-name"); - String newName = req.path().param("new-name"); - - RenameObjectRequest renameObjectRequest = RenameObjectRequest.builder() - .namespaceName(namespaceName) - .bucketName(bucketName) - .renameObjectDetails(RenameObjectDetails.builder() - .newName(newName) - .sourceName(oldName) - .build()) - .build(); - - ResponseHandler renameObjectHandler = - new ResponseHandler<>(); - - try { - objectStorageAsyncClient.renameObject(renameObjectRequest, renameObjectHandler); - RenameObjectResponse renameObjectResponse = renameObjectHandler.waitForCompletion(); - res.status(Http.Status.OK_200) - .send(); - return; - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Error renaming object", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); - return; - } - } - - private void upload(ServerRequest req, ServerResponse res) { - String objectName = req.path().param("file-name"); - PutObjectRequest putObjectRequest = null; - try (InputStream stream = new FileInputStream(System.getProperty("user.dir") + File.separator + objectName)) { - byte[] contents = stream.readAllBytes(); - putObjectRequest = - PutObjectRequest.builder() - .namespaceName(namespaceName) - .bucketName(bucketName) - .objectName(objectName) - .putObjectBody(new ByteArrayInputStream(contents)) - .contentLength(Long.valueOf(contents.length)) - .build(); - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Error creating PutObjectRequest", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); - return; - } - - ResponseHandler putObjectHandler = - new ResponseHandler<>(); - - try { - objectStorageAsyncClient.putObject(putObjectRequest, putObjectHandler); - PutObjectResponse putObjectResponse = putObjectHandler.waitForCompletion(); - res.status(Http.Status.OK_200).send(); - return; - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Error uploading object", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); - return; - } - } - - private void download(ServerRequest req, ServerResponse res) { - String objectName = req.path().param("file-name"); - ResponseHandler objectHandler = - new ResponseHandler<>(); - GetObjectRequest getObjectRequest = - GetObjectRequest.builder() - .namespaceName(namespaceName) - .bucketName(bucketName) - .objectName(objectName) - .build(); - GetObjectResponse getObjectResponse = null; - try { - objectStorageAsyncClient.getObject(getObjectRequest, objectHandler); - getObjectResponse = objectHandler.waitForCompletion(); - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Error getting object", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); - return; - } - - if (getObjectResponse.getContentLength() == 0) { - LOGGER.log(Level.SEVERE, "GetObjectResponse is empty"); - res.status(Http.Status.NOT_FOUND_404).send(); - return; - } - - try (InputStream fileStream = getObjectResponse.getInputStream()) { - byte[] objectContent = fileStream.readAllBytes(); - res.addHeader(Http.Header.CONTENT_DISPOSITION, "attachment; filename=\"" + objectName + "\"") - .status(Http.Status.OK_200).send(objectContent); - return; - } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Error processing GetObjectResponse", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); - return; - } - } - - private static class ResponseHandler implements AsyncHandler { - private OUT item; - private Throwable failed = null; - private CountDownLatch latch = new CountDownLatch(1); - - private OUT waitForCompletion() throws Exception { - latch.await(); - if (failed != null) { - if (failed instanceof Exception) { - throw (Exception) failed; - } - throw (Error) failed; - } - return item; - } - - @Override - public void onSuccess(IN request, OUT response) { - item = response; - latch.countDown(); - } - - @Override - public void onError(IN request, Throwable error) { - failed = error; - latch.countDown(); - } - } -} diff --git a/examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/OciObjectStorageMain.java b/examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/OciObjectStorageMain.java deleted file mode 100644 index 4abb8893af3..00000000000 --- a/examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/OciObjectStorageMain.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2021, 2022 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.integrations.oci.objecstorage.reactive; - -import io.helidon.logging.common.LogConfig; -import io.helidon.config.Config; -import io.helidon.reactive.webserver.Routing; -import io.helidon.reactive.webserver.WebServer; - -import com.oracle.bmc.ConfigFileReader; -import com.oracle.bmc.auth.AuthenticationDetailsProvider; -import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; -import com.oracle.bmc.model.BmcException; -import com.oracle.bmc.objectstorage.ObjectStorageAsync; -import com.oracle.bmc.objectstorage.ObjectStorageAsyncClient; - -import static io.helidon.config.ConfigSources.classpath; -import static io.helidon.config.ConfigSources.file; - -/** - * Main class of the example. - * This example sets up a web server to serve REST API to upload/download/delete objects. - */ -public final class OciObjectStorageMain { - private OciObjectStorageMain() { - } - - /** - * Main method. - * - * @param args ignored - */ - public static void main(String[] args) throws Exception { - LogConfig.configureRuntime(); - // as I cannot share my configuration of OCI, let's combine the configuration - // from my home directory with the one compiled into the jar - // when running this example, you can either update the application.yaml in resources directory - // or use the same approach - Config config = buildConfig(); - - Config ociConfig = config.get("oci"); - - // this requires OCI configuration in the usual place - // ~/.oci/config - AuthenticationDetailsProvider authProvider = new ConfigFileAuthenticationDetailsProvider(ConfigFileReader.parseDefault()); - ObjectStorageAsync objectStorageAsyncClient = new ObjectStorageAsyncClient(authProvider); - - // the following parameters are required - String bucketName = ociConfig.get("objectstorage").get("bucketName").asString().get(); - - WebServer.builder() - .config(config.get("server")) - .routing(Routing.builder() - .register("/files", new ObjectStorageService(objectStorageAsyncClient, bucketName)) - // OCI SDK error handling - .error(BmcException.class, (req, res, ex) -> res.status(ex.getStatusCode()) - .send(ex.getMessage()))) - .build() - .start() - .await(); - } - - private static Config buildConfig() { - return Config.builder() - .sources( - // you can use this file to override the defaults that are built-in - file(System.getProperty("user.home") + "/helidon/conf/examples.yaml").optional(), - // in jar file (see src/main/resources/application.yaml) - classpath("application.yaml")) - .build(); - } -} diff --git a/examples/integrations/oci/objectstorage-reactive/pom.xml b/examples/integrations/oci/objectstorage/pom.xml similarity index 85% rename from examples/integrations/oci/objectstorage-reactive/pom.xml rename to examples/integrations/oci/objectstorage/pom.xml index 62cdac5b41c..f7df51ccec8 100644 --- a/examples/integrations/oci/objectstorage-reactive/pom.xml +++ b/examples/integrations/oci/objectstorage/pom.xml @@ -29,18 +29,18 @@ io.helidon.examples.integrations.oci - helidon-examples-integrations-oci-objectstorage-reactive - Helidon Examples Integration OCI Object Storage Reactive - Reactive integration with OCI Object Storage. + helidon-examples-integrations-oci-objectstorage + Helidon Examples Integration OCI Object Storage + Nima integration with OCI Object Storage. - io.helidon.examples.integrations.oci.objecstorage.reactive.OciObjectStorageMain + io.helidon.examples.integrations.oci.objecstorage.OciObjectStorageMain - io.helidon.reactive.webserver - helidon-reactive-webserver + io.helidon.nima.webserver + helidon-nima-webserver io.helidon.config diff --git a/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java new file mode 100644 index 00000000000..0bb732ef401 --- /dev/null +++ b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2021, 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.integrations.oci.objecstorage; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.oracle.bmc.ConfigFileReader; +import com.oracle.bmc.auth.AuthenticationDetailsProvider; +import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; +import com.oracle.bmc.objectstorage.ObjectStorageClient; +import io.helidon.common.http.Http; + +import com.oracle.bmc.objectstorage.ObjectStorage; +import com.oracle.bmc.objectstorage.requests.DeleteObjectRequest; +import com.oracle.bmc.objectstorage.requests.GetNamespaceRequest; +import com.oracle.bmc.objectstorage.requests.GetObjectRequest; +import com.oracle.bmc.objectstorage.requests.PutObjectRequest; +import com.oracle.bmc.objectstorage.responses.DeleteObjectResponse; +import com.oracle.bmc.objectstorage.responses.GetNamespaceResponse; +import com.oracle.bmc.objectstorage.responses.GetObjectResponse; +import com.oracle.bmc.objectstorage.responses.PutObjectResponse; +import io.helidon.config.Config; +import io.helidon.config.ConfigException; +import io.helidon.nima.webserver.http.HttpRules; +import io.helidon.nima.webserver.http.HttpService; +import io.helidon.nima.webserver.http.ServerRequest; +import io.helidon.nima.webserver.http.ServerResponse; + +/** + * REST API for the objecstorage example. + */ +public class ObjectStorageService implements HttpService { + private static final Logger LOGGER = Logger.getLogger(ObjectStorageService.class.getName()); + private final ObjectStorage objectStorageClient; + private final String namespaceName; + private final String bucketName; + + + ObjectStorageService(Config config) { + try { + AuthenticationDetailsProvider authProvider = new ConfigFileAuthenticationDetailsProvider(ConfigFileReader.parseDefault()); + this.objectStorageClient = ObjectStorageClient.builder().build(authProvider); + this.bucketName = config.get("oci.objectstorage.bucketName") + .asString() + .orElseThrow(() -> new IllegalStateException("Missing bucket name!!")); + GetNamespaceResponse namespaceResponse = + this.objectStorageClient.getNamespace(GetNamespaceRequest.builder().build()); + this.namespaceName = namespaceResponse.getValue(); + } catch (IOException e) { + throw new ConfigException("Failed to read configuration properties", e); + } + } + + /** + * A service registers itself by updating the routine rules. + * + * @param rules the routing rules. + */ + public void routing(HttpRules rules) { + rules.get("/file/{file-name}", this::download); + rules.post("/file/{fileName}", this::upload); + rules.delete("/file/{file-name}", this::delete); + } + + /** + * Download a file from object storage. + * + * @param request request + * @param response response + */ + public void download(ServerRequest request, ServerResponse response) { + String fileName = request.path().pathParameters().value("file-name"); + GetObjectResponse getObjectResponse = + objectStorageClient.getObject( + GetObjectRequest.builder() + .namespaceName(namespaceName) + .bucketName(bucketName) + .objectName(fileName) + .build()); + + if (getObjectResponse.getContentLength() == 0) { + LOGGER.log(Level.SEVERE, "GetObjectResponse is empty"); + response.status(Http.Status.NOT_FOUND_404).send(); + return; + } + + try (InputStream fileStream = getObjectResponse.getInputStream()) { + byte[] objectContent = fileStream.readAllBytes(); + response + .status(Http.Status.OK_200) + .header(Http.Header.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") + .header("opc-request-id", getObjectResponse.getOpcRequestId()) + .header(Http.Header.CONTENT_LENGTH.defaultCase(), getObjectResponse.getContentLength().toString()); + + response.send(objectContent); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Error processing GetObjectResponse", e); + response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); + } + } + + /** + * Upload a file to object storage. + * + * @param request request + * @param response response + */ + public void upload(ServerRequest request, ServerResponse response) { + String fileName = request.path().pathParameters().value("fileName"); + PutObjectRequest putObjectRequest = null; + try (InputStream stream = new FileInputStream(System.getProperty("user.dir") + File.separator + fileName)) { + byte[] contents = stream.readAllBytes(); + putObjectRequest = + PutObjectRequest.builder() + .namespaceName(namespaceName) + .bucketName(bucketName) + .objectName(fileName) + .putObjectBody(new ByteArrayInputStream(contents)) + .contentLength(Long.valueOf(contents.length)) + .build(); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Error creating PutObjectRequest", e); + response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); + return; + } + PutObjectResponse putObjectResponse = objectStorageClient.putObject(putObjectRequest); + + response.status(Http.Status.OK_200).header("opc-request-id", putObjectResponse.getOpcRequestId()); + + response.send(); + } + + /** + * Delete a file from object storage. + * + * @param request request + * @param response response + */ + public void delete(ServerRequest request, ServerResponse response) { + String fileName = request.path().pathParameters().value("file-name"); + DeleteObjectResponse deleteObjectResponse = objectStorageClient.deleteObject(DeleteObjectRequest.builder() + .namespaceName(namespaceName) + .bucketName(bucketName) + .objectName(fileName) + .build()); + response.status(Http.Status.OK_200).header("opc-request-id", deleteObjectResponse.getOpcRequestId()); + + response.send(); + } +} diff --git a/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/OciObjectStorageMain.java b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/OciObjectStorageMain.java new file mode 100644 index 00000000000..9ca86d19bee --- /dev/null +++ b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/OciObjectStorageMain.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021, 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.integrations.oci.objecstorage; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +import io.helidon.config.Config; +import io.helidon.config.spi.ConfigSource; +import io.helidon.nima.webserver.WebServer; +import io.helidon.nima.webserver.http.HttpRouting; + +import static io.helidon.config.ConfigSources.classpath; +import static io.helidon.config.ConfigSources.file; + +/** + * Main class of the example. + * This example sets up a web server to serve REST API to upload/download/delete objects. + */ +public final class OciObjectStorageMain { + + private static Config config; + + private OciObjectStorageMain() { + } + + /** + * Main method. + * + * @param args ignored + */ + public static void main(String[] args) { + + config = Config + .builder() + .sources(examplesConfig()) + .build(); + + WebServer server = WebServer.builder() + .routing(OciObjectStorageMain::routing) + .start(); + } + + /** + * Updates HTTP Routing. + */ + static void routing(HttpRouting.Builder routing) { + ObjectStorageService objectStorageService = new ObjectStorageService(config); + routing.register("/files", objectStorageService); + } + + private static List> examplesConfig() { + List> suppliers = new ArrayList<>(); + Path path = Paths.get(System.getProperty("user.home") + "/helidon/conf/examples.yaml"); + if (Files.exists(path)) { + suppliers.add(file(path).build()); + } + suppliers.add(classpath("application.yaml").build()); + return suppliers; + } +} diff --git a/examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/package-info.java b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/package-info.java similarity index 74% rename from examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/package-info.java rename to examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/package-info.java index 3bda523337e..1a91fa72fe8 100644 --- a/examples/integrations/oci/objectstorage-reactive/src/main/java/io/helidon/examples/integrations/oci/objecstorage/reactive/package-info.java +++ b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -15,6 +15,6 @@ */ /** - * Example of integration with OCI object storage in reactive application. + * Example of integration with OCI object storage in Nima application. */ -package io.helidon.examples.integrations.oci.objecstorage.reactive; +package io.helidon.examples.integrations.oci.objecstorage; diff --git a/examples/integrations/oci/objectstorage-reactive/src/main/resources/application.yaml b/examples/integrations/oci/objectstorage/src/main/resources/application.yaml similarity index 92% rename from examples/integrations/oci/objectstorage-reactive/src/main/resources/application.yaml rename to examples/integrations/oci/objectstorage/src/main/resources/application.yaml index 4c07c154bc6..75e202bd486 100644 --- a/examples/integrations/oci/objectstorage-reactive/src/main/resources/application.yaml +++ b/examples/integrations/oci/objectstorage/src/main/resources/application.yaml @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2022 Oracle and/or its affiliates. +# Copyright (c) 2021, 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. diff --git a/examples/integrations/oci/objectstorage-reactive/src/main/resources/logging.properties b/examples/integrations/oci/objectstorage/src/main/resources/logging.properties similarity index 94% rename from examples/integrations/oci/objectstorage-reactive/src/main/resources/logging.properties rename to examples/integrations/oci/objectstorage/src/main/resources/logging.properties index 43cd0f29d7d..c09e76d612c 100644 --- a/examples/integrations/oci/objectstorage-reactive/src/main/resources/logging.properties +++ b/examples/integrations/oci/objectstorage/src/main/resources/logging.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2022 Oracle and/or its affiliates. +# Copyright (c) 2021, 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. diff --git a/examples/integrations/oci/pom.xml b/examples/integrations/oci/pom.xml index 6a8ff21c520..f427126ffaf 100644 --- a/examples/integrations/oci/pom.xml +++ b/examples/integrations/oci/pom.xml @@ -36,7 +36,7 @@ atp atp-cdi metrics - objectstorage-reactive + objectstorage objectstorage-cdi vault-reactive vault-cdi From 77ce21a853a6cc9a488f8119a70d91f86de89329 Mon Sep 17 00:00:00 2001 From: aserkes Date: Thu, 8 Jun 2023 13:48:47 +0200 Subject: [PATCH 4/6] OCI example - remove reactive from Vault Signed-off-by: aserkes --- examples/integrations/oci/pom.xml | 2 +- .../oci/vault/reactive/OciHandler.java | 51 ---- .../oci/vault/reactive/VaultService.java | 184 --------------- .../oci/{vault-reactive => vault}/pom.xml | 12 +- .../integrations/oci/vault}/OciVaultMain.java | 57 +++-- .../integrations/oci/vault/VaultService.java | 221 ++++++++++++++++++ .../integrations/oci/vault}/package-info.java | 6 +- .../src/main/resources/application.yaml | 2 +- .../src/main/resources/logging.properties | 2 +- 9 files changed, 261 insertions(+), 276 deletions(-) delete mode 100644 examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/OciHandler.java delete mode 100644 examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/VaultService.java rename examples/integrations/oci/{vault-reactive => vault}/pom.xml (85%) rename examples/integrations/oci/{vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive => vault/src/main/java/io/helidon/examples/integrations/oci/vault}/OciVaultMain.java (63%) create mode 100644 examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java rename examples/integrations/oci/{vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive => vault/src/main/java/io/helidon/examples/integrations/oci/vault}/package-info.java (76%) rename examples/integrations/oci/{vault-reactive => vault}/src/main/resources/application.yaml (95%) rename examples/integrations/oci/{vault-reactive => vault}/src/main/resources/logging.properties (94%) diff --git a/examples/integrations/oci/pom.xml b/examples/integrations/oci/pom.xml index f427126ffaf..e896103ba23 100644 --- a/examples/integrations/oci/pom.xml +++ b/examples/integrations/oci/pom.xml @@ -38,7 +38,7 @@ metrics objectstorage objectstorage-cdi - vault-reactive + vault vault-cdi diff --git a/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/OciHandler.java b/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/OciHandler.java deleted file mode 100644 index 1eee9e8b5f2..00000000000 --- a/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/OciHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2022 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.integrations.oci.vault.reactive; - -import java.util.function.Consumer; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.oracle.bmc.responses.AsyncHandler; - -final class OciHandler { - private static final Logger LOGGER = Logger.getLogger(OciHandler.class.getName()); - - private OciHandler() { - } - - static AsyncHandler ociHandler(Consumer handler) { - return new AsyncHandler<>() { - @Override - public void onSuccess(REQ req, RES res) { - handler.accept(res); - } - - @Override - public void onError(REQ req, Throwable error) { - LOGGER.log(Level.WARNING, "OCI Exception", error); - if (error instanceof Error) { - throw (Error) error; - } - if (error instanceof RuntimeException) { - throw (RuntimeException) error; - } - throw new RuntimeException(error); - } - }; - } -} diff --git a/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/VaultService.java b/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/VaultService.java deleted file mode 100644 index 492b8ff29f2..00000000000 --- a/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/VaultService.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 2021, 2022 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.integrations.oci.vault.reactive; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Date; - -import io.helidon.common.Base64Value; -import io.helidon.reactive.webserver.Handler; -import io.helidon.reactive.webserver.Routing; -import io.helidon.reactive.webserver.ServerRequest; -import io.helidon.reactive.webserver.ServerResponse; -import io.helidon.reactive.webserver.Service; - -import com.oracle.bmc.keymanagement.KmsCryptoAsync; -import com.oracle.bmc.keymanagement.model.DecryptDataDetails; -import com.oracle.bmc.keymanagement.model.EncryptDataDetails; -import com.oracle.bmc.keymanagement.model.SignDataDetails; -import com.oracle.bmc.keymanagement.model.VerifyDataDetails; -import com.oracle.bmc.keymanagement.requests.DecryptRequest; -import com.oracle.bmc.keymanagement.requests.EncryptRequest; -import com.oracle.bmc.keymanagement.requests.SignRequest; -import com.oracle.bmc.keymanagement.requests.VerifyRequest; -import com.oracle.bmc.secrets.SecretsAsync; -import com.oracle.bmc.secrets.model.Base64SecretBundleContentDetails; -import com.oracle.bmc.secrets.model.SecretBundleContentDetails; -import com.oracle.bmc.secrets.requests.GetSecretBundleRequest; -import com.oracle.bmc.vault.VaultsAsync; -import com.oracle.bmc.vault.model.Base64SecretContentDetails; -import com.oracle.bmc.vault.model.CreateSecretDetails; -import com.oracle.bmc.vault.model.ScheduleSecretDeletionDetails; -import com.oracle.bmc.vault.model.SecretContentDetails; -import com.oracle.bmc.vault.requests.CreateSecretRequest; -import com.oracle.bmc.vault.requests.ScheduleSecretDeletionRequest; - -import static io.helidon.examples.integrations.oci.vault.reactive.OciHandler.ociHandler; - -class VaultService implements Service { - private final SecretsAsync secrets; - private final VaultsAsync vaults; - private final KmsCryptoAsync crypto; - private final String vaultOcid; - private final String compartmentOcid; - private final String encryptionKeyOcid; - private final String signatureKeyOcid; - - VaultService(SecretsAsync secrets, - VaultsAsync vaults, - KmsCryptoAsync crypto, - String vaultOcid, - String compartmentOcid, - String encryptionKeyOcid, - String signatureKeyOcid) { - this.secrets = secrets; - this.vaults = vaults; - this.crypto = crypto; - this.vaultOcid = vaultOcid; - this.compartmentOcid = compartmentOcid; - this.encryptionKeyOcid = encryptionKeyOcid; - this.signatureKeyOcid = signatureKeyOcid; - } - - @Override - public void update(Routing.Rules rules) { - rules.get("/encrypt/{text:.*}", this::encrypt) - .get("/decrypt/{text:.*}", this::decrypt) - .get("/sign/{text}", this::sign) - .post("/verify/{text}", Handler.create(String.class, this::verify)) - .get("/secret/{id}", this::getSecret) - .post("/secret/{name}", Handler.create(String.class, this::createSecret)) - .delete("/secret/{id}", this::deleteSecret); - } - - private void getSecret(ServerRequest req, ServerResponse res) { - secrets.getSecretBundle(GetSecretBundleRequest.builder() - .secretId(req.path().param("id")) - .build(), ociHandler(ociRes -> { - SecretBundleContentDetails content = ociRes.getSecretBundle().getSecretBundleContent(); - if (content instanceof Base64SecretBundleContentDetails) { - // the only supported type - res.send(Base64Value.createFromEncoded(((Base64SecretBundleContentDetails) content).getContent()) - .toDecodedString()); - } else { - req.next(new Exception("Invalid secret content type")); - } - })); - } - - private void deleteSecret(ServerRequest req, ServerResponse res) { - // has to be for quite a long period of time - did not work with less than 30 days - Date deleteTime = Date.from(Instant.now().plus(30, ChronoUnit.DAYS)); - - String secretOcid = req.path().param("id"); - - vaults.scheduleSecretDeletion(ScheduleSecretDeletionRequest.builder() - .secretId(secretOcid) - .scheduleSecretDeletionDetails(ScheduleSecretDeletionDetails.builder() - .timeOfDeletion(deleteTime) - .build()) - .build(), ociHandler(ociRes -> res.send("Secret " + secretOcid - + " was marked for deletion"))); - } - - private void createSecret(ServerRequest req, ServerResponse res, String secretText) { - SecretContentDetails content = Base64SecretContentDetails.builder() - .content(Base64Value.create(secretText).toBase64()) - .build(); - - vaults.createSecret(CreateSecretRequest.builder() - .createSecretDetails(CreateSecretDetails.builder() - .secretName(req.path().param("name")) - .vaultId(vaultOcid) - .compartmentId(compartmentOcid) - .keyId(encryptionKeyOcid) - .secretContent(content) - .build()) - .build(), ociHandler(ociRes -> res.send(ociRes.getSecret().getId()))); - } - - private void verify(ServerRequest req, ServerResponse res, String signature) { - String text = req.path().param("text"); - VerifyDataDetails.SigningAlgorithm algorithm = VerifyDataDetails.SigningAlgorithm.Sha224RsaPkcsPss; - - crypto.verify(VerifyRequest.builder() - .verifyDataDetails(VerifyDataDetails.builder() - .keyId(signatureKeyOcid) - .signingAlgorithm(algorithm) - .message(Base64Value.create(text).toBase64()) - .signature(signature) - .build()) - .build(), - ociHandler(ociRes -> { - boolean valid = ociRes.getVerifiedData() - .getIsSignatureValid(); - res.send(valid ? "Signature valid" : "Signature not valid"); - })); - } - - private void sign(ServerRequest req, ServerResponse res) { - crypto.sign(SignRequest.builder() - .signDataDetails(SignDataDetails.builder() - .keyId(signatureKeyOcid) - .signingAlgorithm(SignDataDetails.SigningAlgorithm.Sha224RsaPkcsPss) - .message(Base64Value.create(req.path().param("text")).toBase64()) - .build()) - .build(), ociHandler(ociRes -> res.send(ociRes.getSignedData() - .getSignature()))); - } - - private void encrypt(ServerRequest req, ServerResponse res) { - crypto.encrypt(EncryptRequest.builder() - .encryptDataDetails(EncryptDataDetails.builder() - .keyId(encryptionKeyOcid) - .plaintext(Base64Value.create(req.path().param("text")).toBase64()) - .build()) - .build(), ociHandler(ociRes -> res.send(ociRes.getEncryptedData().getCiphertext()))); - } - - private void decrypt(ServerRequest req, ServerResponse res) { - crypto.decrypt(DecryptRequest.builder() - .decryptDataDetails(DecryptDataDetails.builder() - .keyId(encryptionKeyOcid) - .ciphertext(req.path().param("text")) - .build()) - .build(), ociHandler(ociRes -> res.send(Base64Value.createFromEncoded(ociRes.getDecryptedData() - .getPlaintext()) - .toDecodedString()))); - } -} diff --git a/examples/integrations/oci/vault-reactive/pom.xml b/examples/integrations/oci/vault/pom.xml similarity index 85% rename from examples/integrations/oci/vault-reactive/pom.xml rename to examples/integrations/oci/vault/pom.xml index f3ef3e400ed..588d6642305 100644 --- a/examples/integrations/oci/vault-reactive/pom.xml +++ b/examples/integrations/oci/vault/pom.xml @@ -29,18 +29,18 @@ io.helidon.examples.integrations.oci - helidon-examples-integrations-oci-vault-reactive - Helidon Examples Integration OCI Vault Reactive - Reactive integration with OCI Vault. + helidon-examples-integrations-oci-vault + Helidon Examples Integration OCI Vault + Nima integration with OCI Vault. - io.helidon.examples.integrations.oci.vault.reactive.OciVaultMain + io.helidon.examples.integrations.oci.vault.OciVaultMain - io.helidon.reactive.webserver - helidon-reactive-webserver + io.helidon.nima.webserver + helidon-nima-webserver io.helidon.config diff --git a/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/OciVaultMain.java b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/OciVaultMain.java similarity index 63% rename from examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/OciVaultMain.java rename to examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/OciVaultMain.java index 51581058603..628e293efcd 100644 --- a/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/OciVaultMain.java +++ b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/OciVaultMain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -14,25 +14,24 @@ * limitations under the License. */ -package io.helidon.examples.integrations.oci.vault.reactive; +package io.helidon.examples.integrations.oci.vault; import java.io.IOException; +import com.oracle.bmc.keymanagement.KmsCrypto; +import com.oracle.bmc.keymanagement.KmsCryptoClient; +import com.oracle.bmc.secrets.Secrets; +import com.oracle.bmc.secrets.SecretsClient; +import com.oracle.bmc.vault.Vaults; +import com.oracle.bmc.vault.VaultsClient; import io.helidon.logging.common.LogConfig; import io.helidon.config.Config; -import io.helidon.reactive.webserver.Routing; -import io.helidon.reactive.webserver.WebServer; import com.oracle.bmc.ConfigFileReader; import com.oracle.bmc.auth.AuthenticationDetailsProvider; import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; -import com.oracle.bmc.keymanagement.KmsCryptoAsync; -import com.oracle.bmc.keymanagement.KmsCryptoAsyncClient; import com.oracle.bmc.model.BmcException; -import com.oracle.bmc.secrets.SecretsAsync; -import com.oracle.bmc.secrets.SecretsAsyncClient; -import com.oracle.bmc.vault.VaultsAsync; -import com.oracle.bmc.vault.VaultsAsyncClient; +import io.helidon.nima.webserver.WebServer; import static io.helidon.config.ConfigSources.classpath; import static io.helidon.config.ConfigSources.file; @@ -70,28 +69,28 @@ public static void main(String[] args) throws IOException { // ~/.oci/config AuthenticationDetailsProvider authProvider = new ConfigFileAuthenticationDetailsProvider(ConfigFileReader.parseDefault()); - SecretsAsync secrets = SecretsAsyncClient.builder().build(authProvider); - KmsCryptoAsync crypto = KmsCryptoAsyncClient.builder() + Secrets secrets = SecretsClient.builder().build(authProvider); + KmsCrypto crypto = KmsCryptoClient.builder() .endpoint(cryptoEndpoint) .build(authProvider); - VaultsAsync vaults = VaultsAsyncClient.builder().build(authProvider); + Vaults vaults = VaultsClient.builder().build(authProvider); + + WebServer server = WebServer.builder() + .routing(routing -> routing + .register("/vault", new VaultService(secrets, + vaults, + crypto, + vaultOcid, + compartmentOcid, + encryptionKey, + signatureKey)) + .error(BmcException.class, (req, res, ex) -> res.status( + ex.getStatusCode()).send(ex.getMessage()))) + .port(config.get("server.port").asInt().orElse(8080)) + .start(); + + System.out.println("WEB server is up! http://localhost:" + server.port()); - WebServer.builder() - .config(config.get("server")) - .routing(Routing.builder() - .register("/vault", new VaultService(secrets, - vaults, - crypto, - vaultOcid, - compartmentOcid, - encryptionKey, - signatureKey)) - // OCI SDK error handling - .error(BmcException.class, (req, res, ex) -> res.status(ex.getStatusCode()) - .send(ex.getMessage()))) - .build() - .start() - .await(); } private static Config buildConfig() { diff --git a/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java new file mode 100644 index 00000000000..3a89ea5f361 --- /dev/null +++ b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2021, 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.integrations.oci.vault; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.function.Consumer; +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.oracle.bmc.keymanagement.KmsCrypto; +import com.oracle.bmc.keymanagement.responses.DecryptResponse; +import com.oracle.bmc.keymanagement.responses.EncryptResponse; +import com.oracle.bmc.keymanagement.responses.SignResponse; +import com.oracle.bmc.keymanagement.responses.VerifyResponse; +import com.oracle.bmc.secrets.Secrets; +import com.oracle.bmc.secrets.responses.GetSecretBundleResponse; +import com.oracle.bmc.vault.Vaults; +import com.oracle.bmc.vault.responses.CreateSecretResponse; +import io.helidon.common.Base64Value; +import io.helidon.common.http.Http; +import io.helidon.nima.webserver.http.*; + +import com.oracle.bmc.keymanagement.model.DecryptDataDetails; +import com.oracle.bmc.keymanagement.model.EncryptDataDetails; +import com.oracle.bmc.keymanagement.model.SignDataDetails; +import com.oracle.bmc.keymanagement.model.VerifyDataDetails; +import com.oracle.bmc.keymanagement.requests.DecryptRequest; +import com.oracle.bmc.keymanagement.requests.EncryptRequest; +import com.oracle.bmc.keymanagement.requests.SignRequest; +import com.oracle.bmc.keymanagement.requests.VerifyRequest; +import com.oracle.bmc.secrets.model.Base64SecretBundleContentDetails; +import com.oracle.bmc.secrets.model.SecretBundleContentDetails; +import com.oracle.bmc.secrets.requests.GetSecretBundleRequest; +import com.oracle.bmc.vault.model.Base64SecretContentDetails; +import com.oracle.bmc.vault.model.CreateSecretDetails; +import com.oracle.bmc.vault.model.ScheduleSecretDeletionDetails; +import com.oracle.bmc.vault.model.SecretContentDetails; +import com.oracle.bmc.vault.requests.CreateSecretRequest; +import com.oracle.bmc.vault.requests.ScheduleSecretDeletionRequest; + +class VaultService implements HttpService { + + private static final Logger LOGGER = Logger.getLogger(VaultService.class.getName()); + private final Secrets secrets; + private final Vaults vaults; + private final KmsCrypto crypto; + private final String vaultOcid; + private final String compartmentOcid; + private final String encryptionKeyOcid; + private final String signatureKeyOcid; + + VaultService(Secrets secrets, + Vaults vaults, + KmsCrypto crypto, + String vaultOcid, + String compartmentOcid, + String encryptionKeyOcid, + String signatureKeyOcid) { + this.secrets = secrets; + this.vaults = vaults; + this.crypto = crypto; + this.vaultOcid = vaultOcid; + this.compartmentOcid = compartmentOcid; + this.encryptionKeyOcid = encryptionKeyOcid; + this.signatureKeyOcid = signatureKeyOcid; + } + + /** + * A service registers itself by updating the routine rules. + * + * @param rules the routing rules. + */ + @Override + public void routing(HttpRules rules) { + rules.get("/encrypt/{text:.*}", this::encrypt) + .get("/decrypt/{text:.*}", this::decrypt) + .get("/sign/{text}", this::sign) + .post("/verify/{text}", this::verify) + .get("/secret/{id}", this::getSecret) + .post("/secret/{name}", this::createSecret) + .delete("/secret/{id}", this::deleteSecret); + } + + private void getSecret(ServerRequest req, ServerResponse res) { + ociHandler(response -> { + GetSecretBundleResponse id = secrets.getSecretBundle(GetSecretBundleRequest.builder() + .secretId(req.path().pathParameters().value("id")) + .build()); + SecretBundleContentDetails content = id.getSecretBundle().getSecretBundleContent(); + if (content instanceof Base64SecretBundleContentDetails) { + // the only supported type + res.send(Base64Value.createFromEncoded(((Base64SecretBundleContentDetails) content).getContent()) + .toDecodedString()); + } else { + res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send("Invalid secret content type"); + } + }, res); + + } + + private void deleteSecret(ServerRequest req, ServerResponse res) { + ociHandler(response -> { + // has to be for quite a long period of time - did not work with less than 30 days + Date deleteTime = Date.from(Instant.now().plus(30, ChronoUnit.DAYS)); + String secretOcid = req.path().pathParameters().value("id"); + vaults.scheduleSecretDeletion(ScheduleSecretDeletionRequest.builder() + .secretId(secretOcid) + .scheduleSecretDeletionDetails(ScheduleSecretDeletionDetails.builder() + .timeOfDeletion(deleteTime) + .build()) + .build() + ); + response.send(String.format("Secret %s was marked for deletion", secretOcid)); + }, res); + } + + private void createSecret(ServerRequest req, ServerResponse res) { + ociHandler(response -> { + String secretText = req.content().as(String.class); + SecretContentDetails content = Base64SecretContentDetails.builder() + .content(Base64Value.create(secretText).toBase64()) + .build(); + CreateSecretResponse vaultsSecret = vaults.createSecret(CreateSecretRequest.builder() + .createSecretDetails(CreateSecretDetails.builder() + .secretName(req.path().pathParameters().value("name")) + .vaultId(vaultOcid) + .compartmentId(compartmentOcid) + .keyId(encryptionKeyOcid) + .secretContent(content) + .build()) + .build()); + response.send(vaultsSecret.getSecret().getId()); + }, res); + } + + private void verify(ServerRequest req, ServerResponse res) { + + + ociHandler(response -> { + String text = req.path().pathParameters().value("text"); + String signature = req.content().as(String.class); + VerifyDataDetails.SigningAlgorithm algorithm = VerifyDataDetails.SigningAlgorithm.Sha224RsaPkcsPss; + VerifyResponse verifyResponse = crypto.verify(VerifyRequest.builder() + .verifyDataDetails(VerifyDataDetails.builder() + .keyId(signatureKeyOcid) + .signingAlgorithm(algorithm) + .message(Base64Value.create(text).toBase64()) + .signature(signature) + .build()) + .build()); + boolean valid = verifyResponse.getVerifiedData().getIsSignatureValid(); + response.send(valid ? "Signature valid" : "Signature not valid"); + }, res); + } + + private void sign(ServerRequest req, ServerResponse res) { + ociHandler(response -> { + SignResponse signResponse = crypto.sign(SignRequest.builder() + .signDataDetails(SignDataDetails.builder() + .keyId(signatureKeyOcid) + .signingAlgorithm(SignDataDetails.SigningAlgorithm.Sha224RsaPkcsPss) + .message(Base64Value.create(req.path() + .pathParameters().value("text")).toBase64()) + .build()) + .build()); + response.send(signResponse.getSignedData().getSignature()); + }, res); + } + + private void encrypt(ServerRequest req, ServerResponse res) { + ociHandler(response -> { + EncryptResponse encryptResponse = crypto.encrypt(EncryptRequest.builder() + .encryptDataDetails(EncryptDataDetails.builder() + .keyId(encryptionKeyOcid) + .plaintext(Base64Value.create(req.path() + .pathParameters().value("text")).toBase64()) + .build()) + .build()); + response.send(encryptResponse.getEncryptedData().getCiphertext()); + }, res); + } + + private void decrypt(ServerRequest req, ServerResponse res) { + ociHandler(response -> { + DecryptResponse decryptResponse = crypto.decrypt(DecryptRequest.builder() + .decryptDataDetails(DecryptDataDetails.builder() + .keyId(encryptionKeyOcid) + .ciphertext(req.path() + .pathParameters().value("text")) + .build()) + .build()); + response.send(Base64Value.createFromEncoded(decryptResponse.getDecryptedData().getPlaintext()) + .toDecodedString()); + }, res); + } + + private void ociHandler(Consumer consumer, ServerResponse response) { + try { + consumer.accept(response); + } catch (Throwable error) { + LOGGER.log(Level.WARNING, "OCI Exception", error); + response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(error.getMessage()); + } + } +} diff --git a/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/package-info.java b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/package-info.java similarity index 76% rename from examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/package-info.java rename to examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/package-info.java index 23e07e67fd2..deea60af35b 100644 --- a/examples/integrations/oci/vault-reactive/src/main/java/io/helidon/examples/integrations/oci/vault/reactive/package-info.java +++ b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/package-info.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -15,6 +15,6 @@ */ /** - * Example of OCI Vault integration in a reactive application. + * Example of OCI Vault integration in a Nima application. */ -package io.helidon.examples.integrations.oci.vault.reactive; +package io.helidon.examples.integrations.oci.vault; diff --git a/examples/integrations/oci/vault-reactive/src/main/resources/application.yaml b/examples/integrations/oci/vault/src/main/resources/application.yaml similarity index 95% rename from examples/integrations/oci/vault-reactive/src/main/resources/application.yaml rename to examples/integrations/oci/vault/src/main/resources/application.yaml index 982ef550c45..a61582e97b5 100644 --- a/examples/integrations/oci/vault-reactive/src/main/resources/application.yaml +++ b/examples/integrations/oci/vault/src/main/resources/application.yaml @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2022 Oracle and/or its affiliates. +# Copyright (c) 2021, 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. diff --git a/examples/integrations/oci/vault-reactive/src/main/resources/logging.properties b/examples/integrations/oci/vault/src/main/resources/logging.properties similarity index 94% rename from examples/integrations/oci/vault-reactive/src/main/resources/logging.properties rename to examples/integrations/oci/vault/src/main/resources/logging.properties index f8802f90626..341cef8ce9e 100644 --- a/examples/integrations/oci/vault-reactive/src/main/resources/logging.properties +++ b/examples/integrations/oci/vault/src/main/resources/logging.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2022 Oracle and/or its affiliates. +# Copyright (c) 2021, 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. From 2ffff6ec7fa211c9c6b9d6c72d4c37dd1916a50f Mon Sep 17 00:00:00 2001 From: aserkes Date: Fri, 9 Jun 2023 10:49:47 +0200 Subject: [PATCH 5/6] order import, change Nima WebServer builder Signed-off-by: aserkes --- .../integrations/oci/atp/AtpService.java | 10 ++++---- .../integrations/oci/atp/OciAtpMain.java | 4 ++-- .../oci/telemetry/OciMetricsMain.java | 12 ++++------ .../objecstorage/ObjectStorageService.java | 18 +++++++-------- .../objecstorage/OciObjectStorageMain.java | 1 + .../integrations/oci/vault/OciVaultMain.java | 18 +++++++-------- .../integrations/oci/vault/VaultService.java | 23 +++++++++++-------- 7 files changed, 43 insertions(+), 43 deletions(-) diff --git a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java index ce02d141811..0cce1a8273d 100644 --- a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java +++ b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java @@ -32,11 +32,6 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; -import com.oracle.bmc.ConfigFileReader; -import com.oracle.bmc.auth.AuthenticationDetailsProvider; -import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; -import com.oracle.bmc.database.Database; -import com.oracle.bmc.database.DatabaseClient; import io.helidon.common.http.Http; import io.helidon.config.Config; import io.helidon.config.ConfigException; @@ -47,6 +42,11 @@ import io.helidon.reactive.dbclient.DbClient; import io.helidon.reactive.dbclient.jdbc.JdbcDbClientProvider; +import com.oracle.bmc.ConfigFileReader; +import com.oracle.bmc.auth.AuthenticationDetailsProvider; +import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; +import com.oracle.bmc.database.Database; +import com.oracle.bmc.database.DatabaseClient; import com.oracle.bmc.database.model.GenerateAutonomousDatabaseWalletDetails; import com.oracle.bmc.database.requests.GenerateAutonomousDatabaseWalletRequest; import com.oracle.bmc.database.responses.GenerateAutonomousDatabaseWalletResponse; diff --git a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/OciAtpMain.java b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/OciAtpMain.java index e2aa3a3bb39..e63672babe9 100644 --- a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/OciAtpMain.java +++ b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/OciAtpMain.java @@ -18,8 +18,8 @@ import java.io.IOException; -import io.helidon.logging.common.LogConfig; import io.helidon.config.Config; +import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; import io.helidon.nima.webserver.http.HttpRouting; @@ -51,7 +51,7 @@ public static void main(String[] args) throws IOException { WebServer server = WebServer.builder() .routing(OciAtpMain::routing) - .port(config.get("server.port").asInt().orElse(8080)) + .config(config.get("server")) .start(); System.out.println("WEB server is up! http://localhost:" + server.port()); diff --git a/examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/OciMetricsMain.java b/examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/OciMetricsMain.java index 73a3181f23e..77e0ee9282c 100644 --- a/examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/OciMetricsMain.java +++ b/examples/integrations/oci/metrics/src/main/java/io/helidon/examples/integrations/oci/telemetry/OciMetricsMain.java @@ -23,19 +23,15 @@ import java.util.HashMap; import java.util.Map; -import com.oracle.bmc.monitoring.Monitoring; -import com.oracle.bmc.monitoring.MonitoringClient; -import io.helidon.logging.common.LogConfig; import io.helidon.config.Config; +import io.helidon.logging.common.LogConfig; import com.oracle.bmc.ConfigFileReader; import com.oracle.bmc.auth.AuthenticationDetailsProvider; import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; -import com.oracle.bmc.monitoring.model.Datapoint; -import com.oracle.bmc.monitoring.model.FailedMetricRecord; -import com.oracle.bmc.monitoring.model.MetricDataDetails; -import com.oracle.bmc.monitoring.model.PostMetricDataDetails; -import com.oracle.bmc.monitoring.model.PostMetricDataResponseDetails; +import com.oracle.bmc.monitoring.Monitoring; +import com.oracle.bmc.monitoring.MonitoringClient; +import com.oracle.bmc.monitoring.model.*; import com.oracle.bmc.monitoring.requests.PostMetricDataRequest; import com.oracle.bmc.monitoring.responses.PostMetricDataResponse; diff --git a/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java index 0bb732ef401..da42cb4e428 100644 --- a/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java +++ b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java @@ -24,13 +24,19 @@ import java.util.logging.Level; import java.util.logging.Logger; +import io.helidon.common.http.Http; +import io.helidon.config.Config; +import io.helidon.config.ConfigException; +import io.helidon.nima.webserver.http.HttpRules; +import io.helidon.nima.webserver.http.HttpService; +import io.helidon.nima.webserver.http.ServerRequest; +import io.helidon.nima.webserver.http.ServerResponse; + import com.oracle.bmc.ConfigFileReader; import com.oracle.bmc.auth.AuthenticationDetailsProvider; import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; -import com.oracle.bmc.objectstorage.ObjectStorageClient; -import io.helidon.common.http.Http; - import com.oracle.bmc.objectstorage.ObjectStorage; +import com.oracle.bmc.objectstorage.ObjectStorageClient; import com.oracle.bmc.objectstorage.requests.DeleteObjectRequest; import com.oracle.bmc.objectstorage.requests.GetNamespaceRequest; import com.oracle.bmc.objectstorage.requests.GetObjectRequest; @@ -39,12 +45,6 @@ import com.oracle.bmc.objectstorage.responses.GetNamespaceResponse; import com.oracle.bmc.objectstorage.responses.GetObjectResponse; import com.oracle.bmc.objectstorage.responses.PutObjectResponse; -import io.helidon.config.Config; -import io.helidon.config.ConfigException; -import io.helidon.nima.webserver.http.HttpRules; -import io.helidon.nima.webserver.http.HttpService; -import io.helidon.nima.webserver.http.ServerRequest; -import io.helidon.nima.webserver.http.ServerResponse; /** * REST API for the objecstorage example. diff --git a/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/OciObjectStorageMain.java b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/OciObjectStorageMain.java index 9ca86d19bee..16a882fa870 100644 --- a/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/OciObjectStorageMain.java +++ b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/OciObjectStorageMain.java @@ -56,6 +56,7 @@ public static void main(String[] args) { WebServer server = WebServer.builder() .routing(OciObjectStorageMain::routing) + .config(config.get("server")) .start(); } diff --git a/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/OciVaultMain.java b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/OciVaultMain.java index 628e293efcd..0d3cc69b323 100644 --- a/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/OciVaultMain.java +++ b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/OciVaultMain.java @@ -18,20 +18,20 @@ import java.io.IOException; -import com.oracle.bmc.keymanagement.KmsCrypto; -import com.oracle.bmc.keymanagement.KmsCryptoClient; -import com.oracle.bmc.secrets.Secrets; -import com.oracle.bmc.secrets.SecretsClient; -import com.oracle.bmc.vault.Vaults; -import com.oracle.bmc.vault.VaultsClient; -import io.helidon.logging.common.LogConfig; import io.helidon.config.Config; +import io.helidon.logging.common.LogConfig; +import io.helidon.nima.webserver.WebServer; import com.oracle.bmc.ConfigFileReader; import com.oracle.bmc.auth.AuthenticationDetailsProvider; import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; +import com.oracle.bmc.keymanagement.KmsCrypto; +import com.oracle.bmc.keymanagement.KmsCryptoClient; import com.oracle.bmc.model.BmcException; -import io.helidon.nima.webserver.WebServer; +import com.oracle.bmc.secrets.Secrets; +import com.oracle.bmc.secrets.SecretsClient; +import com.oracle.bmc.vault.Vaults; +import com.oracle.bmc.vault.VaultsClient; import static io.helidon.config.ConfigSources.classpath; import static io.helidon.config.ConfigSources.file; @@ -86,7 +86,7 @@ public static void main(String[] args) throws IOException { signatureKey)) .error(BmcException.class, (req, res, ex) -> res.status( ex.getStatusCode()).send(ex.getMessage()))) - .port(config.get("server.port").asInt().orElse(8080)) + .config(config.get("server")) .start(); System.out.println("WEB server is up! http://localhost:" + server.port()); diff --git a/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java index 3a89ea5f361..3b7bf256858 100644 --- a/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java +++ b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java @@ -23,19 +23,14 @@ import java.util.logging.Level; import java.util.logging.Logger; -import com.oracle.bmc.keymanagement.KmsCrypto; -import com.oracle.bmc.keymanagement.responses.DecryptResponse; -import com.oracle.bmc.keymanagement.responses.EncryptResponse; -import com.oracle.bmc.keymanagement.responses.SignResponse; -import com.oracle.bmc.keymanagement.responses.VerifyResponse; -import com.oracle.bmc.secrets.Secrets; -import com.oracle.bmc.secrets.responses.GetSecretBundleResponse; -import com.oracle.bmc.vault.Vaults; -import com.oracle.bmc.vault.responses.CreateSecretResponse; import io.helidon.common.Base64Value; import io.helidon.common.http.Http; -import io.helidon.nima.webserver.http.*; +import io.helidon.nima.webserver.http.HttpRules; +import io.helidon.nima.webserver.http.HttpService; +import io.helidon.nima.webserver.http.ServerRequest; +import io.helidon.nima.webserver.http.ServerResponse; +import com.oracle.bmc.keymanagement.KmsCrypto; import com.oracle.bmc.keymanagement.model.DecryptDataDetails; import com.oracle.bmc.keymanagement.model.EncryptDataDetails; import com.oracle.bmc.keymanagement.model.SignDataDetails; @@ -44,15 +39,23 @@ import com.oracle.bmc.keymanagement.requests.EncryptRequest; import com.oracle.bmc.keymanagement.requests.SignRequest; import com.oracle.bmc.keymanagement.requests.VerifyRequest; +import com.oracle.bmc.keymanagement.responses.DecryptResponse; +import com.oracle.bmc.keymanagement.responses.EncryptResponse; +import com.oracle.bmc.keymanagement.responses.SignResponse; +import com.oracle.bmc.keymanagement.responses.VerifyResponse; +import com.oracle.bmc.secrets.Secrets; import com.oracle.bmc.secrets.model.Base64SecretBundleContentDetails; import com.oracle.bmc.secrets.model.SecretBundleContentDetails; import com.oracle.bmc.secrets.requests.GetSecretBundleRequest; +import com.oracle.bmc.secrets.responses.GetSecretBundleResponse; +import com.oracle.bmc.vault.Vaults; import com.oracle.bmc.vault.model.Base64SecretContentDetails; import com.oracle.bmc.vault.model.CreateSecretDetails; import com.oracle.bmc.vault.model.ScheduleSecretDeletionDetails; import com.oracle.bmc.vault.model.SecretContentDetails; import com.oracle.bmc.vault.requests.CreateSecretRequest; import com.oracle.bmc.vault.requests.ScheduleSecretDeletionRequest; +import com.oracle.bmc.vault.responses.CreateSecretResponse; class VaultService implements HttpService { From 45b4d30e4369359aa3285b5fe4e17cbeda3efcfb Mon Sep 17 00:00:00 2001 From: aserkes Date: Wed, 14 Jun 2023 08:53:15 +0200 Subject: [PATCH 6/6] refactoring Signed-off-by: aserkes --- .../helidon/examples/integrations/oci/atp/AtpService.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java index 0cce1a8273d..fc2ce73e623 100644 --- a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java +++ b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java @@ -45,7 +45,6 @@ import com.oracle.bmc.ConfigFileReader; import com.oracle.bmc.auth.AuthenticationDetailsProvider; import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; -import com.oracle.bmc.database.Database; import com.oracle.bmc.database.DatabaseClient; import com.oracle.bmc.database.model.GenerateAutonomousDatabaseWalletDetails; import com.oracle.bmc.database.requests.GenerateAutonomousDatabaseWalletRequest; @@ -58,7 +57,7 @@ class AtpService implements HttpService { private static final Logger LOGGER = Logger.getLogger(AtpService.class.getName()); - private final Database databaseAsyncClient; + private final DatabaseClient databaseClient; private final Config config; AtpService(Config config) { @@ -66,7 +65,7 @@ class AtpService implements HttpService { // this requires OCI configuration in the usual place // ~/.oci/config AuthenticationDetailsProvider authProvider = new ConfigFileAuthenticationDetailsProvider(ConfigFileReader.parseDefault()); - databaseAsyncClient = DatabaseClient.builder().build(authProvider); + databaseClient = DatabaseClient.builder().build(authProvider); this.config = config; } catch (IOException e) { throw new ConfigException("Failed to read configuration properties", e); @@ -89,7 +88,7 @@ public void routing(HttpRules rules) { * @param res response */ private void generateWallet(ServerRequest req, ServerResponse res) { - GenerateAutonomousDatabaseWalletResponse walletResponse = databaseAsyncClient.generateAutonomousDatabaseWallet( + GenerateAutonomousDatabaseWalletResponse walletResponse = databaseClient.generateAutonomousDatabaseWallet( GenerateAutonomousDatabaseWalletRequest.builder() .autonomousDatabaseId(config.get("oci.atp.ocid").asString().get()) .generateAutonomousDatabaseWalletDetails(