- Notifications
You must be signed in to change notification settings - Fork24
SDK for Java for the Oracle NoSQL Database
License
oracle/nosql-java-sdk
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The Oracle NoSQL SDK for Java provides interfaces,documentation, and examples to help develop Javaapplications that connect to the Oracle NoSQLDatabase Cloud Service, Oracle NoSQL Database or to the Oracle NoSQLCloud Simulator (which runs on a local machine). In order torun the Oracle NoSQL Cloud Simulator, a separate download isnecessary from the Oracle NoSQL OTN download page. The Oracle NoSQLDatabase Cloud Service and Cloud Simulator are referred to as the "cloudservice" while the Oracle NoSQL Database is referred to as "on-premise."
The API for all environments is the same, with the exception of someenvironment-specific classes and methods, mostly related to authenticationand authorization. The API documentation clearly notes environment-specificinformation.
Java versions 8 and higher are supported.
The Oracle NoSQL SDK for Java can be included in a project in 2 ways:
- Include a dependency in a Maven project
- Download from GitHub
This dependency can be used to include the SDK and its dependencies in yourproject. The version changes with each release.
<dependency> <groupId>com.oracle.nosql.sdk</groupId> <artifactId>nosqldriver</artifactId> <version>6.0.0</version></dependency>You can download the Oracle NoSQL SDK for Java as an archive fromGitHub. The archivecontains the runtime library and its dependencies, examples, andAPI documentation.
SeeOracle NoSQL SDK for Java javadoc for the latest API documentation.
General documentation about the Oracle NoSQL Database and the Oracle NoSQL Database Cloud Service can be found in these locations:
SeeCHANGELOG for changes in each release.
There are 3 environments, or services that can be used by the Oracle NoSQLSDK for Java:
- Oracle NoSQL Database Cloud Service
- Oracle NoSQL Database On-premise
- Oracle NoSQL Database Cloud Simulator
The next sections describe how to connect to each and what information isrequired.
There are 3 ways to authorize an application using the Oracle NoSQL Database Cloud Service:
- As a cloud user, orUser Principal
- As anInstance Principal, where an instance is a compute instance in the Oracle cloud
- As aResource Principal, where the resource is a programmatic entity in the Oracle cloud such as an OCI Function
You will need an Oracle Cloud account and credentials to use this SDK. With thisinformation, you'll set up a client configuration to tell your application how tofind the cloud service, and how to properly authenticate.SeeAuthentication to connect to Oracle NoSQL Database for details of credentials you will need to configure an application. This only needs to be done once for any user.
You should have the following information in hand:
- Tenancy OCID
- User OCID
- Public key fingerprint
- Private key file
- Optional private key pass phrase
You can supply your user credentials in 2 ways:
- Using aConfiguration File
- Directly in aSignatureProvider constructor
See the Quickstart example below for details on using a User Principal
Instance Principal is an IAM service feature that enables instances to be authorized actors (or principals) to perform actions on service resources. Each compute instance has its own identity, and it authenticates using the certificates that are added to it. SeeCalling Services from an instance for prerequisite steps to set up Instance Principal.
See the Quickstart example below for code details for using an Instance Principal.
Resource Principal is an IAM service feature that enables the resources to be authorized actors (or principals) to perform actions on service resources. You may use Resource Principal when calling Oracle NoSQL Database Cloud Service from other Oracle Cloud service resource such asFunctions. SeeAccessing Other Oracle Cloud Infrastructure Resources from Running Functions for how to set up Resource Principal.
See the Quickstart example below for code details for using a Resource Principal.
The on-premises configuration requires a running instance of Oracle NoSQLDatabase. In addition, a running proxy service is required. SeeOracle NoSQL Database Downloads for downloads, and seeInformation about the proxyfor proxy configuration information.
On-premise authorization requires use ofStoreAccessTokenProviderSee the Quickstart example below for code details for connecting on-premise.
When you develop an application, you may wish to start withOracle NoSQL Database Cloud Simulator.
The Cloud Simulator simulates the cloud service and lets you write and testapplications locally without accessing the Oracle NoSQL Database Cloud Service.You may run the Cloud Simulator on localhost.
See the Quickstart example below for code details for connecting to the Cloud Simulator.Authorization for the Cloud Simulator is a simple no-op class implemented directlyin the Quickstart example.
Additional logging can be enabled using a java properties file. For full details, see"Logging in the SDK" athttps://oracle.github.io/nosql-java-sdk/oracle/nosql/driver/package-summary.html
The following is a quick start tutorial to run a simple program in all supportedenvironments. It requires access to the Oracle NoSQL Database Cloud Service,a running on-premises Oracle NoSQL Database instance, or a running OracleNoSQL Cloud Simulator instance. As a standalone program it will run most easilyusing a download version of the Oracle NoSQL SDK for Java.
- Copy this example into a local file named Quickstart.java
- If using directly-supplied cloud service credentials edit the file, addingcredentials in the appropriateSignatureProvider constructor. The default cloud service behavior looks for credentials in $HOME/.oci/config.
- Compile
$ javac -cp <path-to-nosqldriver.jar> Quickstart.java- RunUsing the cloud service on region us-ashburn-1
$ java -cp .:<path-to-nosqldriver.jar> Quickstart -service cloud -endpoint us-ashburn-1Using a non-secure on-premises service on endpointhttp://localhost:8090
$ java -cp .:<path-to-nosqldriver.jar> Quickstart -service onprem -endpoint http://localhost:8090Using a Cloud Simulator instance on endpointhttp://localhost:8080
$ java -cp .:<path-to-nosqldriver.jar> Quickstart -service cloudsim -endpoint http://localhost:8080There is code in the example for using Instance Principal and Resource Principal authorization for the cloudservice, but it is not enabled via a command line option. There is an additional, optional argument to thecommand line that allows specification of a compartment to use, where the compartment is an OCID. Thisis required if using Instance Principal or Resource Principal authorization.
/*- * Copyright (c) 2019, 2025 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl/ */import java.io.IOException;import java.util.ArrayList;import oracle.nosql.driver.AuthorizationProvider;import oracle.nosql.driver.NoSQLHandle;import oracle.nosql.driver.NoSQLHandleConfig;import oracle.nosql.driver.NoSQLHandleFactory;import oracle.nosql.driver.iam.SignatureProvider;import oracle.nosql.driver.kv.StoreAccessTokenProvider;import oracle.nosql.driver.ops.GetRequest;import oracle.nosql.driver.ops.GetResult;import oracle.nosql.driver.ops.QueryRequest;import oracle.nosql.driver.ops.QueryResult;import oracle.nosql.driver.ops.PutRequest;import oracle.nosql.driver.ops.PutResult;import oracle.nosql.driver.ops.QueryIterableResult;import oracle.nosql.driver.ops.Request;import oracle.nosql.driver.ops.TableLimits;import oracle.nosql.driver.ops.TableRequest;import oracle.nosql.driver.values.MapValue;/** * A simple quickstart program to demonstrate Oracle NoSQL Database. * It does these things: * - create a table * - put a row * - get a row * - run a query using iterable/iterator * - run a query using partial results * - drop the table * * See the examples for more interesting operations. This quickstart is * intended to illustrate connecting to a service and performing a few * operations. * * This program can be run against: * 1. the cloud service * 2. the on-premises proxy and Oracle NoSQL Database instance, secure or * not secure. * 3. the cloud simulator (CloudSim) * * To run: * java -cp .:../lib/nosqldriver.jar Quickstart \ * -service <cloud|onprem|cloudsim> -endpoint <endpoint-or-region> \ * [-compartment <ocid>] * * The endpoint and arguments vary with the environment. * * This quick start does not directly support a secure on-premise * environment. See the examples for details on that environment. */public class Quickstart { private String endpoint; private String service; /* required for Instance/Resource Principal auth and OKE workload identity */ private String compartment = null; // an OCID /* alternative cloud authorization mechanisms */ private final static boolean useUserPrincipal = true; private final static boolean useInstancePrincipal = false; private final static boolean useResourcePrincipal = false; private final static boolean useSessionToken = false; private final static boolean useOkeWorkloadIdentity = false; private Quickstart(String[] args) { /* * parse arguments */ for (int i = 0; i < args.length; i++) { if (args[i].equals("-service")) { service = args[++i]; } else if (args[i].equals("-endpoint")) { endpoint = args[++i]; } else if (args[i].equals("-compartment")) { compartment = args[++i]; } else { System.err.println("Unknown argument: " + args[i]); usage(); } } if (service == null || endpoint == null) { System.err.println("-service and -endpoint are required"); usage(); } } private static void usage() { System.err.println( "Usage: java -cp <path-to-nosqldriver.jar> Quickstart \\ \n" + " -service <cloud|onprem|cloudsim> -endpoint <endpoint-or-region>" + " \\ \n[-compartment <ocid>]"); System.exit(1); } private NoSQLHandle getHandle() { NoSQLHandleConfig config = new NoSQLHandleConfig(endpoint); if (compartment != null) { config.setDefaultCompartment(compartment); } /* * By default the handle will log to the console at level INFO. * The default logger can be configured using a logging properties * file specified on the command line, e.g.: * -Djava.util.logging.config.file=logging.properties * If a user-provided Logger is desired, create and set it here: * Logger logger = Logger.getLogger("..."); * config.setLogger(logger); * NOTE: the referenced classes must be imported above */ config.setRequestTimeout(5000); configureAuth(config); NoSQLHandle handle = NoSQLHandleFactory.createNoSQLHandle(config); System.out.println("Acquired handle for service " + service + " at endpoint " + endpoint); return handle; } /* * This method contains all service-specific code in this program */ private void configureAuth(NoSQLHandleConfig config) { if (service.equals("cloud")) { try { SignatureProvider authProvider = null; if (useUserPrincipal) { /* * Use User Principal authorization using a config * file in $HOME/.oci/config */ authProvider = new SignatureProvider(); /* * Credentials can be provided directly by editing the * appropriate information into the parameters below authProvider = new SignatureProvider(tenantId, // OCID userId, // OCID fingerprint, // String privateKeyFile, // File passphrase); // char[] */ } else if (useSessionToken) { /* * There are additional constructors for Session Token, * see the javadoc */ authProvider = SignatureProvider.createWithSessionToken(); } else { if (compartment == null) { throw new IllegalArgumentException( "Compartment is required for Instance/Resource " + "Principal authorization"); } /* * There are additional constructors for both Instance and * Resource Principal, see the javadoc */ if (useInstancePrincipal) { authProvider = SignatureProvider.createWithInstancePrincipal(); } else if (useResourcePrincipal) { authProvider = SignatureProvider.createWithResourcePrincipal(); } else if (useOkeWorkloadIdentity) { authProvider = SignatureProvider.createWithOkeWorkloadIdentity(); } else { throw new IllegalArgumentException( "Authorization method is required"); } } config.setAuthorizationProvider(authProvider); } catch (IOException ioe) { System.err.println("Unable to configure authentication: " + ioe); System.exit(1); } } else if (service.equals("onprem")) { config.setAuthorizationProvider(new StoreAccessTokenProvider()); } else if (service.equals("cloudsim")) { /* cloud simulator */ config.setAuthorizationProvider(new AuthorizationProvider() { @Override public String getAuthorizationString(Request request) { return "Bearer cloudsim"; } @Override public void close() { } }); } else { System.err.println("Unknown service: " + service); usage(); } } public static void main(String[] args) { final String tableName = "JavaQuickstart"; /* * The Quickstart instance configures and acquires a handle */ Quickstart qs = new Quickstart(args); /* * Configure and get a NoSQLHandle. All service specific configuration * is handled here */ try (NoSQLHandle handle = qs.getHandle()) { /* * Create a simple table with an integer key, string name and * JSON data */ final String createTableStatement = "create table if not exists " + tableName + "(id integer, name string, data json, primary key(id))"; TableRequest tableRequest = new TableRequest() .setStatement(createTableStatement) .setTableLimits(new TableLimits(10, 10, 10)); /* this call will succeed or throw an exception */ handle.doTableRequest(tableRequest, 20000, /* wait up to 20 sec */ 1000); /* poll once per second */ System.out.println("Created table " + tableName + " ..."); /* * Construct a row to put */ MapValue value = new MapValue() .put("id", 123) .put("name", "joe") .putFromJson("data", "{\"a\": 1, \"b\": 2}", null); PutRequest putRequest = new PutRequest() .setValue(value) .setTableName(tableName); PutResult putRes = handle.put(putRequest); System.out.println("Put row, result " + putRes); /* * Get a row using the primary key */ MapValue key = new MapValue().put("id", 123); GetRequest getRequest = new GetRequest() .setKey(key) .setTableName(tableName); GetResult getRes = handle.get(getRequest); System.out.println("Got row, result " + getRes); /* * Perform a query using iterable and iterator * * To ensure the query resources are closed properly, use * try-with-resources statement. */ try ( QueryRequest queryRequest = new QueryRequest() .setStatement("select * from " + tableName); QueryIterableResult results = handle.queryIterable(queryRequest)) { System.out.println("Query results:"); for (MapValue res : results) { System.out.println("\t" + res); } } /* * Perform a query using partial results */ try ( QueryRequest queryRequest = new QueryRequest() .setStatement("select * from " + tableName) ) { /* * Because a query can return partial results execution must occur * in a loop, accumulating or processing results */ ArrayList<MapValue> results = new ArrayList<MapValue>(); do { QueryResult queryResult = handle.query(queryRequest); results.addAll(queryResult.getResults()); } while (!queryRequest.isDone()); System.out.println("Query results again:"); for (MapValue res : results) { System.out.println("\t" + res); } } /* * Drop the table */ tableRequest = new TableRequest() .setStatement("drop table if exists " + tableName); handle.doTableRequest(tableRequest, 20000, 1000); System.out.println("Dropped table " + tableName + ", done..."); } }}Several example programs are provided in the examples directory toillustrate the API. They can be found in the release download from GitHub ordirectly inGitHub NoSQL Examples. These examples can be runagainst the Oracle NoSQLDatabase, the NoSQL Database Cloud Service or an instance of the OracleNoSQL Cloud Simulator. The code that differentiates among the configurationsis in the file Common.java and can be examined to understand the differences.
Examples can be run directly from a clone of theGitHub Repository. Once the clone has been built (mvn compile) examples canbe run in this manner
Run BasicTableExample using a cloud simulator instance on endpointlocalhost:8080
$ mvn -pl examples exec:java -Dexec.mainClass=BasicTableExample \ -Dexec.args="http://localhost:8080"Run BasicTableExample using an on-premises instance on endpointlocalhost:8090
$ mvn -pl examples exec:java -Dexec.mainClass=BasicTableExample \ -Dexec.args="http://localhost:8090 -useKVProxy"Run BasicTableExample using the cloud service on region us-ashburn-1
$ mvn -pl examples exec:java -Dexec.mainClass=BasicTableExample \ -Dexec.args="us-ashburn-1"Compile Examples:
$ cd examples$ javac -cp ../lib/nosqldriver.jar *.javaThis requires Oracle Cloud credentials. Credentials can be provided directly inAPI or in a configuration file. The default configuration inexamples/Common.java uses a configuration file in ~/.oci/config with thefollowing contents:
[DEFAULT]tenancy=<User OCID>user=<Tenancy OCID>fingerprint=<Public key fingerprint>key_file=<PEM private key file>pass_phrase=<Private key passphrase>Run the example using an Oracle Cloud region endpoint.
$ java -cp .:../lib/nosqldriver.jar BasicTableExample <region> e.g.$ java -cp .:../lib/nosqldriver.jar BasicTableExample us-ashburn-1The region argument will change depending on which region you use.
Running against the on-premises Oracle NoSQL Database on-premises requiresa running instance of the database and running proxy service. See above.
Run against a not-secure proxy and store, with the proxy running on port 80:
$ java -cp .:../lib/nosqldriver.jar BasicTableExample http://localhost:80 -useKVProxyWhen using a secure proxy and store the proxy will generally run on port 443 andrequires SSL configuration. In addition, the store requires a valid user andpassword which must have been created via administrative procedures.
Assumptions for this command:
- a driver.trust file in the current directory with the password "123456"
- user "driver" with password "Driver.User@01". This user must have been createdin the store and must have permission to create and use tables.
Run the command:
$ java -Djavax.net.ssl.trustStorePassword=123456 \ -Djavax.net.ssl.trustStore=driver.trust -cp .:../lib/nosqldriver.jar \ BasicTableExample https://localhost:443 -useKVProxy -user driver \ -password Driver.User@01Run against the Oracle NoSQL Cloud Simulator using its default endpointof localhost:8080, assuming that the Cloud Simulator has been started. Ifstarted on a different host or port adjust the endpoint accordingly.
$ java -cp .:../lib/nosqldriver.jar BasicTableExample localhost:8080See theLICENSE file.
TheTHIRD_PARTY_LICENSES file contains thirdparty notices and licenses.
- Open an issue in theIssues page
- Post your question on theOracle NoSQL Database Community.
- Email to nosql_sdk_help_grp@oracle.com
When requesting help please be sure to include as much detail as possible,including version of the SDK andsimple, standalone example code as needed.
SeeCONTRIBUTING for details.
SeeSECURITY for details.
About
SDK for Java for the Oracle NoSQL Database
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.