mercoledì 30 marzo 2016

Oracle Application Container Cloud & Developer Cloud Service: How to create a Node.js application with DB connection in pool (in cloud) and how to deploy it on Oracle Application Container Cloud (Node.js) using Developer Cloud Service


In this post I'll explain:
  • How to create (without an IDE) a local Node.js Application with DB connection (in Cloud) using the oracledb driver for node.js
  • How to package and load the Application on Oracle Application Container Cloud (Node.js Container)
  • How to create and test the same application with Eclipse 
  • How to push the Application on Oracle Developer Cloud Service (DevOps in Cloud)
  • How to use Developer Cloud Service to be able to automate the packaging & deploy operations on Oracle Application Container Cloud (Node.js Container)
You can DOWNLOAD from HERE the entire project (with source code) described in this post: DemoNode.zip

The Prerequisites:

For this guide you need to install on your local PC:
I suggest to follow this step by step guide for the installation of oracledb driver:
https://community.oracle.com/docs/DOC-931127:
  • I have succesfully tested the previous link on Windows 7. 
  • On Windows 10 I had a problem with Visual Studio executing the command "npm install oracledb" but I have solved it setting: 
    • set VCTargetsPath=C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120
This was the problem (the red part):


Once you have installed Node.js & oracledb driver, we can download the application from the examples page of oracledb:

From the Examples directory we need to get:
  • webapp.js - main project, with oracledb and pool connections
  • dbconfig.js - properties for oracledb connection
We will deploy the application on Oracle Application Container Cloud so we need to change two lines of code in webapp.js (to be able to test it both locally and remotely):
  • Change "var portid = 7000;" in "var portid = process.env.PORT || 80;"
  • Change "hs.listen(portid, "localhost");" in "hs.listen(portid);"
The application is using the following db schema:
https://github.com/oracle/db-sample-schemas/blob/master/human_resources/hr_cre.sql
You can download the schema with all the data from [HERE]

If you are using an oracle db you can find it under user HR.

I have used a DB in Cloud (Oracle Database Cloud Service):


Those are the required parameters to connect to the table Employee under user HR: (sqldeveloper image)
As described in this post, remember to select "Oracle Compute Cloud Service" then select "Network", here you must enable the seurity rules ora_p2_dblistener:


We must insert those parametrs in the file dbconfig.js:

 module.exports = {  
  user     : process.env.NODE_ORACLEDB_USER || "hr",  
  // Instead of hard coding the password, consider prompting for it,  
  // passing it in an environment variable via process.env, or using  
  // External Authentication.  
  password   : process.env.NODE_ORACLEDB_PASSWORD || "hr_pwd",  
  // For information on connection strings see:  
  // https://github.com/oracle/node-oracledb/blob/master/doc/api.md#connectionstrings  
  connectString : process.env.NODE_ORACLEDB_CONNECTIONSTRING || "141.145.26.28:1521/PDB1.gse00000410.oraclecloud.internal",  
  // Setting externalAuth is optional. It defaults to false. See:  
  // https://github.com/oracle/node-oracledb/blob/master/doc/api.md#extauth  
  externalAuth : process.env.NODE_ORACLEDB_EXTERNALAUTH ? true : false  
 };  

Put the webapp.js and dbconfig.js files (both modified as previous described) in a directory, open a command console and test your application in local:


We will talk about the manifest.json later.

Open a Command Console, go to the directory and execute the command "node webapp.js":


Open a Browser and test your application, the number after the "/" is required for the WHERE clause query in the webapp.js code "SELECT employee_id, first_name, last_name FROM employees WHERE  department_id = :id"  (try different numbers 10, 20, 30 ...100 ...)


It is time now to package our application in a zip file and to load it, manually, in Oracle Application Container Cloud - Node.js .

You mast create now a file named manifest.json with inside the command needed to start our application "node webapp.js".

This is our manifest.json file:

 {  
  "runtime":{  
   "majorVersion":"0.12"  
  },  
  "command": "node webapp.js",  
  "release": {},  
  "notes": ""  
 } 

Now we can create a zip file with inside: manifest.json, webapp.js and dbconfig.js:

The zip in our directory:


The content of our zip file:


Connect now to your Oracle Application Container Cloud and load your Application:
Click on Create Application and choose "Node":


Fille the required items and upload your zip file:
Select "Upload application archive" and click on the button "Choose File":


Select your file on your local disk and click open:


Click on Create:


After a while you will get this result:


Wait for the creation of the application:


Click on the generated URL to test your Application:


This is your application up and working:


We have created, packaged and deployed manually the application, now we will see how to use Eclipse and Developer Cloud Service to automate all the tasks of development/test,  packaging and deploy on Oracle Cloud:

I have installed on Eclipse the "nodeclipse plugin", to do this start a new project on Eclipse (OEPE: Oracle Enterprise Pack for Eclipse (12.2.1.2.1)) then select Help->Eclipse Marketplace ...

Search for nodeclipse and install it:


To create a new Node project select: File->New->Other ...
Select Node->Node.js Project:


Choose a name for your project (DemoNode) and click on Finish:


This is your new project:


Drag & Drop dbconfig.js, webapp.js, manifest.json on the root of your project:


To test your application:
right click on webapp.js and select Run As->Run Configurations ...


We need to add an environment variable with the path of the node.js modules:
NODE_PATH=c:\Users\fmarini\Desktop\NODE_JS\node_modules\


This is your environment variable:
Click Apply
Click Run


As you see in the console tab, your application is now up and running, on local pc, and you can test it with a browser:


Go to your DevCS domain and follow this previous post to create a new project with a Git repository:
http://www.fabriziomarini.com/2015/11/creating-project-git-repository-on.html

From Eclpse configure your Oracle Cloud Plugin connect it to your DevCs Domain, drag & Drop your project from Eclipse in the Oracle Cloud Plugin as described here:
http://www.fabriziomarini.com/2015/11/devops-oracle-cloudhow-to-create-from.html#OCPlugin

This is my DevCS, with an empty GIT repository:


This is my Eclipse project with the Oracle Cloud Plugin:
I have added in the project the following file [deploy.sh] :
IMPORTANT: Be sure that deploy.sh is saved with EOL in UNIX mode. (in notepad++ you can do this from Edit->EOL Conversion->UNIX/OSX Format)

 #!/bin/sh  
 export ID_DOMAIN=$1  
 export USER_ID=$2  
 export USER_PASSWORD=$3  
 export APP_NAME=$4  
 export ARCHIVE_FILE=$5  
 export ARCHIVE_LOCAL=$ARCHIVE_FILE  
 export APAAS_HOST=apaas.europe.oraclecloud.com  
 zip -r sites-cloud-service-apps.zip .  
 # CREATE CONTAINER  
 echo '\n[info] Creating container\n'  
 curl -i -X PUT \  
   -u ${USER_ID}:${USER_PASSWORD} \  
   https://${ID_DOMAIN}.storage.oraclecloud.com/v1/Storage-$ID_DOMAIN/$APP_NAME  
 # PUT ARCHIVE IN STORAGE CONTAINER  
 echo '\n[info] Uploading application to storage\n'  
 curl -i -X PUT \  
  -u ${USER_ID}:${USER_PASSWORD} \  
  https://${ID_DOMAIN}.storage.oraclecloud.com/v1/Storage-$ID_DOMAIN/$APP_NAME/$ARCHIVE_FILE \  
    -T $ARCHIVE_LOCAL  
 # See if application exists  
 let httpCode=`curl -i -X GET \  
  -u ${USER_ID}:${USER_PASSWORD} \  
  -H "X-ID-TENANT-NAME:${ID_DOMAIN}" \  
  -H "Content-Type: multipart/form-data" \  
  -sL -w "%{http_code}" \  
  https://${APAAS_HOST}/paas/service/apaas/api/v1.1/apps/${ID_DOMAIN}/${APP_NAME} \  
  -o /dev/null`  
 # If application exists...  
 if [ $httpCode == 200 ]  
 then  
  # Update application  
  echo '\n[info] Updating application...\n'  
  curl -i -X PUT \  
   -u ${USER_ID}:${USER_PASSWORD} \  
   -H "X-ID-TENANT-NAME:${ID_DOMAIN}" \  
   -H "Content-Type: multipart/form-data" \  
   -F archiveURL=${APP_NAME}/${ARCHIVE_FILE} \  
   https://${APAAS_HOST}/paas/service/apaas/api/v1.1/apps/${ID_DOMAIN}/${APP_NAME}  
 else  
  # Create application and deploy  
  echo '\n[info] Creating application...\n'  
  curl -i -X POST \  
   -u ${USER_ID}:${USER_PASSWORD} \  
   -H "X-ID-TENANT-NAME:${ID_DOMAIN}" \  
   -H "Content-Type: multipart/form-data" \  
   -F "name=${APP_NAME}" \  
   -F "runtime=node" \  
   -F "subscription=Hourly" \  
   -F archiveURL=${APP_NAME}/${ARCHIVE_FILE} \  
   https://${APAAS_HOST}/paas/service/apaas/api/v1.1/apps/${ID_DOMAIN}  
 fi  
 echo '\n[info] Deployment complete\n'  

In red I have marked some important part:

In you are not in Europe you need to change this
export APAAS_HOST=apaas.europe.oraclecloud.com

Here we are creating the zip file with the required manifest.json:
zip -r sites-cloud-service-apps.zip .

We are deploying in Node.js Container so we need:
-F "runtime=node" \

If you would like to use the same script in JavaSE Container change it in
-F "runtime=java" \


I have dragged and dropped DemoNode project on Demo_Node.js folder on the Cloud Plugin:
In the Synchronize window deselect "Generate or update Maven ..." and "Create Hudson build job", we will package and deploy the application with deploy.sh script that uses Rest API for Oracle Cloud, in this way (no Maven) you can learn a different way to use DevCS.


This is our local project synchronized with the Git on DevCS:


On the Code tab of DevCs you can see now your project:


We can create a new Build Job, select the Build tab and click on the green button New Job:


Choose a name for the build job:
Click Save:


In Source Control tab of you buil job select your Git repository:


In the Build Steps, click on Add Build Step and select Execute Shell:
Insert the following commands:

 cd DemoNode  
 /bin/sh -xe deploy.sh gse00000410 cloud.admin mypassword provaNodeJs sites-cloud-service-apps.zip  

With this command you go inside the directory DemoNode, here there are all the files of your project, there is also the deploy.sh.

You must pass some parameters to deploy.sh:
The Identity Domain : gse00000410
User: cloud.admin
Password : mypassword
Name of the project we want create on Oracle Application Container Cloud =  provaNodeJs
Zip file to upload: sites-cloud-service-apps.zip

Click the Save Button:


Click on Build Now button:


You can see a progress bar:


If everything goes well, you will get green icon:


Go to your Oracle Application Container Cloud and you will see the new project: (provaNodeJs)


Click on the generated URL to test it:



lunedì 21 marzo 2016

Oracle Application Container Cloud & Developer Cloud Service: How to create an application with Tomcat Embedded (with datasource) and how to deploy it on Oracle Application Container Cloud (JavaSE) using Developer Cloud Service


In this post I'll explain:
  1. how to create an application with Tomcat Embedded (7.x) using Eclipse & Maven
  2. how to use datasource and database connection with Tomcat Embedded & Maven
  3. how to use local maven repository to install/get Oracle Jdbc drivers
  4. how to connect to a remote database in cloud
  5. how to test the project on the local machine
  6. how to manually deploy the project on Oracle Application Container Cloud - JavaSE 
  7. how to push the local project on a remote DevOps system in Cloud (Oracle Developer Cloud Services)
  8. Hot to use the Maven Repository on DevCS
  9. how to automate operations as Building & Deploy in Developer Cloud Service
Please do not hesitate to contact me if something is not clear or wrong (or if you can improve this post), you can write comments in the post :)

DOWNLOAD from [HERE] the entire Eclipse project descibed in this post.(JavaSeContainerPrj.zip)

Important: All the passwords, users, IP addresses and Cloud Domains are not real :) remember that if you try to repeat the following guide you must always work in the same Oracle Cloud Domain.

You need to download & install:


------- How to create an application with Tomcat Embedded using Eclipse & Maven -------


Start your Eclipse and choose a name for your workspace:
I have choosed JavaSEContainer 
Remember the creation path that in my case is: C:\Users\Dell


Click on the Workbench icon on the right to start working on Eclipse:


We need now to create a web application with Maven to do this click on:
File-.>New->Other...
Select Maven>Maven Project
Click on Next:


Click on Next:


Choose maven-archetype-webapp
Click on Next


Choose a Group Id (acc)
Choose an Artifact Id (javase)
Click on Next:


You have now a Maven Web Project with a simple index.jsp page in javase/src/main/webapp
Now we will modify the pom.xml file:
Double click on it to open the file n the Eclipse editor:


Java web applications require a web container, such as Tomcat, to run on.

Installing and configuring a web container on each development machine can be time-consuming. Furthermore, other developers must manage the dependencies manually if they want to run the web application.

Add the following lines in the pom.xml just after
<finalName>javase</finalName>

<plugins>  
    <plugin>  
       <groupId>org.apache.tomcat.maven</groupId>  
       <artifactId>tomcat7-maven-plugin</artifactId>  
       <version>2.2</version>  
    </plugin>  
 </plugins>  


Right Click in the project
Run as… -> Maven build…


Add the goals in the goals field: clean install tomcat7:run
Click Run



As you can see in the Eclipse console you will have Tomcat running on :
http://localhost:8080/javase


Open your browser and test your web application:
http://localhost:8080/javase


To stop the server click on the red square on the right of the console tab:


We are able now to run and test our web application inside a Tomcat Embedded (we do not have installed Tomcat on our local system) but now we must add in the pom.xml all the dependencies required to run Tomcat in an embedded mode and the plugins to compile and package the project in a single uber JAR. (our target is to create a bootable jar file with inside Tomcat and our application deployed on it)

Add the following lines in our pom.xml:

Just after <url>http://maven.apache.org</url> insert:

<properties>  
   <tomcat.version>7.0.57</tomcat.version>  
</properties>  

just before </dependencies> insert:

   <dependency>  
     <groupId>org.apache.tomcat.embed</groupId>  
     <artifactId>tomcat-embed-core</artifactId>  
     <version>${tomcat.version}</version>  
   </dependency>  
   <dependency>  
     <groupId>org.apache.tomcat.embed</groupId>  
     <artifactId>tomcat-embed-logging-juli</artifactId>  
     <version>${tomcat.version}</version>  
   </dependency>  
   <dependency>  
     <groupId>org.apache.tomcat.embed</groupId>  
     <artifactId>tomcat-embed-jasper</artifactId>  
     <version>${tomcat.version}</version>  
   </dependency>  
   <dependency>  
     <groupId>org.apache.tomcat</groupId>  
     <artifactId>tomcat-jasper</artifactId>  
     <version>${tomcat.version}</version>  
   </dependency>  
   <dependency>  
     <groupId>org.apache.tomcat</groupId>  
     <artifactId>tomcat-jasper-el</artifactId>  
     <version>${tomcat.version}</version>  
   </dependency>  
   <dependency>  
     <groupId>org.apache.tomcat</groupId>  
     <artifactId>tomcat-jsp-api</artifactId>  
     <version>${tomcat.version}</version>  
   </dependency>  
   <dependency>  
     <groupId>jstl</groupId>  
     <artifactId>jstl</artifactId>  
     <version>1.2</version>  
   </dependency>

Important:
we need to be able to create a far file and to start it with a command like:
java -jar myfile.jar

This because in ACC (Oracle Application Container Cloud - JavaSE) we have "only" a JVM. (we will see later how to work with ACC)

To be able to execute the command java -jar myfile.jar we need to create a Main.java Class with a main method that creates an instance of the Tomcat server. This method is executed when you run the JAR file.

Right click with the mouse on the main directory (under javase->src) and select New->Other->Java->Class:


Choose java.com.acc as package name: (we need java for maven)


In the Main.java now correct the name of the package "package com.acc"


Add the following code in the Main.java:

package com.acc;  
 import java.util.Optional;  
 import org.apache.catalina.startup.Tomcat;  
 public class Main {  
   public static final Optional<String> port = Optional.ofNullable(System.getenv("PORT"));  
   public static void main(String[] args) throws Exception {  
     String contextPath = "/";  
     String appBase = ".";  
     Tomcat tomcat = new Tomcat();     
     tomcat.setPort(Integer.valueOf(port.orElse("8080") ));  
     tomcat.getHost().setAppBase(appBase);  
     tomcat.addWebapp(contextPath, appBase);  
     tomcat.start();  
     tomcat.getServer().await();  
   }  
 }  

The previous code will start Tomcat on port 8080.


Now we must add code to configure the following plugins:
  • The Maven Compiler Plugin (maven-compiler-plugin) is used to compile the sources of the project.
  • The Maven Assembly Plugin (maven-assembly-plugin) allows users to aggregate the project output along with its dependencies, modules, site documentation, and other files into a single distributable archive.
Build plugins are executed during the build. You configure the plugins in the <build> element of the POM.

To add the <build> element containing the <plugins> section, copy and paste the following code into the pom.xml file

<build>  
  <finalName>javase</finalName>  
  <resources>  
    <resource>  
      <directory>src/main/webapp</directory>  
      <targetPath>META-INF/resources</targetPath>  
    </resource>  
  </resources>  
  <plugins>  
    <plugin>  
      <groupId>org.apache.maven.plugins</groupId>  
      <artifactId>maven-compiler-plugin</artifactId>  
      <version>2.3.2</version>  
      <inherited>true</inherited>  
      <configuration>  
        <source>1.8</source>  
        <target>1.8</target>  
      </configuration>       
    </plugin>     
    <plugin>  
      <groupId>org.apache.maven.plugins</groupId>  
      <artifactId>maven-assembly-plugin</artifactId>  
      <configuration>  
        <descriptorRefs>  
          <descriptorRef>jar-with-dependencies</descriptorRef>  
        </descriptorRefs>  
        <finalName>${project.build.finalName}-${project.version}</finalName>  
        <archive>  
          <manifest>  
            <mainClass>com.acc.Main</mainClass>  
          </manifest>  
        </archive>  
      </configuration>  
      <executions>  
        <execution>  
          <phase>package</phase>  
          <goals>  
            <goal>single</goal>  
          </goals>  
        </execution>  
      </executions>  
    </plugin>     
  </plugins>  
 </build>   

We have removed the previous part that was for testing scope:

<plugins>  
    <plugin>  
       <groupId>org.apache.tomcat.maven</groupId>  
       <artifactId>tomcat7-maven-plugin</artifactId>  
       <version>2.2</version>  
    </plugin>  
 </plugins>  

Now your complete pom.xml must be like this:


 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>acc</groupId>  
  <artifactId>javase</artifactId>  
  <packaging>war</packaging>  
  <version>0.0.1-SNAPSHOT</version>  
  <name>javase Maven Webapp</name>  
  <url>http://maven.apache.org</url>  
  <properties>   
    <tomcat.version>7.0.57</tomcat.version>   
  </properties>  
  <dependencies>  
   <dependency>  
    <groupId>junit</groupId>  
    <artifactId>junit</artifactId>  
    <version>3.8.1</version>  
    <scope>test</scope>  
   </dependency>  
   <dependency>   
    <groupId>org.apache.tomcat.embed</groupId>   
    <artifactId>tomcat-embed-core</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat.embed</groupId>   
    <artifactId>tomcat-embed-logging-juli</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat.embed</groupId>   
    <artifactId>tomcat-embed-jasper</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat</groupId>   
    <artifactId>tomcat-jasper</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat</groupId>   
    <artifactId>tomcat-jasper-el</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat</groupId>   
    <artifactId>tomcat-jsp-api</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>jstl</groupId>   
    <artifactId>jstl</artifactId>   
    <version>1.2</version>   
   </dependency>  
  </dependencies>  
  <build>  
   <finalName>javase</finalName>  
   <resources>   
    <resource>   
     <directory>src/main/webapp</directory>   
     <targetPath>META-INF/resources</targetPath>   
    </resource>   
   </resources>   
   <plugins>  
   <plugin>   
    <groupId>org.apache.maven.plugins</groupId>   
    <artifactId>maven-compiler-plugin</artifactId>   
    <version>2.3.2</version>   
    <inherited>true</inherited>   
    <configuration>   
     <source>1.8</source>   
     <target>1.8</target>   
    </configuration>      
   </plugin>     
   <plugin>   
    <groupId>org.apache.maven.plugins</groupId>   
    <artifactId>maven-assembly-plugin</artifactId>   
    <configuration>   
     <descriptorRefs>   
      <descriptorRef>jar-with-dependencies</descriptorRef>   
     </descriptorRefs>   
     <finalName>${project.build.finalName}-${project.version}</finalName>   
     <archive>   
      <manifest>   
       <mainClass>com.acc.Main</mainClass>   
      </manifest>   
     </archive>   
    </configuration>   
    <executions>   
     <execution>   
      <phase>package</phase>   
      <goals>   
       <goal>single</goal>   
      </goals>   
     </execution>   
    </executions>   
   </plugin>  
   </plugins>  
  </build>  
 </project>  

We can compile and package the project and test it, but before you must verify that in your eclipse project you are using a jdk and not only the default jre installed on the system to do this right click with the mouse on the project name (javase) and select Properties:

Select Java Build Path:

Then Select your default JRE inside libraries tab and click the Edit Button to change it:



Click on the Installed JRE's... button



Click the Search button to choose your JDK directory the select it:


We can now Compile and Package:

Right click with the mouse on the name of the projest (javase) and select:
Run As->Maven Build ...

Choose a name (javase-mvn-clean-compile)
use "clean compile" as Goals

Click on Run:



This must be your output in the console:


Now we must package:

Right click with the mouse on the name of the projest (javase) and select:
Run As->Maven Build ...

Choose a name (javase-mvn-package)
use "package" as Goals

Click on Run:



You must obtain a Build Success on the console.

now open a cmd console and go in the target directory of your projest, usually Eclipse create the project under: c:\Users\<user_name>\<project_name>

In my PC is under:
c:\Users\Dell\JavaSEContainer\javase\target\

This is what you must have under your target directory:



Now we can start our Embedded Tomca with our project installed inside with the command:
java -jar javase-0.0.1-SNAPSHOT-jar-with-dependencies.jar


As you can see Tomcat is now running on localhost:8080:


Open your browser and test it:


Now we will modify the project and we will create a datasource in tomcat embedded and a jsp with a connection to an Oracle Database ...

------- How to use Datasource and Database connection with Tomcat Embedded & Maven -------

I suggest to download SQLDEVELOPER from OTN:
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index-097090.html

Once you have created a Database Cloud Service:
How to create an Oracle Database Service on Oracle Database Cloud Service

You can see the public IP address and the Connect String:


To access to the DBCS from sqldeveloper, you need to open some port on the Oracle Compute Cloud Service (the best way is to use ssh ... but this is a "learning" demo/post):

Select from the menu "Oracle Compute Cloud Service":


Now Select "Network", here you can enable or disable seurity rules: (this is my configuration)
You need to "Enable" the ora_p2_dblistener:


Now you can start sqldeveloper and create a new connection to DBCS:


 Put all the required information, and test your connection:


I'm connected and this will be the table that we will use in the demo:


We need, now, to download Oracle Jdbc Driver:

OTN JDBC Link:
http://www.oracle.com/technetwork/database/application-development/index-099369.html

OTN JDBC Download:
http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html

ojdbc7.jar (3,698,857 bytes) - (SHA1 Checksum: 7c9b5984b2c1e32e7c8cf3331df77f31e89e24c2)
Certified with JDK7 and JDK 8; It contains the JDBC driver classes except classes for NLS support in Oracle Object and Collection types.

Now we need to install the ojdbc7.jar in the default Maven repository in our local machine so we can insert a <dependency> in our pom.xm:

If you have installed mvn in a directory of your PC you can do this with a simple command:

mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc7 -Dversion=12.1.0.2 -Dpackaging=jar -Dfile=c:\Users\Dell\Desktop\ACCDemo\ojdbc7.jar -DgeneratePom=true

In the -Dfile parameter you must specify the directory in which you have downloaded the ojdbc7.jar drifer file.
We are using Eclipse so we will intall the jdbc driver with a wizard, to do this in the main menu tab, click on file->import ...

Then choose Mave->Install or deploy an artifact to a Maven repository :


Fill the required items:
Click Finish:


As you can see in the default .m2 directory (mvn plugin of Eclipse) now under repository there is the ojdbc7 driver installed:


We need now to add in the pom.xml of the project the following <dependency> for the ojdbc7.jar :


<dependency>  
  <groupId>com.oracle</groupId>  
  <artifactId>ojdbc7</artifactId>  
  <version>12.1.0.2</version>  
</dependency> 



We must insert also the JDBC/Datasource/dbcp <dependencies> for Tomcat:

<dependency>  
   <groupId>org.apache.tomcat</groupId>  
   <artifactId>tomcat-jdbc</artifactId>  
   <version>${tomcat.version}</version>  
 </dependency>  
 <dependency>  
   <groupId>org.apache.tomcat</groupId>  
   <artifactId>tomcat-dbcp</artifactId>  
   <version>${tomcat.version}</version>  
 </dependency> 


Your complete pom.xml now is like this:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>acc</groupId>  
  <artifactId>javase</artifactId>  
  <packaging>war</packaging>  
  <version>0.0.1-SNAPSHOT</version>  
  <name>javase Maven Webapp</name>  
  <url>http://maven.apache.org</url>  
  <properties>   
    <tomcat.version>7.0.57</tomcat.version>   
  </properties>  
  <dependencies>  
   <dependency>  
    <groupId>junit</groupId>  
    <artifactId>junit</artifactId>  
    <version>3.8.1</version>  
    <scope>test</scope>  
   </dependency>  
   <dependency>   
    <groupId>org.apache.tomcat.embed</groupId>   
    <artifactId>tomcat-embed-core</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat.embed</groupId>   
    <artifactId>tomcat-embed-logging-juli</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat.embed</groupId>   
    <artifactId>tomcat-embed-jasper</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat</groupId>   
    <artifactId>tomcat-jasper</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat</groupId>   
    <artifactId>tomcat-jasper-el</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>org.apache.tomcat</groupId>   
    <artifactId>tomcat-jsp-api</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
    <groupId>jstl</groupId>   
    <artifactId>jstl</artifactId>   
    <version>1.2</version>   
   </dependency>  
    <dependency>   
    <groupId>org.apache.tomcat</groupId>   
    <artifactId>tomcat-jdbc</artifactId>   
    <version>${tomcat.version}</version>   
   </dependency>   
   <dependency>   
   <groupId>org.apache.tomcat</groupId>   
   <artifactId>tomcat-dbcp</artifactId>   
   <version>${tomcat.version}</version>   
  </dependency>   
  <dependency>   
   <groupId>com.oracle</groupId>   
   <artifactId>ojdbc7</artifactId>   
   <version>12.1.0.2</version>   
  </dependency>   
  </dependencies>  
  <build>  
   <finalName>javase</finalName>  
   <resources>   
    <resource>   
     <directory>src/main/webapp</directory>   
     <targetPath>META-INF/resources</targetPath>   
    </resource>   
   </resources>   
   <plugins>  
   <plugin>   
    <groupId>org.apache.maven.plugins</groupId>   
    <artifactId>maven-compiler-plugin</artifactId>   
    <version>2.3.2</version>   
    <inherited>true</inherited>   
    <configuration>   
     <source>1.8</source>   
     <target>1.8</target>   
    </configuration>      
   </plugin>     
   <plugin>   
    <groupId>org.apache.maven.plugins</groupId>   
    <artifactId>maven-assembly-plugin</artifactId>   
    <configuration>   
     <descriptorRefs>   
      <descriptorRef>jar-with-dependencies</descriptorRef>   
     </descriptorRefs>   
     <finalName>${project.build.finalName}-${project.version}</finalName>   
     <archive>   
      <manifest>   
       <mainClass>com.acc.Main</mainClass>   
      </manifest>   
     </archive>   
    </configuration>   
    <executions>   
     <execution>   
      <phase>package</phase>   
      <goals>   
       <goal>single</goal>   
      </goals>   
     </execution>   
    </executions>   
   </plugin>  
   </plugins>  
  </build>  
 </project>  

We can now modify the Main.java Class with the required code to create a Datasource:

package com.acc;  
 import java.util.Optional;  
 import org.apache.catalina.Context;  
 import org.apache.catalina.deploy.ContextResource;  
 import org.apache.catalina.startup.Tomcat;  
 public class Main {  
     public static final Optional<String> PORT = Optional.ofNullable(System.getenv("PORT"));  
     public static final Optional<String> HOSTNAME = Optional.ofNullable(System.getenv("HOSTNAME"));  
     public static void main(String[] args) throws Exception {  
     String contextPath = "/" ;  
     String appBase = ".";  
     Tomcat tomcat = new Tomcat();    
     tomcat.setPort(Integer.valueOf(PORT.orElse("8080") ));  
     tomcat.setHostname(HOSTNAME.orElse("localhost"));  
     tomcat.getHost().setAppBase(appBase);  
     ContextResource resource = new ContextResource();  
     resource.setName("myoracle");  
     resource.setAuth("Container");  
     resource.setType("javax.sql.DataSource");  
     resource.setScope("Sharable");  
     resource.setProperty("driverClassName","oracle.jdbc.OracleDriver");  
     resource.setProperty("url", "jdbc:oracle:thin:@//141.145.26.28:1521/pdb1.gse00000410.oraclecloud.internal");  
     resource.setProperty("username","myuser");  
     resource.setProperty("password","mypassword");  
     Context rootCtx = tomcat.addWebapp(contextPath, appBase);  
     rootCtx.getNamingResources().addResource(resource);  
     tomcat.enableNaming();  
     tomcat.start();  
     tomcat.getServer().await();  
   }  
 } 

By default Tomcat Embedded has jndi disabled so you need to call:
tomcat.enableNaming();

For security reason the user/password and ip address obviously are not real :) but in my demo they are really pointing to a Oracle Database Cloud Service.


We can create a new jsp with a query: (sqlDemo.jsp)

 <%@ page import="java.util.Hashtable,java.sql.*,javax.naming.*,javax.sql.*" %>  
 <html>  
 <head><title>Database Query in Embedded Tomcat7</title></head>  
 <body>  
 <h2>Querying a database with a JSP in "Embedded" Tomcat 7</h2>  
 <%  
 Context initContext = new InitialContext();  
 DataSource pool = (DataSource)initContext.lookup("java:/comp/env/myoracle");  
   String sql = "select * from CITTADINO";  
   Connection conn = null;  
   Statement stmt = null;  
   ResultSet rs = null;  
   ResultSetMetaData rsm = null; %>  
  <table border='1'><tr>  
  <%   
    try{    
        //get a java.sql.Connection from the pool  
        conn = pool.getConnection( );  
        stmt = conn.createStatement( );//create a java.sql.Statement  
        //execute a SQL statement,generating a ResultSet  
        rs = stmt.executeQuery(sql);   
        rsm = rs.getMetaData( );  
        int colCount = rsm.getColumnCount( );  
        //print column names  
        for (int i = 1; i <=colCount; ++i) { %>  
         <th><%=rsm.getColumnName(i)%> </th>  
      <% } %>  
       </tr>  
      <% while( rs.next( )){ %>  
         <tr>  
       <%   for (int i = 1; i <=colCount; ++i) { %>  
         <td>  <%= rs.getString(i) %> </td>  
       <%}//for %>   
         </tr>  
      <%} //while  
  } catch (Exception e) {  
       throw new JspException(e.getMessage( ));  
  } finally {  
    try{  
      stmt.close( );  
      conn.close( );  
    } catch (SQLException sqle){ }  
  }         %>  
 </table>  
 </body>  
 </html>  

Add the jsp in the web-app dir of your project:


As previous described we can now Compile and Package:

Right click with the mouse on the name of the projest (javase) and select:
Run As->Run Configurations ...



Select the previous created task:  javase-mvn-clean-compile
Click on Run

Now we must package:

Right click with the mouse on the name of the projest (javase) and select:
Run As->Run Configurations ...

Select the previous created task: javase-mvn-package
Click on Run

Open a Command Console and test your application (as previous described):
java -jar javase-0.0.1-SNAPSHOT-jar-with-dependencies.jar




---- How to manually deploy the project on Oracle Application Container Cloud - JavaSE ----

the first thing to do is to create a zip file (with the name that you prefer) with inside the jar (javase-0.0.1-SNAPSHOT-jar-with-dependencies.jar) that we have created and a manifest.json file with the command needed to start the jar.

Now we do it manually, after we will change our pom.xml and this zip file will be create automatically.

The manifest.json file must be:

 {  
   "runtime":{  
     "majorVersion": "8"  
   },  
   "command": "java -jar javase-0.0.1-SNAPSHOT-jar-with-dependencies.jar",  
   "release": {  
     "build": "1",  
     "commit": "1",  
     "version": "1"  
   },  
   "notes": "Web application for demo"  
 }  

I have created JavaSEDemo.zip:


We can upload this file in our Oracle Application Container Cloud - JavaSE (after we will use Developer Cloud Service to be able to build and deploy all the project automatically).

Login in your Oracle Cloud Domain:


Click on the icon on the left of the Oracle logo to open the menu:
Select Oracle Application Container Cloud:


Click on the Blue button "Create Application":


Choose the Container Java SE:

Choose a name (this will be used in the auto-generate url to access the service):


Click on Upload application archive


Click on Create:


After a while you will obtain a success popup window:


As you can see now you will have a "Creating Application ..." status:


You can test your Application, open the menu and click on "Open Application":



you can call now your sqlDemo.jsp page:
https://tomcatembeddedsqldemo-metcsgse00495.apaas.us6.oraclecloud.com/sqlDemo.jsp


----------------------------------------------------------------------------------------------------------
How to push the local project on a remote DevOps system in Cloud (Oracle Developer Cloud Services) and How to automate operations as Building & Deploy
----------------------------------------------------------------------------------------------------------
Now we will see:

  • How to zip the jar+manifest.json file with Maven, so in DevCS will be very simple the operations of Building & Deploy
  • How to add the ojdbc7.jar file in the local Maven repository of DevCS, and how to change the pom.xml file to be able to get it.
  • How to push the project from local Git to DevCS Git and how to automate operations as Building and Deploy on Oracle Application Container Cloud
To create a zip file with jar+manifest.json file from Maven you need to create a file named bin.xml under the directory javase/src/assembly:

Click with the right button of the mouse on src directory of the project then select New->Folder:
Choose assembly as Folder name:

Click Finish:



Now click with the right button of the mouse on src directory of the project then select New->File:
Choose bin.xml as File name:

Click Finish:


Put this code in bin.xml:

 <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"   
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">  
  <id>bin</id>  
  <formats>  
   <format>zip</format>  
  </formats>  
  <includeBaseDirectory>false</includeBaseDirectory>  
  <fileSets>  
   <fileSet>  
    <directory>${project.basedir}</directory>  
    <outputDirectory>/</outputDirectory>  
    <includes>  
     <include>manifest.json</include>  
    </includes>  
   </fileSet>  
   <fileSet>  
    <directory>${project.build.directory}</directory>  
    <outputDirectory>/</outputDirectory>  
    <includes>  
     <include>*.jar</include>  
    </includes>  
   </fileSet>  
  </fileSets>  
 </assembly>  


Now we need to change the pom.xml file:

add this part just after the present </execution> tag:

    <execution>  
    <!-- Build Archive Zip File -->  
      <id>build-zip</id>  
      <phase>package</phase>  
      <goals>  
       <goal>single</goal>  
      </goals>  
      <configuration>  
       <descriptors>  
         <descriptor>src/assembly/bin.xml</descriptor>  
       </descriptors>  
      </configuration>  
    </execution>   


Add the previous created manifest.json file in the root of your project (you can simply drag & drop it on javase directory on Eclipse)


Now you can compile & package your project:

As previous described right click with the mouse on the name of the projest (javase) and select:
Run As->Run Configurations ...

Select the previous created task:  javase-mvn-clean-compile
Click on Run

Now we must package:

Right click with the mouse on the name of the projest (javase) and select:
Run As->Run Configurations ...

Select the previous created task: javase-mvn-package
Click on Run

Open a Command console go to the target directory of your project  (on my PC is under c:\Users\Dell\JavaSEContainer\javase\target\) and verify that the zip file is now present (javase-0.0.1-SNAPSHOT-bin.zip):


Verify that inside the javase-0.0.1-SNAPSHOT-bin.zip there are the jar and the manifest.json file:
(verify also that the name of the jar file inside the json file is correct)


Now you can create a new project on Developer Cloud Service (DevCS):

Go to your DevCS domain and follow this previous post to create a new project with a Git repository:
http://www.fabriziomarini.com/2015/11/creating-project-git-repository-on.html

We will create now a Maven repository on DevCS and we will put on it the ojdbc7.jar file:
Select the Code tab in your DevCS:
 If you do not have already create nothing you will see the following page, click on Go To Maven Repository:


If you have already create a Git Repository you can switch from it to the Maven repository clicking on this list menu:



This is your "empty" Maven Repository, we need to use the Distribution Management informations in our pom.xml file in Eclipse because when we start a build job on DevCS we need those informations to be able to get the ojdbc7.jar file:


Add in your pom.xml in Eclipse the following tag:

<repositories>
  <repository>  
   <id>ACCDemo_repo</id>  
   <name>ACCDemo Maven Repository</name>  
   <url>https://developer.us2.oraclecloud.com/profile/developer70830-metcsgse00495/s/developer70830-metcsgse00495_accdemo/maven/</url>  
  </repository> 
</repositories>


Now click the Upload Button and drag & drop your ojdbc7.jar in the Browser:


Fill the required items with the same informations present in your pom.xml file:

 <dependency>   
   <groupId>com.oracle</groupId>   
   <artifactId>ojdbc7</artifactId>   
   <version>12.1.0.2</version>   
 </dependency>  

Click Start Upload:


After a while you will get this result:


You can "navigate" the tree of your Maven Repository:


From Eclpse configure your Oracle Cloud Plugin connect it to your DevCs Domain, drag & Drop your project from Eclipse in the Oracle Cloud Plugin as described here:
http://www.fabriziomarini.com/2015/11/devops-oracle-cloudhow-to-create-from.html#OCPlugin

Important: Before start the build job on DevCs, remember that we are using in our project, in the Main.java Class, these lines of code that can be compiled only with JDK1.8:

 public static final Optional<String> PORT = Optional.ofNullable(System.getenv("PORT"));    
 public static final Optional<String> HOSTNAME = Optional.ofNullable(System.getenv("HOSTNAME"));   

For that reason we are using this in our pom.xml:

 <configuration>   
     <source>1.8</source>   
     <target>1.8</target>   
 </configuration>  

So, we need to say to the build job on DevCs to use the JDK1.8:

Select the Build Tab on your DevCS:

Click on the name of your job (javase-build):


Click on Configue:


Select JDK 8 in the JDK field:


You can start now your build job ( from previous page), here you can see the artifacts produced, you can download it and verify that the zip file is well packaged.

We can create now a deploy task:
Select the Deploy tab on your DevCS:
Click on New Configuration:


Fill the required fields:

In the Deloyment Target, you can already find the name of the Container that you can use in your Domain:


Choose if you whant an "On Demand" or "Automatic deploy:"
Automatic Deploy is linked to a specific build-job so every time you start that job, you will have also a deployment:
Click on Save:


This is your Deploy Configuration:


You can restart your build job or you can only start the deployment from here:


If you go now in the main page of Application Container Cloud you can find your new Application (ACCDemo) in the state "Creating Application ..."


Wait that your job has finished:


Refresh your page (or click on ACCDemo) to see if it is ready to be tested:
Click on the URL:


Yes it is working:


Also the DB connection works fine :)