Tuesday, October 01, 2019

Java Development with Autonomous Transaction Processing Dedicated (ATP-D)

The Oracle Autonomous Transaction Processing Dedicated (ATP-D) is a database Cloud service which allows implementing a private database Cloud service running on dedicated Exadata Infrastructure within the Oracle Public Cloud. The goal of this blog article is to help you, Java developer or architect, build and deploy fast, scalable, and reliable Java applications with ATP-D, using plain Java, Java Servlets, or Java Microservices with WebLogic, Helidon, WebSphere, Liberty, Tomcat, WildFly (JBoss), Spring, and so on.



Please read the full blog post @ https://medium.com/oracledevs/java-development-with-autonomous-transaction-processing-dedicated-atp-d-f0355a2f9abd

Oracle JDBC drivers on Maven Central



At last!

Yes, you asked for it, and with some delay (better late than ..), we did it!
Maven Central becomes a distribution center for the Oracle JDBC drivers. We started with the latest release 19.3.0.0 but will soon add previous and supported releases.
Read the full post @ https://medium.com/oracledevs/oracle-jdbc-drivers-on-maven-central-64fcf724d8b

Friday, August 09, 2019

OracleCode One 2019 - My Sessions Pick

OracleCode One 2019 is few weeks ahead and like many, you have not yet made up your mind on which sessions to attend or why attend?

Here is a selection of sessions that I highly recommend (full disclosure, I am involved in these sessions).




And you don't want to miss this exciting hands-on lab
See you there.

Thursday, March 29, 2018

Optimizing the Performance & Scalability of Java Applications that use an RDBMS

Preamble

There is an abundant literature on Java performance (books, articles, blogs, websites, and so on); a Google search returns more than 5 millions hits. To name a few, the Effective Java programming language guide, Java Performance the definitive guide, Java performance tuning newsletter and associated http://www.javaperformancetuning.com website. This is not the purpose of this post.

The goal of this post is to revisit the known best practices for speeding up and scaling database operations for Java applications then discuss database proxy and the upcoming standard Java API for asynchronous database access (ADBA).

Even those familiar with Java optimization techniques will learn new tips!

Speeding up Java applications that use an RDBMS


Optimizing database operations for Java applications includes: speeding up database connectivity, speeding up SQL statements processing, optimizing network traffic, and in-place processing. 

Speeding up Database Connectivity

Connection establishment is the most expensive database operation; the obvious optimization that
Java developers have been using for ages is connection pooling which avoid creating connections at runtime. 



Client-side Connection Pools

Java connection pools such as the Apache Commons DBCP, C3P0, as well as the Oracle  
Universal Connection Pool (UCP) and many others,  run as part of your stand-alone Java/JDBC
applications  along the JDBC libraries or as part of Java EE containers datasources (e.g.,
Tomcat, Weblogic, WebSphere and others). Java EE containers usually furnish their own
connection pools but they also allow replacing theirs with 3rd party pools (see using
UCP with Tomcat, UCP with Weblogic). 

Most Java developers use these client-side or mid-tier connection pools for sustaining small and
 medium workloads however, these connection pools are confined to the JRE/JDK instance
(i.e., can't be shared beyond the boundary of the JRE/JDK) and unpractical when deploying
thens of thousands of mid-tiers or Web servers. Even with very small pool size each, the RDBMS
 server  is overwhelmed by thens of thousands of pre-allocated connections that are idle (more
than 90% of the time).



Proxy Connection Pools

Proxy connection pools such as MySQL Router, Oracle Database Connection Manager in Traffic
 Director Mode (CMAN-TDM), and others, are part of proxy servers that sit between the database
 clients (i.e., Java apps) and the RDBMS. These allow thousands of database clients to share a 
common connection pool. I will discuss this a bit more, near the end of this post.

The Oracle database also furnishes database-side connection pools such as  the Shared Servers, and the Database Resident Connection Pool (DRCP). We will not discuss those in this post.

Other connection optimization features include: deferring connection health check and the 
de-prioritization of failed nodes.
   Deferring Connection Health Check

The ability of a connection pool such as Oracle's Universal Connection Pool (UCP) to avoid
checking the health of connections for a defined period of time, improves the latency of
connection check-out (i.e., getConnection() returns faster).

De-prioritization of Failed Nodes
In a multi-instances clustered database environment such as Oracle RAC,  this JDBC feature assigns
a low priority to a failed instance for a user-defined period of time thereby reducing the connection
establishment latency (iow, avoid attempting to get connections from the failed instance).


Optimizing Statements Processing

The default COMMIT mode with JDBC is Auto-COMMIT; unless this corresponds to your desire, 
you should explicitly disable Auto-COMMIT on the connection object.

conn.setAutoCommit(false);


Processing a SQL statement requires several steps including: parsing, binding variables, executing,
fetching resultSets (if a query), and COMMITting or ROLLBACKing the transaction (if a DML
i.e., Insert, Update, or Delete). 



Java developers have several options for optimizing SQL statements processing including: 
Prepared Statements, Statements Caching, ResultSets caching with change notification.


Prepared Statements

Parsing (i.e., hard parsing) is the most expensive operation during the processing of a SQL statement.
The best practice consists in avoiding parsing by using Prepared Statements which are parsed only once then reused many times on subsequent invocations, after binding variables. A security
 byproduct of Prepared Statements is to prevent SQL injection.

https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Statements Caching

Statement caching significantly improves performance.  The JDBC driver caches the SQL statements 
(PreparedStatements and CallableStatements) on close, using an LRU algorithm then refers
the RDBMS to the parsed form in its library cache (i.e., "use statement #2), during subsequent
invocations of the same statement.  Enabled by setting  Implicit statement caching  to true and
 allocating a statement cache in the driver memory (i.e., an array per physical connection).

  
OracleDataSource ods = new OracleDataSource(); 
... 
ods.setImplicitCachingEnabled( true ); 

ods.setStmtCacheSize(nn);

...

ResultSets Caching with Change Notification - the Hard Way (JDBC-OCI)

Caching JDBC result sets avoids re-executing the corresponding SQL query, resulting in dramatic
Java applications performance. RDBMSes allow caching ResultSet at the server side but the 
applications needs a roundtrip to the database to get these. Optimizing further, these result set can be
pushed to the drivers (Java, C/C++, PHP, C#, and so on) and grabbed by the applications without
 database roundtrips. 
Then what if the ResultSets become stale, out of sync with the actual RDBMS data? RDBMSes 
furnish mechanisms to maintain the ResultSets, up to date. For example, the Oracle database's Query
Change Notifications allows registering a SQL query with the RDBMS and receiving notifications
when committed DMLs from other threads render the ResultSets out of sync. 
Java applications may explicitly implement ResultSet caching with change notification through the
 following steps:

Prerequisite: grant CHANGE NOTIFICATION to the schema (i.e., database user); 

 grant change notification to HR;  // might need your DBA's help.

1) Create a registration


OracleConnection conn = ods.getConnection();
Properties prop = new Properties();
prop.setProperty(OracleConnection.DCN_NOTIFY_ROWIDS, "true");
prop.setProperty(OracleConnection.DCN_QUERY_CHANGE_NOTIFICATION,"true");
   ...
    DatabaseChangeRegistration dcr = conn.registerDatabaseChangeNotifictaion(prop);
    ...

2) Associate a query with the registration
  
  Statement stmt = conn.createStatement(); 
  // associating the query with the registration
  ((OracleStatement)stmt).setDatabaseChangeRegistration(dcr); 
  // any query that will be executed with the 'stmt' object will be associated with
  // the registration 'dcr' until 'stmt' is closed or 
  // '((OracleStatement)stmt).setDatabaseChangeRegistration(null);' is executed.
 ...



3) Listen to the notification
 ...
 // Attach the listener to the registration. 
 // Note: DCNListener is a custom listener and not a predefined or standard 
 // listener
 DCNListener list = new DCNListener(); dcr.addListener(list); 
 ...

 catch(SQLException ex) { 
 // if an exception occurs, we need to close the registration in order 
 // to interrupt the thread otherwise it will be hanging around. 
  if(conn != null) 
     conn.unregisterDatabaseChangeNotification(dcr); 
  throw ex; 
 }



ResultSets Caching with Change Notification - the Easy Way (JDBC Thin with DB 18c)

You may also enable ResultSet caching with invalidation, in a much easier way, using the following
 steps (once JDBC-Thin in Oracle database 18c is available on-premise).

1) Set the following database parameters in the database configuration file also known as
 INIT.ORA.
CLIENT_RESULT_CACHE_SIZE=100M // e.g., maximum cache size, in bytes
CLIENT_RESULT_CACHE_LAG=1000 // maximum delay for refreshing the cache (msec) 



2) Set the JDBC connection property oracle.jdbc.enableQueryResultCache to true (the default).



3) add the following hint to the SQL query string  "/*+ RESULT_CACHE */"

Example "SELECT /*+ RESULT_CACHE */ product_name, unit_price 
             FROM PRODUCTS WHERE unit_price > 100"

If changing the Java/JDBC source code to add the SQL hint is not an option, you can instruct the
 RDBMS to cache the ResultSets of all queries related to a specific table, either at table creation 
(default mode) or later (force mode); this is called Table annotation.

Examples              

CREATE TABLE products (...) RESULT_CACHE (MODE DEFAULT);
   ALTER TABLE products RESULT_CACHE (MODE FORCE);

The RDBMS furnishes views such as the V$RESULT_CACHE_STATISTICS and
a CLIENT_RESULT_CACHE_STATS$ table for monitoring the effectiveness of ResultSet caching.
See section 15  in the performance tuning guide for more details on configuring the server-side 
result set cache

Array Fetch

Array fetching is an absolute necessity when retrieving a large number of rows from a ResultSet.
The fetch size can be specified on Statement, PreparedStatement, CallableStatement, and 
ResultSet objects.
Example: pstmt.setFetchSize(20);



When using the Oracle database, this array size is capped by the RDBMS's internal buffer known as
Session Data Unit (SDU). The SDU buffer is used  for transferring data from the tables to the client, 
over the network. The size of this buffer, in bytes, can be specified in JDBC URL

      jdbc:oracle:thin:@(DESCRIPTION=(SDU=10240)
                     (ADDRESS=(PROTOCOL=tcp)(HOST=myhost-vip)(PORT=1521))
                     (CONNECT_DATA=(SERVICE_NAME=myorcldbservicename)))



or at the service level in Net Services configuration files sqlnet.ora and tnsnames.ora.
There is a hard limit depending on the RDBMS release: 2MB with DB 12c, 64K with DB 11.2,
 and 32K with DB pre-11.2.
In summary, even if you set the array fetch to a large number, it cannot retrieve more data than
the SDU permits.

Array DML (Update Batch)

The JDBC specification defines array operations as sending a batch of the same DML operations
(i.e.,  array INSERTs, array UPDATEs, array DELETE) for sequential execution at the server, 
thereby reducing network round-trips.

Update Batching consists in explicitly invoking the addBatch methods which adds a statement to
 an array operation then explicitly calling executeBatch method. 

...
 PreparedStatement pstmt =
  conn.prepareStatement("INSERT INTO employees VALUES(?, ?)");
pstmt.setInt(1, 2000);
pstmt.setString(2, "Milo Mumford");
pstmt.addBatch();
pstmt.setInt(1, 3000);
pstmt.setString(2, "Sulu Simpson");
pstmt.addBatch();
int[] updateCounts = pstmt.executeBatch();

...

Optimizing Network Traffic


Network Data Compression

The ability to compress data transmitted between the Java applications and the RDBMS over LAN or WAN reduces the volume of data, the transfert time and the number of roundtrips.

// Enabling Network Compression 
prop.setProperty("oracle.net.networkCompression","on"); 
// Optional configuration for setting the client compression threshold.
prop.setProperty("oracle.net.networkCompressionThreshold","1024"); ds.setConnectionProperties(prop); 
ds.setURL(url); 
Connection conn = ds.getConnection(); 
...

Sessions Multiplexing 


The Oracle database Connection Manager a.k.a. CMAN, furnishes the ability to funnel multiple database connections over a single network connection thereby saving OS resources.
See more details in the Net Services Admin guide.

In-Place Processing


As we have seen earlier, SQL statements execution involves a number of roundtrips between a database client i.e., Java mid-tier/web-server and the RDBMS; this is the rationales for using stored procedures. Even modern data processing such as Hadoop or Spark, collocate the processing and data for low latency.
All RDBMSes furnish stored procedures in various languages including proprietary procedural language such as Oracles PL/SQL but also Java, JavaScript, even PHP, Perl, Python, and TCL.
I discussed the pros and cons of stored procedures in chapter 1 of my book.
I'd add that in a modern micro-services based architecture, stored procedures are perfect for designing data-bound services.
The Oracle database furnishes Java and PL/SQL stored procedures. Java in the database is one of the best Oracle database gem; see some code samples on GitHub.

Scaling Out Java Applications that use an RDBMS


In this section, I will discuss scaling Java applications using Sharded databases, Multitenant databases, database proxy and the upcoming asynchronous Java database access API.

Horizontal Scaling of Java applications with Sharded Databases


Sharded database have been around for a while; think of shards as horizontal partitioning of tables across several databases (iow, partitions on steroids!).
The main impact for developers is that Java application must be Shard-aware; iow, the requirement to: (i) define which fields serve as sharding key, (ii) set the binding values and build the sharding key (and optionally, the super sharding key) before requesting a connection to the datasource. RDBMS vendors are actively working on a routing capability which will remove shard-awareness (see database proxy, later in this post).

Java SE 9 furnishes the standard APIs for building the sharding and supersharding keys.

DataSource ds = new MyDataSource();
     ShardingKey shardingKey = ds.createShardingKeyBuilder()
                           .subkey("abc", JDBCType.VARCHAR)
                           .subkey(94002, JDBCType.INTEGER)
                           .build();
 ...
 Connection con = ds.createConnectionBuilder()
                           .shardingKey(shardingKey)
                           .build();

Depending on the RDBMS implementation, the map of shards keys across all shard, also know as "shard topology" is maintained by an external mechanism known as the "Shard Director" (in  Oracle database implementation). Without further optimization, all connection requests (with a mandatory sharding key) go to the Shard Director which finds the corresponding shard then a connection is established with that shard.

A Shared Pool for Sharded DBs

The Oracle Universal Connection Pool (UCP) furnishes a shared single pool for all shards.
UCP has been enhanced to transparently suck the shard map (i.e., all the keys that map to a specific shard), from the Shard Director, during the first connection to a specific shard. Once UCP gets the keys range, it no longer needs to go to the Shard Director for subsequent connections requests related to that shard. After a little while, assuming your Java application randomly accesses all shards, UCP will get the entire shard topology from the Shard Director. A high availability byproduct of UCP acting as the Shard Director is that shard-aware Java applications can work even if the Shard Director is down.

Scaling Java Applications with Multi-Tenant Databases


Multi-tenancy is a key business requirement for enterprise Java applications. It could be simulated at the application level but true Multi-tenancy requires a Multi-tenant RDBMS where each tenant has it's own database.
Multi-tenant RDBMS scale by managing thousands of databases with one of very few database instances (an instance being the set of processes and memory structures necessary for managing a database), thereby reducing drastically the required computing resources.

How would Java applications scale with Multi-Tenant RDBMS?

A non Multi-tenant aware connection pool would allocate a pool per database, defeating the purpose.  UCP has been enhanced to use a single shared pool for all pluggable databases -- a.k.a. PDB (a PDB is the tenant specific database in Oracle's Multi-tenant architecture).
Upon a connection request to a specific PDB, if there is no free/available connection attached to that tenant database, UCP transparently repurposes an idle connection in the pool, which was attached to another PDB to be re-attached to this one, thereby allowing to use a small set of pooled connections to service all tenants while avoiding new connection creation (remember, this is very expensive!) and preserving system resources.
See the UCP doc for more details on using one datasource per tenant or a single datasource for all tenants.

Database proxy 


Proxies are man-in-the-middle software running between the database and its clients e.g., Java applications. There are several proxy offerings on the market; to name a few: MySQL Router, the Oracle Database Connection Manager in Traffic Director Mode (CMAN-TDM), ProxySQL, and so on.
The Oracle CMAN-TDM is new in Oracle database 18c; it is an extension of the existing Oracle Connection Manager a.k.a. CMAN and furnishes these new following capabilities
  • Fully transparent to applications
  • Routes database traffic to right instance (planned)
  • Hides database planned and unplanned outages to support zero application downtime
  • Optimizes database session usage and application performance 
  • Enhances database security
CMAN-TDM is client agnostic, iow, it supports all database clients applications including: Java, C, C++, DotNET, Node.js, Python, Ruby, R.
Java applications would connect to CMAN-TDM which, in its turn, connects to the database using the latest driver and libraries then transparently furnish the Quality of Service that the application would get only if it was using the latest driver and APIs. 

See more details in the CMAN landing page and the Net Services documentions linked from the landing page.

Asynchronous Java Database Access API (ADBA)


The existing JDBC API leads to blocked threads, threads scheduling, and contention; it is not suitable for reactive applications or high throughput and large-scale deployments. There exist non-standard asynchronous Java database access APIs but the Java community needs a standard one where user threads never block. User threads submit database operations and return; the API implementation takes care of executing the operations, independently of user threads.
This new API proposal is not intended to be an extension to, or a replacement for, JDBC but, rather, an entirely separate API that provides completely nonblocking access to the same databases as JDBC.


The new API proposal relies on the java.util.concurrent.CompletionStage interface; it is available for download from the OpenJDK sandbox @  http://tinyurl.com/java-async-db.
You can sed some examples in the latest JavaOne presentation @ http://bit.ly/2wi948k.

There was a suggestion on the mailing list http://mail.openjdk.java.net/pipermail/jdbc-spec-discuss/ to rather base he API on the Reactive Streams class java.util.concurrent.Flow; you can follow that discussion in the mailing list.

I would encourage all the readers of this blog to review the API and get involved in the discussion.

ADBA over JDBC

In order to help the community get a feel of ADBA, an alpha version of it that runs over the vanilla/synchronous JDBC -- that we are calling AoJ for ADBA over JDBC -- @ https://github.com/oracle/oracle-db-examples/tree/master/java/AoJ

Resources

Monday, September 04, 2017

My Sessions Recommendations for JavaOne and Oracle Open World 2017

Good Day,

JavaOne, and Oracle Open World are 4 exactly weeks away.

Here are some sessions related to Java, JDBC, OJVM (database embedded JVM), JavaScript Nashorn (JavaSCript data access, JavaScript stored procedures), Apache Spark, Apache Hadoop, Apache Flink, Apache Beam that I'd warmly recommend.

JavaOne 2017 Sessions Recommendations


OpenWorld 2017 Sessions Recommendations

Friday, May 26, 2017

Carbonated Java & JavaScript Stored Procedures

Carbonated Java Stored Procedures

For accessing JSON Collections and documents without any knowledge of SQL, Oracle furnishes the SODA for Java API. It allows a convenient access and navigation using the dot notation.

How to use SODA for Java in Java Stored Procedures? I have posted the steps, the code samples and scripts on GitHub.

Carbonated JavaScript Stored Procedures 

Nashorn allows interoperability between Java and javaScript. By leveraging such interoperability, I've been able to reuse SODA for Java with JavaScript Stored Procedures.

How to use SODA for Java in JavaScript Stored Procedures? I have posted the steps, the code samples and scripts on GitHub.

Enjoy!

Thursday, March 02, 2017

What's in Oracle Database 12c Release 2 for Java & JavaScript Developers?

Here is the summary of New Java & JavaScript Features in Oracle Database 12c Release 2 on Cloud and on-Premise
  • Java 8: Java 8 in JDBC/UCP and OJVM; JDBC 4.2
  • JavaScript with Nashorn: JDBC/UCP, OJVM
  • Performance: JIT (OJVM), Network Compression over WAN (JDBC), Configurable connection health check frequency (UCP), PL/SQL Callback interface (JDBC)
  • Scalability: Shared Pool for Multi-Tenant Database (UCP), Shared Pool for Sharded database (UCP), Sharding Key APIs (JDBC, UCP), DRCP Proxy session sharing, DRCP support for  multiple labels
  • High-Availability: Java APIs for FAN events (SimpleFan.jar), Planned Maintenance in the driver (JDBC), Application Continuity for XA Datasources, Transaction Guard for XA Datasource
  • Security: SSL v1.2 / TLS v 1.2 (JDBC)
  • Manageability: XMLconfiguration (UCP), Enable/disable/suspend/resume feature level logging (JDBC), MAX_THINK_TIME for Transactions in progress (DRCP), new statistics view and AWR reports  
  • Ease of Use : Web Services Callout (OJVM), Long Identifiers (OJVM), PL/SQL Boolean (JDBC), Debugger for OJVM (Java Debug Wire Protocol)
See our latest white paper for more details.

Friday, December 02, 2016

My Talks/Sessions at UKOUG Tech16

Hi guys,

If you plan to attend UKOUG Tech16, please check out my talks.sessions

  1.  Sunday 12/04 16:10  New JDBC & UCP Perf, Scalability & HA features in Oracle Database 12cR2 @
  2. Monday 12/05 17:55 A RESTful MicroService for JSON Processing in Oracle Database 12c R2 @  
  3. Wednesday 12/07 8:50 Hadoop, Spark & Flink Explained to Oracle DBAs & why They Should Care @ https://t.co/7CGLchAYAF
  4. Wednesday 12/07 15:10 Integrate BigData with Master Data: Oracle database table as Hadoop Datasource @
See you there



Wednesday, November 09, 2016

REST Enable Java or JavaScript in the Database

REST Enable Java or JavaScript in the Database

The Oracle REST Data Service (ORDS) allows you to turn Java stored procedures or JavaScript stored procedures into REST Web Services that you may publish these in the Oracle REST Data Service.
See more details @ http://www.oracle.com/technetwork/developer-tools/rest-data-services/overview/index.html

Prerequisite

This article assumes you've already loaded your Java or JavaScript code in the Oracle database 12c Release 2 (for JavaScript); for Java, any supported database release will do (Oracle has been supporting Java in the database since version 8i.)
This blog post describes how to load and run JavaScript in Oracle database 12c Release 12.2.

Download and Configure ORDS

1) First step: download the latest ORDS  @ http://www.oracle.com/technetwork/developer-tools/rest-data-services/downloads/index.html

2) Extract the zip file in a directory say ../ords.3.0.8

3) Configure and Install

$ ls 
docs logs params examples ords.war readme.html

Navigate into params directory and edit the ords_params.properties file.
Modify the standalone.http.port value to a desired port # (e.g., 8090) and save the file.

$vi params/ords_params.properties
#Tue Jul 26 05:23:16 UTC 2016
db.hostname=
db.port=
db.servicename=
db.sid=
db.username=APEX_PUBLIC_USER
migrate.apex.rest=false
rest.services.apex.add=
rest.services.ords.add=true
schema.tablespace.default=SYSAUX
schema.tablespace.temp=TEMP
standalone.http.port=8090
standalone.static.images=
user.tablespace.default=USERS
user.tablespace.temp=TEMP
~                                                                               
~                                                                               
~                                                                                                                                                              
~                                                                               
~                                                                               
"params/ords_params.properties" 17L, 467C                     1,1           All

Note: Do not modify any other property

$ java -jar ords.war
This Oracle REST Data Services instance has not yet been configured.
Please complete the following prompts

Enter the location to store configuration data:/u01/oracle/ords.3.0.6/ordsi
Enter the name of the database server [localhost]:
Enter the database listen port [1521]:
Enter 1 to specify the database service name, or 2 to specify the database SID [1]:
Enter the database service name:pdb1
Enter the database password for ORDS_PUBLIC_USER:
Confirm password:
Please login with SYSDBA privileges to verify Oracle REST Data Services schema.

Enter the username with SYSDBA privileges to verify the installation [SYS]:
Enter the database password for SYS:Welcome1
Confirm password:Welcome1
Enter 1 if you want to use PL/SQL Gateway or 2 to skip this step.
If using Oracle Application Express or migrating from mod_plsql then you must enter 1 [1]:2
Sep 07, 2016 3:53:19 AM oracle.dbtools.common.config.file.ConfigurationFilesBase update
INFO: Updated configurations: defaults, apex_pu
Installing Oracle REST Data Services version 3.0.6.176.08.46
... Log file written to /u01/oracle/ords.3.0.6/logs/ords_install_core_2016-09-07_035319_00534.log
... Verified database prerequisites
... Created Oracle REST Data Services schema
... Created Oracle REST Data Services proxy user
... Granted privileges to Oracle REST Data Services
... Created Oracle REST Data Services database objects
... Log file written to /u01/oracle/ords.3.0.6/logs/ords_install_datamodel_2016-09-07_035342_00050.log
Completed installation for Oracle REST Data Services version 3.0.6.176.08.46. Elapsed time: 00:00:23.840 

Enter 1 if you wish to start in standalone mode or 2 to exit [1]:1
Enter 1 if using HTTP or 2 if using HTTPS [1]:1
2016-09-07 03:54:28.867:INFO::main: Logging initialized @158428ms
Sep 07, 2016 3:54:29 AM oracle.dbtools.standalone.StandaloneJetty setupDocRoot
INFO: Disabling document root because the specified folder does not exist: /u01/oracle/ords.3.0.6/ordsi/ords/standalone/doc_root
2016-09-07 03:54:29.525:INFO:oejs.Server:main: jetty-9.2.z-SNAPSHOT
Sep 07, 2016 3:54:29 AM oracle.dbtools.auth.crypto.CryptoKeysGenerator startup
INFO: No encryption key found in configuration, generating key
Sep 07, 2016 3:54:29 AM oracle.dbtools.auth.crypto.CryptoKeysGenerator startup
INFO: No mac key found in configuration, generating key
Sep 07, 2016 3:54:29 AM oracle.dbtools.common.config.file.ConfigurationFilesBase update
INFO: Updated configurations: defaults
Sep 07, 2016 3:54:29 AM oracle.dbtools.auth.crypto.CryptoKeysGenerator startup
INFO: Updated configuration with generated keys
2016-09-07 03:54:29.793:INFO:/ords:main: INFO: Using configuration folder: /u01/oracle/ords.3.0.6/ordsi/ords
2016-09-07 03:54:29.793:INFO:/ords:main: FINEST: |ApplicationContext [configurationFolder=/u01/oracle/ords.3.0.6/ordsi/ords, services=Application Scope]|
Sep 07, 2016 3:54:29 AM oracle.dbtools.common.config.db.DatabasePools validatePool
INFO: Validating pool: |apex|pu|
Sep 07, 2016 3:54:29 AM oracle.dbtools.common.config.db.DatabasePools validatePool
INFO: Pool: |apex|pu| is correctly configured
config.dir
2016-09-07 03:54:30.298:INFO:/ords:main: INFO: Oracle REST Data Services initialized|Oracle REST Data Services version : 3.0.6.176.08.46|Oracle REST Data Services server info: jetty/9.2.z-SNAPSHOT|
2016-09-07 03:54:30.305:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@429bd883{/ords,null,AVAILABLE}
2016-09-07 03:54:30.346:INFO:oejs.ServerConnector:main: Started ServerConnector@b7f23d9{HTTP/1.1}{0.0.0.0:8090}
2016-09-07 03:54:30.348:INFO:oejs.Server:main: 
Started @159913ms   

4) Allow your schema to use ORDS 

SQL> exec ords.enable_schema;
SQL> COMMIT;     

Define and Configure Your ORDS Service

Let's use the JavaScript procedure defined in an earlier blog post @
http://db360.blogspot.in/2016/11/javascript-in-oracle-database-12c.html

Rem Create a procedure based on the select.js and it's javax.script wrapper (see the previous blog post)
CREATE OR REPLACE PROCEDURE selectproc(id IN varchar2)
IS
   output varchar2(10000);
BEGIN
   SELECT invokeScriptEval(id) INTO output from dual;
   htp.prn(output);
END;
/
SHOW ERRORS;

-- delete load.routes module
begin
  ords_services.delete_module(
   p_name => 'load.routes');
  commit;
end;
/
SHOW ERRORS;

-- External JS select query
-- URL: load/routes/nashorn/select
-- procedure: selectproc
begin
  ords.create_service(
    p_module_name => 'load.routes' ,
    p_base_path   => '/load/routes/',
    p_pattern     => 'nashorn/selectbyid/:id',
    p_source_type => 'plsql/block',
    p_source      => 'begin selectproc(:id); end;'
);
   commit;
end;
/
SHOW ERRORS;  

Let's use the JavaScript procedure defined in an earlier blog post 
Open your  web browser and navigate to  http://localhost:8090/ords/ordstest/load/routes/nashorn/selectbyid/100.
 You must see the JSON document of the employee with empid as 100 displayed.
That's it! You have just created your first ORDS service
The same process can be used tor Java stored procedures or other JavaScript procedures in the database.

JavaScript in Oracle Database 12c Release 2

JSR 223 introduced the idea of Scripting for the Java platform. Java 8 furnishes the Nashorn JavaScript engine as a more performant replacement for Rhino 
Per the Redmonk ranking (http://redmonk.com/sogrady/2016/07/20/language-rankings-6-16/) and the TIOBE index (http://www.tiobe.com/tiobe-index), JavaScript is one the most popular programming languages, disputing the top seat with Java.

This blog post is an update to a previous post which discussed the rationales and a proof of concept of Nashorn (JavaScript on the JVM) and Avatar.js (Node.js APIs on the JVM. This update discusses the real production implementation of Nashorn on the JVM in rhe database.

Rationales for JavaScript in the Database


The embedded JVM in Oracle Database 12c Release 2 (a.k.a. OJVM) supports Java 8 and the Nashorn JavaScript engine.Running JavaScript in the database stemmed from the same motivations for running Java in the database namely: reuse of skills, libraries and code for implementing data-bound modules or applications and performance.

However, JavaScript in the database makes sense only when it is processing data stored in the database thereby - and this is another major motivation -- yielding better performance by the virtue of running close to the data. The beauty of the Nashorn JavaScript engine on the JVM is the ability to call Java APIs from JavaScript e.g., calling JDBC APIs from JavaScript, for database access.

Let's create an EMPLOEES table storing employees data as JSON documents

CREATE TABLE employees (
  id    RAW(16) NOT NULL,
  data  CLOB,
  CONSTRAINT employees_pk PRIMARY KEY (id),
  CONSTRAINT employees_json_chk CHECK (data IS JSON)
);


INSERT INTO employees (id, data)
VALUES (SYS_GUID(),
        '{
          "EmpId"     : "100",
          "FirstName" : "Kuassi",
          "LastName"  : "Mensah",
          "Job"       : "Manager",
          "Email"     : "kuassi@oracle.com",
          "Address"   : {
                          "City" : "Redwood",
                          "Country" : "US"
                        }
         }');

...
...

INSERT INTO employees (id, data)
VALUES (SYS_GUID(),
        '{
          "EmpId"     : "300",
          "FirstName" : "Suresh",
          "LastName"  : "Mohan",
          "Job"       : "Developer",
          "Email"     : "Suresh@oracle.com",
          "Address"   : {
                          "City" : "Bangalore",
                          "Country" : "India"
                        }
         }');

COMMIT;

Here is a JavaScript code which uses JDBC for querying JSON documents stored in the EMPLOYEE table.

var selectQuery = function(id)
{
   var Driver = Packages.oracle.jdbc.OracleDriver;
   var oracleDriver = new Driver();
   var url = "jdbc:default:connection:";
   var output = "";
   var connection = oracleDriver.defaultConnection();
   var prepStmt;

   // Prepare statement    if(id == 'all') {
       prepStmt = connection.prepareStatement("SELECT a.data FROM employees a");
      } else {
       prepStmt = connection.prepareStatement("SELECT a.data FROM employees a WHERE a.data.EmpId = ?");
       prepStmt.setInt(1, id);
       }

   // execute Query   var resultSet = prepStmt.executeQuery();

   // display results   while(resultSet.next()) {
      output = output + resultSet.getString(1) + "
";
   }

   // cleanup    resultSet.close();
    prepStmt.close();
    connection.close();
    return output;
}

Fluent JavaScript API using SODA for Java with Nashorn

For accessing JSON Collections and documents, Oracle furnishes SODA for Java; this API allows No SQL and dot notation access to JSON.
Check out the code samples and scripts for running testSODA.java and testSODA.js in OJVM  

How to Run JavaScript in Oracle Database 


Your  schema (or database user) must be granted the DBJAVASCRIPT role (check with your DBA).
Your JavaScript source code (select.js) may originate from strings, files or Java resources.

function hello()
{
/*
*This is a sample Javascript file that prints "Hello World".
*/
var hellow = "Hello World";
return hellow;
}

var output = hello();
print(output);

Oracle recommends loading your JavaScript source code from a file into the database, as Java resource, using the loadjava utility

loadjava -v -u yourschema hello.js

Upon loading your JavaScrit code as a Java resource you may invoke it using: (i) either the dbms_java.javascript.run() procedure from SQL or PL/SQL, or (ii) DbmsJavaScript.run() Java call or the javax.script package.
Make sure that your database schema has been granted the DBJAVASCRIPT role.

Running JavaScript in the Database using DBMS_JAVA.JAVASCRIPT.RUN Procedure

From SQL or PL/SQL


SQL>set serveroutput on
SQL>call dbms_java.set_output(20000);
SQL>call dbms_javascript.run("hello.js"); 

Running JavaScript in the Database using DbmsJavaScript.run Java call

From Java running in the database

import oracle.aurora.rdbms.DbmsJavaScript; 
…
DbmsJavaScript.run("hello.js");

Notes: 

  • The direct invocation of Nashorn classes is restricted in Oracle JVM.
  • All scripting mode extensions are disabled in Oracle JVM.

Running JavaScript in the Database using the javax.script API

Invoking JavaScript in the database using the javax.script API requires the following steps:
  1. Instantiate a script manager
  2. Create an engine
  3. Pass your resource stream reader as the argument to the eval method of the engine
import javax.script.*;
import java.net.*;
import java.io.*;
...

// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine =
    factory.getEngineByName("javascript");
// create schema resource URL
URL url = Thread.currentThread()
    .getContextClassLoader().getResource("hello.js");
engine.eval(new InputStreamReader(url.openStream()));
...

These steps can be turned into a wrapper class (the signature may differ depending on your input parameters and return value(s).

Here is a javax.script wrapper for invoking select.js JavaScript function (shown earlier).


create or replace and compile java resource named "InvokeScript" as
import javax.script.*;
import java.net.*;
import java.io.*;

public class InvokeScript {    
public static String eval(String inputId) throws Exception {
 String output = new String();
    try {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();

        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("javascript");

        //read the script as a java resource
     engine.eval(new InputStreamReader(InvokeScript.class.getResourceAsStream("select.js")));
     // Alternative approach
     //engine.eval(Thread.currentThread().getContextClassLoader().getResource("select.js"));

        Invocable invocable = (Invocable) engine;
        Object selectResult = invocable.invokeFunction("selectQuery", inputId);
        output = selectResult.toString();
    } catch(Exception e) {
  output =e.getMessage();
 }
        return output;
    }
}
/

Then we need to create a SQL wrapper for the eval function

-- Create function
CREATE OR REPLACE FUNCTION invokeScriptEval(inputId varchar2) return varchar2 as language java 
name 'InvokeScript.eval(java.lang.String) 
  return java.lang.String'; 
/

Allow and make easy to call invokeScriptEval() from SQL or PL/SQL  

CREATE OR REPLACE PROCEDURE sqldemo(id IN varchar2)
IS
 output varchar2(10000);
BEGIN
 SELECT invokeScriptEval(id) INTO output from dual;
 dbms_output.put_line(output);
END;
/
SHOW ERRORS;
  
Finally, invoke SelectQuery function (in select.js), using Javax API thru SQLDEMO procedure

In a SQLPlus session
set serveroutput on
call dbms_java.set_output(5000);
call sqldemo('100');

REST Enabling JavaScript in the Database


You may turn your JavaScript function into a REST service deployed in Oracle Cloud by wrapping it with the Oracle Rest Data Service (ORDS). See the related blog post and the Java Developers guide in the Oracle Database 12c Release 2 doc library for more details.