Hi,

This is the third part of in the series of JavaScript in which we are going to see how to implement the Server Side Java Script inside the WildFly 10 Container. As we know that WildFly provides the “undertow” container inside it. Undertow is a flexible performant web server written in java, providing both blocking and non-blocking API’s based on NIO. Undertow has a composition based architecture that allows users to build a web server by combining small single purpose handlers. In order to know more about undertow please refer to: http://undertow.io/

WildFly 10 allows users to use the JavaScript on the server side with the help of the Nashorn JavaScript engine offered by JDK8. So far as part of our previous part-1 and part-2 articles we have learned about Nashorn javascript, jjs command line tool and the JSR-292 APIs which allows us to execute and javascript. If you have not gone through those articles then it is better to have a look at them before we start this demo:

Why Nashorn Java Scripting in Java8, Is it Poisonous for Java? (part-1)

JDK8 Based Nashorn JavaScript & Java to interact with MySQL Database. (part-2)

What this demo is about?

As part of this demo we will learn about the following things:

1. How to create a MySQL DataSource inide the WildFly 10 using jboss-cli.

2. How to include the *.js (java script files) inside the application in WildFly and what is the use of “WEB-INF/undertow-scripts.conf” file.

3. How to execute simple JavaScript inside wildfly/undertow.

4. How to execute Plain JDBC based java script inside the wildfly/undertow.

5. How to lookup the DataSource from the Nashorn java script and fetch customer table data from database.

6. We will also see how to use the “wildfly-maven-plugin” to deploy the Application on Wildfly.

Setting up MySQL Database

Start the MySQL database and then do the following steps which will basically do the following things:
A. Creating a simple Database with name “TestJavaScriptDB”
B. Creating a table with name “CUSTOMER”.
C. Insert some dummy records inside the “CUSTOMER” table.

mysql -u root -p 
password:


mysql> create database TestJavaScriptDB;
Query OK, 1 row affected (0.00 sec)


mysql> use TestJavaScriptDB;
Database changed


mysql> CREATE TABLE CUSTOMER (custId INT(10) NOT NULL, custName CHAR(20) NOT NULL);
Query OK, 0 rows affected (0.02 sec)

mysql> INSERT INTO CUSTOMER VALUES (1000, "MiddlewareMagic");
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO CUSTOMER VALUES (2000, "Customer-2");
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO CUSTOMER VALUES (3000, "Customer-3");
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM CUSTOMER;
+--------+-----------------+
| custId | custName        |
+--------+-----------------+
|   1000 | MiddlewareMagic |
|   2000 | Customer-2      |
|   3000 | Customer-3      |
+--------+-----------------+
3 rows in set (0.01 sec)

Creating DataSource on WildFly10 side.

Now lets create a simple MySQL datasource using jboss-cli.sh script provided by WildFly.

[standalone@localhost:9990 /] module add --name=com.mysql  --dependencies=javax.api,javax.transaction.api --resources=/PATH/TO/mysql-connector-java-5.1.37-bin.jar 


[standalone@localhost:9990 /] /subsystem=datasources/jdbc-driver=mysql/:add(driver-module-name=com.mysql,driver-name=mysql,jdbc-compliant=false,driver-class-name=com.mysql.jdbc.Driver) 
{"outcome" => "success"}

[standalone@localhost:9990 /] /subsystem=datasources/data-source="MySqlDS":add(jndi-name="java:jboss/MySqlDS",driver-name="mysql",connection-url="jdbc:mysql://localhost:3306/TestJavaScriptDB",user-name="root",password="testpwd")
{"outcome" => "success"}

[standalone@localhost:9990 /] :reload
{
    "outcome" => "success",
    "result" => undefined
}

[standalone@localhost:9990 /] /subsystem=datasources/data-source="MySqlDS":test-connection-in-pool()
{
    "outcome" => "success",
    "result" => [true]
}

Once the above jboss-cli commands are executed we should be able to see the following kind of DataSource created inside our wildfly profile (i am using “standalone.xml”).

        <subsystem xmlns="urn:jboss:domain:datasources:4.0">
            <datasources>
                <datasource jndi-name="java:jboss/MySqlDS" pool-name="MySqlDS">
                    <connection-url>jdbc:mysql://localhost:3306/TestJavaScriptDB</connection-url>
                    <driver>mysql</driver>
                    <security>
                        <user-name>root</user-name>
                        <password>testpwd</password>
                    </security>
                </datasource>
                <drivers>
                    <driver name="mysql" module="com.mysql">
                        <driver-class>com.mysql.jdbc.Driver</driver-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>

Developing WebApplication containing the Nashorn Script

Now lets start developing the WebApplication so in order to do that lets create some directory structure and to understand where we are going to place which file.

Step-1). Create a directory “Part-3_WildFly_ServerSide_JavaScript” some there in your filesystem.

mkdir Part-3_WildFly_ServerSide_JavaScript

mkdir -p Part-3_WildFly_ServerSide_JavaScript/src/main/webapp/WEB-INF

Step-2). Now lets write the “hello.js” simple script inside the “Part-3_WildFly_ServerSide_JavaScript/src/main/webapp/” directory as following, Where we will define the resource uri “/hello” and its actions.

$undertow.onGet("/hello",
                  { headers: {"content-type": "text/plain"}},
                      [function ($exchange) {
                         return "Hello, MiddlewareMagic!!!";
                   }])

Step-3). Similarly we will write another javascript inside the “Part-3_WildFly_ServerSide_JavaScript/src/main/webapp/” directory with name “testDB.js”. This is a simple javascript file which uses the plain JDBC approach to interact with the Database.

//  ## JDBC Based JavaScript  ##

$undertow
    .onGet("/getCustomerRecords",
        {headers: {"content-type": "text/plain"}},
        [function ($exchange) {
            var con1 = getConnection();
            var customerData = runQuery(con1, "select * from CUSTOMER");
            return "Got Customer Data: " + customerData;
        }])
        
     
     
//  Java Script Functions  //        
var getConnection = function() {
    var Properties = Java.type("java.util.Properties");
    var Driver = Java.type("com.mysql.jdbc.Driver");
    var driver = new Driver();
    var properties = new Properties();
    var conn = null;
    try {
        properties.setProperty("user", "root");
        properties.setProperty("password", "testpwd");
        conn = driver.connect("jdbc:mysql://localhost:3306/TestJavaScriptDB", properties);
        print("****** Got the JDBC Connection : " +conn);
        return conn;
    } finally {
    }
}

// Declaring runQuery function
var runQuery = function(conA, query) {
   var result = "";
   try {
       var stmt = conA.prepareStatement(query);
       var resultSet = stmt.executeQuery();
       print("      --------------------------- ");
       while (resultSet.next()) {
          result = result + " [";
          var rowData = resultSet.getString("custId") + " - " + resultSet.getString("custName");
          print("\t" + rowData);
          result = result + rowData + "], "; 
       }
       print("      --------------------------- ");
       return result;
    } finally {
      if (resultSet)
         try {
            resultSet.close();
            print("\nResultSet Closed.");
         }
         catch(e) {}
      if (stmt)
         try {
            stmt.close();
            print("Statement Closed.");            
         } catch (e) { print( e );  }
      if (conA)        
         try { 
            conA.close();
            print( "Connection Closed." );
         } catch (e) { print( e );  }          
      }  
 } 

//  Following Cals are commended else those wil be executed as soon as WildFly startes deploying this WebApplication.
//var con1 = getConnection();
//runQuery(con1, "select * from CUSTOMER");

Step-4). As above we have seen a plain JDBC interaction based javascript. However we want to use the DataSource concept as well in order to interact with the Database. So here we will be writing another simple Hava Script file “testDataSource.js” inside the directory “Part-3_WildFly_ServerSide_JavaScript/src/main/webapp/” directory with name “testDB.js” and will performa simple JNDI lookup of the DataSource. This shows that we do not need to write so lengthy java scripts as mentioned above in order to interact with the database.

$undertow
    .onGet("/getCustomersViaDataSource",
        {headers: {"content-type": "application/json"}},
        ['jndi:java:jboss/MySqlDS', function ($exchange, db) {
            return db.select("select * from CUSTOMER");
        }])

Step-5). Lets write a simple “index.jsp” page which will have the URL of the above mentioned javascript Get Resources. Lets place this index.jsp file inside the “Part-3_WildFly_ServerSide_JavaScript/src/main/webapp” directory as following:

<HTML>
  <HEAD>
     </TITLE>Nashorn Server Side Java Script Demo Undertow/WildFly</TITLE>
  </HEAD>
  <BODY>
     <Center>

<h3>This is a simple demo explaining how to use Server Side Java Script in WildFly</h3>

       <a href="hello">Click Here to execute to "/hello" resource</a>
       <BR/><BR/>
       <a href="getCustomerRecords">Click Here "/getCustomerRecords" to access customers records from Database</a>  
       <BR/><BR/>
       <a href="getCustomersViaDataSource">Click Here "/getCustomersViaDataSource" to access customers records from Database via DataSource lookup</a>         
      </Center>      
  </BODY>
</HTML>   

Step-6). If needed then we can add the “web.xml” file inside the “Part-3_WildFly_ServerSide_JavaScript/src/main/webapp/WEB-INF” as following (in my case as i do not have anything specific to be written in this file so i am keeping a dummy file here)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> 
</web-app>

Step-7). Now the Most important part. We are going to add the file “undertow-scripts.conf” inside the “Part-3_WildFly_ServerSide_JavaScript/src/main/webapp/WEB-INF”

hello.js
testDB.js
testDataSource.js

NOTE: We need to tell WildFly/Undertow container that where to find our javascript files. So in order to do this we create a file “WEB-INF/undertow-scripts.conf”. In this file we list all our server side JavaScript files one per line. See: http://undertow.io/undertow-docs/undertow-docs-1.3.0/index.html

Step-8). Now we will simply write our Maven “pom.xml” file to build the WAR file containing all the above contents in it and it will also use the “wildfly-maven-plugin<” plugin which will help us in deploying it on WildFly (running on localhost:9990). So lets create “pom.xml” file inside the “Part-3_WildFly_ServerSide_JavaScript” directory as following:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>middleware.magic</groupId>
  <artifactId>WildFlyServerSideJavaScript</artifactId>
  <version>1.0</version>
  <packaging>war</packaging>
  <name>WildFlyServerSideJavaScript</name>
  
  <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>
        <version.wildfly.bom>10.0.0.CR2</version.wildfly.bom>
        <version.wildfly-maven-plugin>1.0.2.Final</version.wildfly-maven-plugin>
        
        <!-- Compiler Related versions -->
        <version.war.plugin>2.5</version.war.plugin>
        <version.maven.compiler.plugin>3.3</version.maven.compiler.plugin>
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.compiler.source>1.7</maven.compiler.source>
  </properties>  
  
  
  <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.wildfly.bom</groupId>
            <artifactId>jboss-javaee-7.0-wildfly</artifactId>
            <version>${version.wildfly.bom}</version>
            <scope>import</scope>
         </dependency>
      </dependencies>
  </dependencyManagement> 

  <dependencies>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-web-api</artifactId>
      <version>7.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.37</version>
   </dependency>
  </dependencies>
  
  <build>
   <finalName>WildFlyServerSideJavaScript</finalName>   <!-- WAR name -->
   <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${version.maven.compiler.plugin}</version>
        <configuration>
          <source>${maven.compiler.target}</source>
          <target>${maven.compiler.source}</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>${version.war.plugin}</version>
        <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
        
        <!-- The WildFly Maven Plugin deploys your war to a local WildFly container -->
        <!-- To use, set the JBOSS_HOME environment variable and run: mvn package wildfly:deploy -->
      <plugin>
         <groupId>org.wildfly.plugins</groupId>
         <artifactId>wildfly-maven-plugin</artifactId>
         <version>${version.wildfly-maven-plugin}</version>
      </plugin>
   </plugins>
  </build>
  
</project>

Building and Deploying the application

Lets build and deploy this application as following , Start WildFly default profile “standalone.xml” and open a terminal to run the maven build.

Setting up the environment:
For Unix Based OS

$ export M2_HOME=/PATH/TO/apache_maven_3.2.3
$ export JAVA_HOME=/PATH/TO/jdk1.8.0_60
$ export PATH=$JAVA_HOME/bin:/PATH/TO/apache_maven_3.2.3/bin:$PATH

$ cd Part-3_WildFly_ServerSide_JavaScript
$ mvn clean install

For Windows Based OS

$ set M2_HOME=C:\PATH\TO\apache_maven_3.2.3
$ set JAVA_HOME=C:\PATH\TO\jdk1.8.0_60
$ set PATH=%JAVA_HOME%/bin;C:\PATH\TO\apache_maven_3.2.3\bin;%PATH%

$ cd C:\Part-3_WildFly_ServerSide_JavaScript
$ mvn clean install 

Now make sure that wildfly is ruinning on localhost:9990 , run the maven build as following [mvn clean install wildfly:deploy] the wildfly:deploy task will find the running wildfly instance and will automatically deploy the WAR.


$ mvn clean install wildfly:deploy

########
OUTOUT
########
[INFO] Scanning for projects...
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for middleware.magic:WildFlyServerSideJavaScript:war:1.0
[WARNING] 'dependencyManagement.dependencies.dependency.type' for org.wildfly.bom:jboss-javaee-7.0-wildfly:jar must be 'pom' to import the managed dependencies. @ line 28, column 22
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING] 
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building WildFlyServerSideJavaScript 1.0
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ WildFlyServerSideJavaScript ---
[INFO] Deleting /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ WildFlyServerSideJavaScript ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ WildFlyServerSideJavaScript ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ WildFlyServerSideJavaScript ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ WildFlyServerSideJavaScript ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ WildFlyServerSideJavaScript ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-war-plugin:2.5:war (default-war) @ WildFlyServerSideJavaScript ---
[INFO] Packaging webapp
[INFO] Assembling webapp [WildFlyServerSideJavaScript] in [/Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/target/WildFlyServerSideJavaScript]
[INFO] Processing war project
[INFO] Copying webapp resources [/Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/src/main/webapp]
[INFO] Webapp assembled in [54 msecs]
[INFO] Building war: /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/target/WildFlyServerSideJavaScript.war
[INFO] 
[INFO] --- maven-install-plugin:2.4:install (default-install) @ WildFlyServerSideJavaScript ---
[INFO] Installing /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/target/WildFlyServerSideJavaScript.war to /Users/jsensharma/.m2/repository/middleware/magic/WildFlyServerSideJavaScript/1.0/WildFlyServerSideJavaScript-1.0.war
[INFO] Installing /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/pom.xml to /Users/jsensharma/.m2/repository/middleware/magic/WildFlyServerSideJavaScript/1.0/WildFlyServerSideJavaScript-1.0.pom
[INFO] 
[INFO] >>> wildfly-maven-plugin:1.0.2.Final:deploy (default-cli) > package @ WildFlyServerSideJavaScript >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ WildFlyServerSideJavaScript ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ WildFlyServerSideJavaScript ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ WildFlyServerSideJavaScript ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ WildFlyServerSideJavaScript ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ WildFlyServerSideJavaScript ---
[INFO] No tests to run.
[INFO] Skipping execution of surefire because it has already been run for this configuration
[INFO] 
[INFO] --- maven-war-plugin:2.5:war (default-war) @ WildFlyServerSideJavaScript ---
[INFO] Packaging webapp
[INFO] Assembling webapp [WildFlyServerSideJavaScript] in [/Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/target/WildFlyServerSideJavaScript]
[INFO] Processing war project
[INFO] Copying webapp resources [/Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/src/main/webapp]
[INFO] Webapp assembled in [5 msecs]
[INFO] Building war: /Users/jsensharma/NotBackedUp/MM_Tests/WildFly/JavaScript/Java_8_Nashorn_WildFly/Part-3_WildFly_ServerSide_JavaScript/target/WildFlyServerSideJavaScript.war
[INFO] 
[INFO] <<< wildfly-maven-plugin:1.0.2.Final:deploy (default-cli) < package @ WildFlyServerSideJavaScript <<<
[INFO] 
[INFO] --- wildfly-maven-plugin:1.0.2.Final:deploy (default-cli) @ WildFlyServerSideJavaScript ---
Nov 27, 2015 4:18:54 PM org.xnio.Xnio <clinit>
INFO: XNIO version 3.2.2.Final
Nov 27, 2015 4:18:55 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.2.2.Final
Nov 27, 2015 4:18:55 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 4.0.3.Final
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.741 s
[INFO] Finished at: 2015-11-27T16:18:55+05:30
[INFO] Final Memory: 14M/245M
[INFO] ------------------------------------------------------------------------

Source code for this demo is present in :
https://github.com/jaysensharma/MiddlewareMagicDemos/tree/master/WildFly/Java_8/ServerSideJavaScript/Part-3_WildFly_ServerSide_JavaScript
.
.
Regards
Jay SenSharma