Sunday, August 24, 2014

How to Fix Unbound Classpath Variable Error in Eclipse?

  1. Open the Eclipse Preferences [Window - Preferences]
  1. Go to [Java - Build Path - Classpath Variables]
  1. Click New and set its name as M2_REPO
  1. Click Folder and select your Maven repository folder. For example, my repository folder is C:/Users/Firman El Hakim/.m2/repository

Add M2_REPO Variable

  1. Done. Rebuild the Project.

How To Remove Javascript validation Error in Eclipse


  1. Right click your project
  2. Select Properties -> JavaScript -> Include
  1. Select Source tab (It looks similar to the Java Build Path Source tab)
  1. Expand source folder
  1. Highlight Excluded pattern
  1. Click Edit button
  1. Click Add button next to Exclusion patterns box.

  1. Click Browse button and select the JavaScript source by name.

How to Solve Servlet [DispatcherServlet]: org.springframework.web.servlet.DispatcherServlet was found, but is missing another required class.

Error Message: javax.servlet.UnavailableException: SRVE0203E: Servlet [DispatcherServlet]: org.springframework.web.servlet.DispatcherServlet was found, but is missing another required class. SRVE0206E: This error typically implies that the servlet was originally compiled with classes which cannot be located by the server. SRVE0187E: Check your class path to ensure that all classes required by the servlet are present.SRVE0210I: This problem can be debugged by recompiling the servlet using only the classes in the application's runtime class path SRVE0234I: Application class path=[C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\java\lib;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\java\lib\dt.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\java\lib\htmlconverter.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\java\lib\ibmorbtools.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\java\lib\jconsole.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\java\lib\tools.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\profiles\node-monitor-ear\classes;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\classes;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\EJBCommandTarget.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\IVTClient.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\OTiSConvertTime.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\activation-impl.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\aspectjrt.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\bootstrap.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\bsf-engines.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\cimgr.ops.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\commandlineutils.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\commons-discovery.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\databeans.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\ffdcSupport.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\htmlshell.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\installver.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\installxml.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\iscdeploy.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\ivblogbr.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\j2ee.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\jNative2ascii.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\jacl.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\jrom.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\jsf-nls.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\lib\launchclient.jar;C:\Program Files (x86)\IBM\SDP80\runtimes\base_v7\li

Solution :
Right click web project -> Deployment Assembly -> Add... -> Java Build Path Entry -> Select the jar files from M2 Repo.

mvn clean install


Redeploy the app and check again.  

How To Solve CHKJ3000E: WAR Validation Failed

Problem - You would get error similar to below while using Eclipse.

:org.eclipse.jst.j2ee.commonarchivecore.internal.exception.DeploymentDescriptorLoadException: WEB-INF/web.xm

You may face error in a Eclipse Project  CHKJ3000E: WAR Validation Failed:


How to Solve it?

  1. Assuming that you have Mavenized your application, run the following command on command prompt in the project directory.  This is not a compulsory step but regenerates the manifest file.

del /S *.MF && mvn eclipse:clean eclipse:eclipse -U


  1. Once the above step is completed in the workspace right click on the web project and click on Validate.

Wednesday, August 20, 2014

How To Create Distributable Staging Build In Play

Play is one of the easiest and fastest frameworks to create Java and Scala based web applications.  Usually in J2EE applications deploying the web applications require application server and web server on which builds can be deployed.  Play is different.

You do not need any application server or web server.  You just need JRE in your system.  If you are able to run java and javac commands on the command prompt you should be able to run any play application. Isn't that wonderful?

One unique thing about Play build is for production you would need Unix or Linux environment.  The reason behind this is Play would need a separate process to run on.  That is truly possible on Unix and not Windows.  In Windows you can create a staging build.  Fortunately the process is similar for both Production and Staging as far as creating the build is concerned.  In this article I will show you how to create a Stage build for Windows environment.

How To Create Distributable Staging Build In Play (Ver 2.2.3)

Here are the steps to create staging build on Windows.  With help from (http://stackoverflow.com/questions/21429234/play-framework-2-stage-task-on-windows-the-input-line-is-too-long)


  1. Ensure that the Play application you have created runs on local Netty server.  Running it is very simple.  Just issue the command Play run on command prompt.  Then you should be able to access the application on browser at http://localhost:9000/  
  2. Ensure that JAVA_HOME is set to bin directory where java.exe and javac.exe are present on your computer.  For example in my machine JAVA_HOME is set as C:\Program Files (x86)\IBM\SDP80\jdk\bin
  3. Now go to command prompt and browse to the play application folder.
  4. Issue the command - Play clean stage
  5. This will create a directory [application-workspace]\target\universal\stage\bin
  6. You will find a file called [your_app].bat.  For example if the app name is helloWorld the file will be called helloWorld.bat.
  7. Create a folder dist in the [application-workspace] folder.
  8. Copy the bat file in step 5 to the dist folder.  The reason is next time automatically this file will be copied from the dist directory to the target folder.
  9. Edit the bat file in any text editor.
  10. Change the following line 
       if "%HELLOWORLD_HOME%"=="" set "HELLOWORLD_HOME=%~dp0\\.."
to
       if "%HELLOWORLD_HOME%"=="" set "HELLOWORLD_HOME=%~dp0\\"

Basically remove the last two dots (..) at the end of the line.  In my example the application name is helloWorld.  If your application name is different then you will see [application_name]_HOME as appropriate.
10. Search for the line which starts with set "APP_CLASSPATH=
11. It will have the names of all jar files required in the application....
set "APP_CLASSPATH=%APP_LIB_DIR%\helloworld.helloworld-1.0-SNAPSHOT.jar;%APP_LIB_DIR%\....
   Change this line to

set "APP_CLASSPATH=%APP_LIB_DIR%\helloworld.helloworld-1.0-SNAPSHOT.jar;%APP_LIB_DIR%\*"

Adding the asterisk at the end will ensure that all jar files are included in the class path.
12. Save the bat file and close it.
13. Now copy it back to [application-workspace]\target\universal\stage\bin 
14.  To test it go to [application-workspace]\target\universal\stage\bin and run the bat file.  You should see the something similar to
     Play server process ID is 14180
     [info] play - Application started (Prod)
     [info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
15. Now your application is ready to test.  You can access it on http://localhost:9000 in your browser.
16. Now you can zip your stage directory and distribute to other machines where JRE is available and run it on that machine.

Related Article 

How to Deploy Play Application on Tomcat

Wednesday, August 6, 2014

How To Connect Play Application To Derby Database

Play comes with embedded H2 database which can be used for testing out database applications.  However what about testing external databases just to make sure that your application can connect to them and the code will execute properly.

Derby is a open source light weight database provide by Apache.  Derby is made in Java and supports most of the SQL statements available in any SQL database.  In the post we will see how your application can be made to connect to Derby Database.

Here are the steps.


1. Download Derby from http://db.apache.org/derby/derby_downloads.html

2. Extract the zip file into a folder.

3.  Add a environment variable - DERBY_HOME.  The value should be <installation directory of Derby>

4.  In the path variable add the following - %DERBY_HOME%/bin;%PATH% . This will add the Derby bin folder to path where all the binaries for Derby are present.

5. Start the Derby Server by going to the  <installation directory of Derby>/bin directory and issue the following command - startNetworkServer.bat  The Derby server will start and listen on the port 1527.

6. In another command window issue the command ij.  This is also present in the bin folder of Derby installation folder.

7. Issue the following command -
     connect 'jdbc:derby://localhost:1527/db;create=true';
    This will connect to db database on Derby.  In case that database is not present it will create that database.

8.  Now create the table you need in the play framework.  For example in my application I am going to need an Employee table which has auto incremented id as primary key.  Here is the script to create that table.

ij> create table employee (
  id                        bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
  first_name                varchar(255),
  middle_name               varchar(255),
  last_name                 varchar(255),
  email_id                  varchar(255),
  contact_number1           varchar(255),
  contact_number2           varchar(255),
  customer_user_id          varchar(255),
  grade                     varchar(255)
);

9.  Now you need to make the changes in the Play application.

10. First we will change the application.conf and add the information as follows -
 db.default.driver=org.apache.derby.jdbc.ClientDriver
db.default.url="jdbc:derby://localhost:1527/db"

# Evolutions
# ~~~~~
# You can disable evolutions if needed
evolutionplugin=disabled

11.  Now add the Derby client jar dependency in the build.sbt

libraryDependencies ++= Seq(

  javaJdbc,

  javaEbean,

  cache,

  "org.apache.derby" % "derbyclient" % "10.8.3.0"

)    

The last line "org.apache.derby" % "derbyclient" % "10.8.3.0" is the most important line related to Derby.  It basically tells Play application to pick the jar from maven central with the following information :

GroupId   :  org.apache.derby
ArtifactId  : derbyclient
Version    : 10.8.3.0

12. If you have  Build.scala you can also add it there.  Usually if you are planning to create a war file from Play application Build.scala is required.  See how to create a Play framework war file here.

Restart the play application and it is now ready to connect to the Derby database.

How To Create a Play HelloWorld Application and Deploy to Tomcat

If you want yo try out deploying a Hello World Play application to Tom Cat it can be done in 15 minutes or less.

What you need in your System :

Play installed. - I have tested this in Play 2.2.3
Tomcat downloaded and configured. - Tomcat version where I tested is 7.0.55

Here are steps you need to follow -

1. At the command prompt go to the folder under which you are planning to create the play application.
2. Issue the command - play new helloworld
3. You will be prompted for more inputs.  Select Java as the template.  Although Scala is just as fine.
4. At the play prompt issue - play idea (if using intellij) or play eclipse (for eclipse users).  Now open the application in your editor.
5. Create a new file Build.scala in the project directory with following content.

import sbt._
import Keys._
import play.Project._
import com.github.play2war.plugin._

object ApplicationBuild extends Build {

  val appName = "y"
  val appVersion = "1.0-SNAPSHOT"

  val appDependencies = Seq(
    // Add your project dependencies here,
    javaCore,
    javaJdbc,
    javaEbean,
    cache
  )

  val main = play.Project(appName, appVersion, appDependencies)
    .settings(Play2WarPlugin.play2WarSettings: _*)

    .settings(
      Play2WarKeys.servletVersion := "3.0"
    )
  // Add your own project settings here
}

6. Open plugins.sbt in the project directory and overwrite the content with the following content -

// Comment to get more information during initialization
logLevel := Level.Warn

// The Typesafe repository
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

resolvers += "Play2war plugins release" at "http://repository-play-war.forge.cloudbees.com/release/"

// Use the Play sbt plugin for Play projects
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.2.3")

addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.2-beta2")

7. Open the build.sbt in the root directory and overwrite the content with content below.

import com.github.play2war.plugin._

name := "helloPlay"

version := "1.0-SNAPSHOT"

Play2WarPlugin.play2WarSettings

Play2WarKeys.servletVersion := "3.1"


libraryDependencies ++= Seq(
  javaJdbc,
  javaEbean,
  cache
)     

play.Project.playJavaSettings

8. Save the changes and go back to command prompt.

9. In the helloworld directory issue the command - play war

10. War will be generated in the target directory with the name helloplay-1.0-SNAPSHOT.war

11. Create another copy of the above war as helloplay.war

12. Copy the war to <tomcat installation directory>/webapps folder.

13. Start tomcat with the command startup.bat inside the bin directory which is inside tomcat installation directory.

14. You should see in the console that helloplay application is being deployed.

15.  You can access the application with the url - http://localhost:8080/helloplay/

16. You will see the following -


Monday, August 4, 2014

How To Return JSON As Output From Play Controller

Many times the client expects a JSON response from the controller here is how you can do it.  As you may be aware all Play controllers return object which is of type play.mvc.Result.  So how can you convert the response to JSON, especially if you are returning any object?

Assume that there is a object of Employee class which needs to be returned as JSON. Here is how you can return the employee object as JSON.

import java.io.ByteArrayOutputStream;
import com.fasterxml.jackson.databind.ObjectMapper;

    public static Result employeeAsJson(Long id) throws Exception{
        Employee employee = Employee.findById(id); //Find the employee
        response().setContentType("application/json"); //Sets the content type

        ByteArrayOutputStream ba = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(ba,employee); //convert the employee object to byte array output stream
        return ok(ba.toByteArray()); //return byte[ ]
    }

Since the content type of the response is set as Json you will get Json as output.

How to Convert List of Objects to Json in Play Framework?

We saw above how easily we can convert an object to Json output from a controller method.  How about a list of object?  That is also very simple.  In fact ObjectMapper class can easily do this for you as well.


import java.io.ByteArrayOutputStream;
import com.fasterxml.jackson.databind.ObjectMapper;

    public static Result employeesAsJson() throws Exception{
        List<Employee> employees = Employee.findAll(); //Return all employees as List
        response().setContentType("application/json"); //Sets the Content Type to json

        ByteArrayOutputStream ba = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(ba,employees); //Convert the employee object to byte array output stream
        return ok(ba.toByteArray()); //return byte[ ]
    }

As you can see the change was just sending the list of Employee to the writeValue method.  You will see output similar to below listing...

[{"id":1,"firstName":"Shailesh","middleName":"","lastName":"Sharma","emailId":"shaileshs@yash.com","contactNumber1":null,"contactNumber2":null,"customerUserId":null,"grade":"EE"},{"id":33,"firstName":"Abhijeet","middleName":"A","lastName":"Sawant","emailId":"abhijeet@yash.com","contactNumber1":null,"contactNumber2":null,"customerUserId":null,"grade":"E1"},{"id":34,"firstName":"Madhu","middleName":"","lastName":"Patel","emailId":"madhu@yash.com","contactNumber1":null,"contactNumber2":null,"customerUserId":null,"grade":"EE"},{"id":35,"firstName":"Chetan","middleName":"","lastName":"Bhagat","emailId":"chetan@yash.com","contactNumber1":null,"contactNumber2":null,"customerUserId":null,"grade":"E4"},{"id":41,"firstName":"Ashwin","middleName":"","lastName":"Patil","emailId":"aaa@aamm.com","contactNumber1":null,"contactNumber2":null,"customerUserId":null,"grade":"EE"},{"id":65,"firstName":"Another","middleName":"","lastName":"Name","emailId":"another@yash.com","contactNumber1":null,"contactNumber2":null,"customerUserId":null,"grade":"E5"}]

Thursday, July 31, 2014

Play Framework "Model Class" NOT an Entity Bean registered with this server?

Sometimes you may get PersistenceException while trying to run a Play application.

For example there is a Employee model class.  While running the play app it throws the following exception.

PersistenceException: models.Employee is NOT an Entity Bean registered with this server?


Solution : The simple solution is to annotate the Employee class with @Entity.  Doing this tells the application to treat the Employee model as an Entity.  Here is the code snippet...


import play.db.ebean.Model;
import javax.persistence.*;

@Entity
public class Employee extends Model{ ... }

Thursday, July 10, 2014

Understanding How :: Cons works in Scala

:: which is also pronounced as Cons is sometimes confusing to understand.  In this article let us try to understand how it works.

Before we try to understand Cons you should remember that every operation is actually a method call in Scala.  There is no such thing called operator, although the operation may falsely lead you to think that operands are being operated with an operator.

So What About + and - Operators?

You many think that simple operations such as 5 + 3 are using the + (plus) operator.  So how can we say operators are not there.

In Scala there is no primitive types.  So 5 is nothing but Int(5) and 3 is stored as Int(3).  There is a method named + in the Int class.  When we call 5 + 3 internally it calls (5).+(3), similarly 4 * 3 becomes (4).*(3).

Scala allow you to call method names with spaces and without the . (period) if there is a single parameter to the method name.  Hence (5).+(3) can be called as 5 + 3.

What About :: Cons?

:: is a special method which is used for prepending values.  Which means when you want to add a value to beginning of a list you can used cons or ::

For Example :

var names = List ("Roy","Randy","Amit")
var newNames = "Cindy" :: names
println(newNames)

Output would be

List(Cindy, Roy, Randy, Amit)

So how does it work?  If we keep the previous discussion in mind the :: should be a method which should work on the String "Cindy".  However in reality it works on the List names.

The reason is whenever any method name is invoked it is applied on the left operand in most cases apart from those method which end with a : (colon).  In those cases the method is invoked on the right operand.

In this case this method has a name :: which ends with a : so the method is invoked on the names List.

Just remember "Cindy" :: names is interpreted as names.::("Cindy")

Hopefully this will help you to understand how cons work.

How to Write public static void main in Scala

psvm or public static void main(String agrs[]) is the starting method for any Java new bee.  This method is static as the signature suggests  , hence it can be invoked from the command line.  So if you are starting Scala you may be thinking about the method which is equivalent to this method.

Here is that signature -

def main (args : Arrays[String]) : Unit = {
  //method body
}

Here is an example in a class.

object HelloWorld {
   def main (args : Arrays[String]) : Unit = {
      println("Hello World")
   }
}

As may notice we started keyword object.  This is how you created Singleton object in Scala.  Isn't it simple?  The main method can now be easily mapped to public static void main.  Unit is a datatype which is equivalent to void in java.  It basically means this method does not have return value.

Class Parameter Differences Between Scala And Java

Scala has something called class parameter.  In Java there is no such thing as class parameter but we can initialize a class with constructor arguments which look similar to class parameter in Scala.

Let's have a bit more detailed look.

Scala Class Example

We can define a Scala class as follows -

class Person(name : String) {
    def sayHello(){
      println("Hello "+name)
    }
}

Now to run the class after compiling you can do it the following way -

new Person("John").sayHello()

Output should be

Hello John

However in Java if we want to have send some parameter while instantiating the object it would be similar to following -

public class Person {
    String name ;
    Person(String name){
        this.name=name;
    }
    public void sayHello(){
        System.out.println("Hello"+name);
    }
}

while running we can then run in similar manner as

new Person("John").sayHello()

The output should be same as what we got in Scala.

So What are the Differences?

In Java the parameter passed in the constructor can't be used in any other method unless it is assigned to some field or property.  In Scala it is available for use in any other method of the instance directly.  However the parameter value is only available in this particular instance of the class.

Another difference is in Scala class parameter is defined while defining the class name and we do not need a separate constructor unlike in Java.

How to upgrade the Scala Class Parameters to fields or Properties?

Scala class parameters can be upgraded to fields very easily.  We can do that by adding the keywords val or var.

Here are examples -

class Person(var name : String) {
    def sayHello(){
      println("Hello "+name)
    }
}

class Person(val name : String) {
    def sayHello(){
      println("Hello "+name)
    }
}

If you add the val keyword the parameter becomes immutable field and in the byte code you can see a private field with public getter method.

If you add the var keyword the parameter becomes mutable field and in the byte code you can see a private field with public getter and setter methods.

Tuesday, July 8, 2014

How Does Scala List.map Function Work

When I was learning Scala I came across the List,map method.  It is defined as follows in the documentation ...

final def
map[B](f: (A) ⇒ B): List[B]

[use case] Builds a new collection by applying a function to all elements of this list.

How what does this mean and how can we use it?

Although from the definition it may look cryptic it becomes easier to understand once we have an example.   Let us see how to use List.map in Scala using a simple example -

Let us say you have defined a list of fruits as follows -

var fruits = List("Apple","Orange","Banana");

Now you want to convert each of the fruits into lower case and return another List.  This can be achieved very easily with List.map function.

var lowerCaseFruits = fruits.map(fruit => fruit.toLowerCase)
println(lowerCaseFruits)

The map function is applied on the fruits list and each element is stored in the fruit element one by one. Then the element is converted to lower case using the String lower case function and then stored in another list which is eventually returned back.  In this case the output List is stored in the variable lowerCaseFruits.

There is more fun to List. The output of List.map can be again chained to another List.map.  Here is an example -

var listOfNumber = List(1,2,3)
var nums = listOfNumber.map(number => number * 2).map(number => number * number)
println(nums)

Can you guess what will be the output and why?

What Happens When Scala Set Contains Duplicate Elements

Set is a collection of non duplicate items.  In Scala also the concept is similar.  So what happens when you have a Set defined with duplicate items.

For example : 

    val vege = Set("Radish","Carrot","Carrot","Potato");
    println(vege);

You may expect the compiler to complain since Carrot occurs twice in the Set.  However see the result below on what happens -

Set(Radish, Carrot, Potato)

It simply means that Scala ignores the duplicate entry in the Set and does not complain.

Cool...