Showing posts with label Eclipse. Show all posts
Showing posts with label Eclipse. Show all posts

Friday, September 13, 2013

Build Ear File with ant for MongoDB, WebSphere Application Server

I have explained how to setup MongoDB development environment for WebSphere Application Server with Eclipse in post: http://feijiangnan.blogspot.ca/2013/09/setup-eclipse-for-mongodb-and-websphere.html, let's go further to compile the code using Apache Ant.

In this scenario, I used Linux to run the tasks.

1. Install Ant

You can find the binary and installation guide on http://ant.apache.org/

2. Create build.xml like below


<?xml version="1.0"?>
<project name="mongodbHelloWorld" default="buildEar" basedir=".">
    <description>
        First Mongodb Java Project
    </description>
    <!-- set global properties for this build -->
    <property name="distName" value="mongodbHelloWorld" />
    <property name="src" location="src" />
    <property name="build" location="build" />
    <property name="warDir" location="wars" />
    <property name="earDir" location="ears" />
    <property name="outputDir" location="output" />
    <property name="warFile" value="${distName}.war" />
    <property name="earFile" value="${distName}.ear" />
    <property name="wasJRELib" value="/opt/IBM/WebSphere/AppServer/java/jre/lib" />
    <property name="wasLib" value="/opt/IBM/WebSphere/AppServer/java/jre/lib" />
    <property name="wasJavaLib" value="/opt/IBM/WebSphere/AppServer/java/lib" />
    <property name="wasLibExt" value="/opt/IBM/WebSphere/AppServer/java/jre/lib/ext" />
    <property name="wasPlugins" value="/opt/IBM/WebSphere/AppServer/plugins" />
    <property name="wasEndorsed" value="/opt/IBM/WebSphere/AppServer/endorsed_apis" />
    <property name="wasJEE" value="/opt/IBM/WebSphere/AppServer/dev/JavaEE/6.0" />
    <property name="wasVM" value="/opt/IBM/WebSphere/AppServer/java/jre/lib/amd64/default/jclSC160" />

    <path id="project.class.path">
        <pathelement location="lib/mongo-java-driver-2.11.2.jar" />
        <fileset dir="${wasJEE}" includes="*.jar" />
        <fileset dir="${wasJRELib}" includes="*.jar" />
        <fileset dir="${wasLib}" includes="*.jar" />
        <fileset dir="${wasJavaLib}" includes="*.jar" />
        <fileset dir="${wasLibExt}" includes="*.jar" />
        <fileset dir="${wasEndorsed}" includes="*.jar" />
        <fileset dir="${wasPlugins}" includes="*.jar" />
    </path>


    <target name="init">
        <!-- Create the time stamp -->
        <tstamp />
        <!-- Create the build directory structure used by compile -->
        <mkdir dir="${build}" />
    </target>

    <target name="compile" depends="init" description="compile the source ">
        <!-- Compile the java code from ${src} into ${build} -->
        <javac srcdir="${src}" destdir="${build}" includeantruntime="false">
            <classpath refid="project.class.path" />
        </javac>
    </target>

    <target name="buildWar" depends="compile" description="generate the distribution">
        <!-- Create the distribution directory -->
        <mkdir dir="${warDir}/lib" />
        <war destfile="${warDir}/wars/${warFile}" needxmlfile='false'>

            <webinf dir="WebContent/WEB-INF">
                <include name="**/*.xml" />
            </webinf>

            <classes dir="WebContent/WEB-INF/classes" />
           
            <lib dir="lib">
                <include name="mongo-java-driver-2.11.2.jar" />
                <exclude name="jdbc1.jar" />
            </lib>
        </war>

    </target>

    <target name="clean" description="clean up">
        <!-- Delete the ${build} and ${warDir} directory trees -->
        <delete dir="${build}" />
        <delete dir="${warDir}" />
        <delete dir="${earDir}" />
    </target>

    <target name="buildEar" depends="clean, buildWar">
        <mkdir dir="${earDir}/META-INF" />

        <copy todir="${earDir}/" file="${warDir}/wars/${warFile}" />
        <copy tofile="${earDir}/META-INF/application.xml" file="application.xml" />
    <!--    <copy todir="${earDir}/META-INF">
            <fileset dir="localDirectory" includes="was.policy" />
        </copy>
        -->
        <jar jarfile="${outputDir}/${earFile}" basedir="${earDir}">
            <!-- Define the properties for the Manifest file. -->
            <manifest>
                <attribute name="Implementation-Vendor" value="Go Weekend" />
                <attribute name="Implementation-Title" value="Client Registration" />
                <attribute name="Implementation-Version" value="1.0" />
            </manifest>
        </jar>
    </target>
</project>

3. Create application.xml as below

<?xml version="1.0" encoding="UTF-8"?>
<application id="HellowMongodb" version="6" 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/application_6.xsd">
        <application-name>HelloMongoDB</application-name>
        <display-name>Hello Mongodb</display-name>
        <icon>
                <small-icon>/META-INF/MongoDB_Small.jpeg</small-icon>
                <large-icon>/META-INF/MongoDB_Large.jpeg</large-icon>
        </icon>
        <module id="WebModule_HelloMongodb">
                <web>
                        <web-uri>mongodbHelloWorld.war</web-uri>
                        <context-root>HelloMongodb</context-root>
                </web>
        </module>
</application>

4. Create web.xml in WebContent/WEB-INF

<?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">
    <display-name>mongodbHelloWorld</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

5. Run Ant to build ear file


 ant -f build.xml buildEar

6. Deploy the ear file

Deploy the ear file in your WebSphere Application Server, and connect to the application in your browser like:
http://<your hostname>:9060/HelloMongodb/HelloMongodb

Friday, September 6, 2013

Setup Eclipse for mongoDB and WebSphere Application Development Environment


Install JDK

Download jdk from http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase6-419409.html
# cd /opt
# <path to jdk binary>/jdk-6u38-linux-x64.bin
# cd /opt/jdk1.6.0_38

set environment variables for users accordingly
set JAVA_HOME=/opt/jdk1.6.0_38
and set PATH=$JAVA_HOME/bin:$PATH

Install mongoDB

Download mongoDB from http://www.mongodb.org/downloads
Extract the binaries in /opt/mongoDB
Verify Installation
# cd /opt/mongoDB/bin
Start Server
# ./mongod

Start client
# ./mongo

Install WebSphere Application Server

please refer to IBM WebSphere Application Server Installation

Install Eclipse

Download Eclipse from http://www.eclipse.org/downloads/
Eclipse Juno is used in this scenario.
extract the binary into /opt/tools
$ cd /opt/tools
$ tar -zxf eclipse-jee-juno-SR2-linux-gtk-x86_64.tar.gz
$ mv eclipse mongodbDev

Configuring Eclipse with WebSphere Application Server

Help -> Eclipse Marketplace -> Search
type in "Websphere application server" in Find field, and click Go
In the results panel, Install "IBM WebSphere Application Server V8.0 Developer Tools for Eclipse Juno"
Followin instructions in screen to finish the installation.
Restart Eclipse

Goto Windows -> Preferences -> Server -> Runtime Environments
Remove the existing one "Web Preview Server Runtime".
Add -> IBM -> WebSphere Application Server v8.0
Check "Create a new local server", click Next
Point "Installation Dictionary" to your WebSphere Application Server installation location, i.e. /opt/IBM/WebSphere/AppServer
Provide information accordingly in the following screens, and click Finish.
Goto Windows -> Preferences -> Server -> WebSphere Application Server to verify the settings.

Download MongoDB Java Driver from http://api.mongodb.org/java/
we use version of 2.11.2 in this scenario, and put it in your CLASSPATH.

Create First Application, mongodbHelloWorld

Goto File -> New -> Dynamic Web Project
Project Name: mongodbHelloWorld
Click Finish

In project of mongodbHelloWorld, goto File -> New -> Servlet
Java package: ca.goweekend.mongo
Class name: HelloMongodb
Click Finish
paste below code in HelloMongodb.java, and you will see many errors.

Now let's include Mongodb Java Driver into CLASSPATH to resove those errors.
right click on mongodbHelloWorld project, and choose properties -> Java Build Path -> Libraries -> Add External Jars, add the Java driver you downloaded before. Click OK, and the errors should be all gone.

Goto Windows -> Preferences -> Java -> Build Path -> Classpath Variables -> New
Name: Mongodb Java Driver
Path: /apps/mongodb/mongo-java-driver-2.11.2.jar

HelloMongodb.java

package ca.goweekend.mongo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.ws.webcontainer.servlet.ServletConfig;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;

/**
 * Servlet implementation class HelloMongodb
 */
@WebServlet("/HelloMongodb")
public class HelloMongodb extends HttpServlet {
        private static final long serialVersionUID = 1L;

        /**
         * @see HttpServlet#HttpServlet()
         */
        public HelloMongodb() {
                super();
        }

        public void init(ServletConfig config) {
                System.out.println("Inititiating Database Connection.");
        }

        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doGet(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException, IOException {

                MongoClient mongleClient = new MongoClient("db.goweekend.ca",
                                27017);

                DB db = mongleClient.getDB("HelloMongodb");

                DBCollection coll = db.getCollection("client");

                try {
                        BasicDBObject doc = new BasicDBObject();

            String yourIPAddress = request.getRemoteAddr();
            String hostname = request.getRemoteHost();
            int portNumber = request.getRemotePort();
                        doc.put("hostname", hostname);
                        doc.put("ipaddress", yourIPAddress);
                        doc.put("portnumber", portNumber);

                        coll.insert(doc);

                } catch (Exception e) {
                        e.printStackTrace();
                }

                DBCursor cursor = coll.find();

                try {
                   while(cursor.hasNext()) {
                           response.getWriter().print(cursor.next());
                           response.getWriter().print("\n");
                   }
                } finally {
                   cursor.close();
                }
        }
}

right click on HellowMongodb.java in Enterprise Explorer Panel, and chose Run As -> Run on Server, and follow the instructions on screen, and you will see the result. Open the URL on different machine, you will see different machine entries added in MongoDB.

To use ant to build ear file, please refer to http://feijiangnan.blogspot.ca/2013/09/build-ear-file-with-ant-for-mongodb.html