Montag, 5. Mai 2014

MongoDB, EclipseLink and Eclipse - a Database connection for our Webapp

Hey everyone,

this is the second part of my tutorial on how to set up a development environment for 3 tier web application development. This post is just a collection of step by step instructions until now. In the next days I will add some more descriptive text, but right now I'm pretty busy at work ;)

Nevertheless, I hope you can draw something useful from these step by step instructions until then.

Assumptions: 
Installing and configuring :
  • MongoDB 2.6.x
  • MonjaDB
  • EclipseLink 2.5
Instructions:

How to setup MongoDB

  • Go to http://www.mongodb.org/downloads -> Download Windows 64bit (32bit)msi installer 
  • Run the installer -> Next -> check License Agreement -> Next -> Custom -> Choose your favorite install location -> Next -> Install -> Finish
  • Go to your installation directory and create the folder structure "/data/db".
  • Go to your installation directory and create a folder named "log".
  • In the installation directory create a file named "mongod.cfg" -> open file -> type the mongod.cfg snippet (see below)
  • In the installation directory create a file named "mongoStart.bat" -> open file (e.g. with notepad) -> type "C:\path\to\mongo\bin\mongod.exe --config C:\path\to\mongo\mongod.cfg"
  • DB Startup: doubleclick mongoStart.bat
  • DB Shutdown: in command prompt type CTRL+C -> J -> Enter
  • All log files are created in the log directory and can be read with notepad or a text editor
  • (optional) If you are running Windows7 AND you are getting Errorcode 33 while running MongoDB -> Installhttp://support.microsoft.com/kb/2731284

How to install MonjaDB Eclipse Plugin
  • Install MonjaDB Plugin
    • Help -> Eclipse Marketplace -> type "MonjaDB" -> Install -> Confirm -> I accept the terms of the license agreement -> Finish (Installs Monja DB for easier DB development)
    • Window -> Perspectives -> Other -> MonjaDB (opens the perspective for Monja DB. One can switch back to the normal perspective by clicking on "JavaEE" in the right top corner of Eclipse)
    • To connect to a running MongoDB click on the leftmost icon of the "DB Tree" view -> ConnectionType=Normal / No SSH Configuration / Host=127.0.0.1 / Port=27017 / Database=test -> OK

How to configure a DynamicWebProject for MongoDB + EclipseLink
  • Setup MongoDB and EclipseLink 
    • R-Click project -> Maven -> Add Dependency -> org.eclipse.persistence.jpa / org.eclipse.persistence.nosql / mongo-java-driver / org.apache.tomcat servlet api / javax javaee-api
    • R-Click on "src" folder -> New -> Other -> General -> Folder -> Name it "META-INF"
    • R-Click on "META-INF" folder -> New -> Other -> File -> Name it "persistence.xml" (This is where you are configuring )
    • insert persistence.xml snippet (see below)

Snippets:
mongod.cfg

systemLog:
 destination: file
 path: 'C:\\path\\to\\mongo\\log\\mongo.log'
storage:
 dbPath: 'C:\\path\\to\\mongo\\data'



persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_2_0.xsd" version="2.0"> 
<persistence-unit name="<unitname>" transaction-type="RESOURCE_LOCAL"> 
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> 
<exclude-unlisted-classes>false</exclude-unlisted-classes> 
<properties> 
<property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/> 
<property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/> 
<property name="eclipselink.nosql.property.mongo.port" value="<xxxxx>, 27017"/>
<property name="eclipselink.nosql.property.mongo.host" value="<host1>, localhost"/> 
<property name="eclipselink.nosql.property.mongo.db" value="<dbname>"/> 
<property name="eclipselink.logging.level" value="FINEST"/>
</properties> 
</persistence-unit> 
</persistence> 

References

Client-Server Development with Eclipse, AngularJS, Java EE and Apache Tomcat

Hey everyone!

Welcome to the first part of the tutorial on how to setup Eclipse for 3 tier application development. Let's start with the assumptions I made, which are not that many. So let us see what you need and what we are trying to install/configure and so on :)

Assumptions: 
  • Installed JDK (1.7.x)
  • Windows 7
Installing and configuring :
  • Apache Tomcat 7.0.52
  • Eclipse 4.3.2 (Kepler)
  • Chrome 34.0.1847.92
  • Maven 3.2.1
  • Jersey 2.7
  • Jackson 2.3.2
  • Angular JS
  • LiveReload

The first step on our journey to the "perfect" development enivronment is the installation of Maven. I know that many people say that Maven is too heavy or too compilcated, but if you just take those parts of it you really need (in our case dependency management), it is a really great tool. Especially when used in combination with Eclipse and the m2e plugin.
So just follow the step-by-step instructions below in order to install Maven on your machine:

  • Download Maven from http://maven.apache.org/download.cgi (Binary zip)
    • make sure "JAVA_HOME" variable is set as an environment variable
    • extract Maven into a folder (note: the path to this folder must not contain white spaces and should not be too deep e.g. C:/../../../../Maven/)
    • add "MAVEN_HOME" to your environment variables. It should point to your Maven directory

Now, that we've installed Maven let's go and get our IDE. We will use Eclipse as it provides us great support for several frameworks and technologies we're going to use. As we're going to develop web applications you will install the JEE version of Eclipse, which comes with a set of preinstalled plugins that come very handy when developing web applications.
Although many of the plugins we need are already bundled in the JEE version, two are still missing.
The first is the Angular JS plugin that provides us an HTML editor which supports Angular JS expressions and directives. This great plugin was written by Angelo Zerr (Thank you very much!!!)
The second plugin we need is a LiveReload server, so that we don't have to refresh our webpage by hand every time we change the code. Later in this tutorial we also will install the LiveRelod plugin for Chrome, which connects to this server and therefore gets notified whenever the sourcecode on our server has changed. Great tool which saves you a lot of time.
As already done at the Maven installation, you just follow those steps below in order to install and configure Eclipse, the Angular JS plugin and the LiveReload server.


After setting up our IDE we need a server on wich our logic shall run later on. I decided to use Apache Tomcat, as it is lightweight in the first place, but can be extended to a full blown JEE Application Server if needed (http://tomee.apache.org/apache-tomee.html).

  • Setup Apache Tomcat 
    • In Eclipse -> Window -> Preferences -> Server -> Runtime Environments -> Add
    • Choose Apache Tomcat v7.0 -> Next
    • Choose a Name
    • Click "Downlad and Install..." and choose a directory where you want to install tomcat -> Finish

As already mentioned above, we install the LiveReload plugin for our browser (in my case Chrome) for a more seamless development cycle regarding GUI development. What does that mean? Well in fact that you always will see the results of what you're coding with nearly no delay. When changing the code of your webapp in eclipse, the IDE will recognize that you've just changed something. It will then hot redeploy your new code to the server (Apache Tomcat). The LiveReload server that runs in parallel to Apache Tomcat  recognizes this change and notifies the browser which shows your webapp and forces it to reload the page with your webapp. This whole process is a matter of a few seconds and therefore you will always see the changes you made immediately reflected in your browser.


Now that everything we need is installed, we have to configure some little things so that everything works perfectly together. For example: Maven does not always show all available artifacts when seraching for them at first. So we need to configure it's behaviour regarding updating of its repositories.  Just follow the instructions below and you should be fine. If your deeper into eclipse and those plugins you're free to make your own preference settings ;)

  • Configure Apache Tomcat, preferred Browser, Maven and LiveReload in Eclipse
    • Window -> Preferences -> Server -> Runtime Environments -> Add
    • Choose Apache Tomcat v7.0 -> Next
    • Chose a Name -> Browse to your Tomcat installation directory -> Finish
    • Window -> Show View -> Other -> Server ->Servers
    • R-Click in Server View -> New ->Server -> Apache ->Tomcat v7.0 Server -> Finish
    • R-Click in Sever View -> New -> Server -> Basic -> LiveReload Server -> Finish
    • Window -> Preferences -> General -> Web Browser -> Check Default system web browser (i assume it's chrome) (everytime you click "run on server" this browser gets opened)
    • Window -> Preferences -> Maven -> check "Download Artifact Sources" and "Download Artifact JavaDoc" (if you have an already existing project: R-Click project -> Maven -> Download Sources/Download JavaDoc)
    • Window -> Show View -> Other -> Maven -> Maven Repositories -> Global Repositories -> R-Click on central -> Update Index
    • Window -> Preferences -> Maven -> Download repository index updates on startup

Finally we got everything to work as we wanted and are now able to create our first project :)
At first lets create and  configure a new Dynamic WebProject in Eclipse. Afterwards I will give some explanations to regarding the project setup and using the different plugins.


How to create and run a new DynamicWebProject 
  • Create Dynamic Web Project with Angular Support, Maven Dependency Management, Jersey Support, Jackson Support
    • Create Project
      • Right Click -> New -> Other -> Web -> Dynamic Web Project
      • Project name: de.uniaugsburg.mdsd.<your-project-structure>
      • Target runtime Apache Tomcat v7.0 -> Finish
    • Configure Angular JS Support
      • R-Click Project -> Configure -> Convert to Angular JS Project
      • R-Click Project ->Properties -> Validation -> HTMLSyntax -> Check "Enable Project specific Settings" -> Attributes -> Undefined Attribute name -> Ignore
      • HTML/CSS/JS Files come into the WebContent Folder of the Project
    • Configure Maven
      • R-Click Project -> Configure -> Convert to Maven Project
    • Configure Jersey and Jackson
      • R-Click project -> Maven -> Add Dependency -> jersey-container-servlet / jackson-jaxrs-json-provider
      • Copy config of jersey_web (see below) snippet into WEB-INF/web.xml and replace <package-where-your-services-are> to your respective packagename
    • Run Dynamic Web Project
      • R-Click on LiveReload Server -> Start
      • R-Click on Project -> Run as... -> Run on server
      • in Chrome type URL of your Webservice
      • in Chrome enable LiveReload Plugin
      • go out there and CODE :)

    First the project setup. What you've just created is an Eclipse project that can also be built by using Maven only. Moreover it's an Eclipse project that is aimed to run on a server, more specific a JEE Servlet container (just like Tomcat ;) ). This project can be split in two parts:

    The server code:
    The code for the server side logic is written in good old Java, with a little help of frameworks like Jersey, Jackson and later in the next tutorial EclipseLink and JPA. The java code resides in the folder "JavaResources/src". Feel free to create your own folder hierarchy below this root folder.
    The server side logic normally consists of a bunch of webservices and a litle bit of business logic. So how do we create those webservices? Here, Jersey comes into play. We do nothing more than writing a POJO and annotate it with Jersey's annotations in order to mark it as a Webservice:


    1:  @Path("/fooservice")  
    2:  public class FooService {  
    3:       @Path("/getsomefoo")  
    4:       @Produces(MediaType.APPLICATION_JSON)  
    5:       public Foo getSomeFoo() {  
    6:            Foo foo = new Foo("fooname");  
    7:            return foo;  
    8:       }  
    9:  }  

    Given you followed the instructions on how to create a dynamic Web Project and pointed the jersey servlet to the package where you've written this service, you should be able to reach it via an URL like "http://localhost:8080/myappname/rest/fooservice/getsomefoo". 
    That's easy, isn't it?


    The client code:
    This code resides within the folder "WebContent". Normally, I create a structure like the following:

    WebContent
       |__ index.html
       |__ webapp
              |__ scripts
              |__ views
              |__ styles
              |__ etc...

    This is just a basic webapp layout and you are free to change it to fit your needs.

    One of the last questions I had when I sat up this IDE was: "how to manage my dependencies in the JavaScript part of the webapp?". Originally, Maven was a tool that evolved strongly in the Java world and had less to nothing to do with JS. Therefore it's not the first choice when it comes to managing dependencies in JS. Tools that are preferred here are e.g. Grunt. Nevertheless I wanted to use Maven for my dependency management in Java as well as in JS. Fortunatly I found the webjars project ( http://www.webjars.org/ ), that ideally fitted my needs. Now I can add libraries like angular.js, bootstrap and all the like just like normal Java jars. To see how to add those libraries to your webapp just follow the instructions below and add a web library of your choice.

    How to add new Dependencies with Maven
    • Add Javascript Libs
      • R-Click Project -> Maven -> Add dependency -> Type Name (we work with org.webjars)
      • in index.html add line with <script src="webjars/<path/to/your/file.js>"></script>
      • the path can be looked up when you go to JavaResources -> Libraries -> Maven Dependencies -> <Your Library> -> META-INF -> resources -> webjars -> <everything from here on is your path>
    • Add Java Libs
      • R-Click Project -> Maven -> Add dependency -> Type Name 
      • use it

    Now that you know how to use your favorite web libraries with Maven you're free to go on and develop your own 3 tier web app. Well at this time we only had two tiers, but if you read the next post you can add the last tier easily ;)

    I hope you enjoyed reading this post and hopefully it helped you in some way to save time and money ;)

    Thanks for reading and we'll read us at the next post!



    Snippets:
    jersey_web_xml
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>de.uniaugsburg.mdsd.<package-where-your-services-are></param-value>
        </init-param>
    <init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>
      <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
      </servlet-mapping>
    </servlet>


    References

    How to set up Eclipse for 3 tier web application development

    Hey everyone!

    In the following posts I will describe the experiences I made with setting up a complete development environment for 3 tier web applications.
    For the client side we got Angular JS. In my last project I had a first glance at this framework and compared it with my previous experiences with SWT in Java. Afterwards, Angular JS became my framework of choice for the client side as it takes away a lot of the pain of GUI programming.
    The serverside is written in Java and bundles a lot of different frameworks for easier development of webservices, automatic serialisation, security and database connections.
    Which leads us to the database side, where we have MongoDB. Why MongoDB? Because I wanted to experience a little bit with NoSQL databases. Fortunatly EclipseLink, my chosen ORM, is capable of communicating with NoSQL Databases (at least with MongoDB and Oracle NoSQL) as of version 2.4.

    I think I just give you a complete list of what frameworks / technologies / whatsoever I will use and then you can jump right to the part that's interesting for you :)
    I hope you enjoy it...