Showing posts with label jetty. Show all posts
Showing posts with label jetty. Show all posts

Friday, 16 November 2012

Hacking on liftweb 2.5 and sbt 0.12



STEP 1 Download the ‘Lift Basic’ template
prayag@prayag:/backup/workspace.programming/workspace.scala$ git clone git://github.com/lift/lift_25_sbt.git
Cloning into 'lift_25_sbt'...
remote: Counting objects: 881, done.
remote: Compressing objects: 100% (506/506), done.
remote: Total 881 (delta 301), reused 839 (delta 259)
Receiving objects: 100% (881/881), 3.03 MiB | 20 KiB/s, done.
Resolving deltas: 100% (301/301), done.

Going through the liftweb app structure
prayag@prayag:/backup/workspace.programming/workspace.scala/lift_25_sbt/scala_29$ ls -l lift_basic/
total 1100
-rw-rw-r-- 1 prayag prayag    1159 Nov 16 16:33 build.sbt
drwxrwxr-x 2 prayag prayag    4096 Nov 16 16:33 project
-rwxrwxr-x 1 prayag prayag     116 Nov 16 16:33 sbt
-rw-rw-r-- 1 prayag prayag     137 Nov 16 16:33 sbt.bat
-rw-rw-r-- 1 prayag prayag 1103617 Nov 16 16:33 sbt-launch-0.12.jar
drwxrwxr-x 4 prayag prayag    4096 Nov 16 16:33 src

There is sbt-launch-0.12.jar, which means the Lift Basic template comes with a SBT launcher, so there’s no need to install sbt separately.

The src/main structure is 
prayag@prayag:/backup/workspace.programming/workspace.scala/lift_25_sbt/scala_29$ ls -l lift_basic/src/main/
total 12
drwxrwxr-x 3 prayag prayag 4096 Nov 16 16:33 resources
drwxrwxr-x 4 prayag prayag 4096 Nov 16 16:33 scala
drwxrwxr-x 6 prayag prayag 4096 Nov 16 16:33 webapp

The MVC looking architecture of liftweb is 
prayag@prayag:/backup/workspace.programming/workspace.scala/lift_25_sbt/scala_29$ ls -l lift_basic/src/main/scala/code/
total 20
drwxrwxr-x 2 prayag prayag 4096 Nov 16 16:33 comet
drwxrwxr-x 2 prayag prayag 4096 Nov 16 16:33 lib
drwxrwxr-x 2 prayag prayag 4096 Nov 16 16:33 model
drwxrwxr-x 2 prayag prayag 4096 Nov 16 16:33 snippet
drwxrwxr-x 2 prayag prayag 4096 Nov 16 16:33 view

STEP 2 : Building an app
Add Lift and Jetty to project dependencies:
#The build.sbt file is

name := "Lift 2.5 starter template"

version := "0.0.1"

organization := "net.liftweb"

scalaVersion := "2.9.1"

resolvers ++= Seq("snapshots"     at "http://oss.sonatype.org/content/repositories/snapshots",
                "releases"        at "http://oss.sonatype.org/content/repositories/releases"
                )

seq(com.github.siasia.WebPlugin.webSettings :_*)

scalacOptions ++= Seq("-deprecation", "-unchecked")

libraryDependencies ++= {
  val liftVersion = "2.5-M3"
  Seq(
    "net.liftweb"       %% "lift-webkit"        % liftVersion        % "compile",
    "net.liftweb"       %% "lift-mapper"        % liftVersion        % "compile",
    "net.liftmodules"   %% "lift-jquery-module" % (liftVersion + "-2.0"),
    "org.mortbay.jetty" % "jetty" % "6.1.22"    % "container",
    "org.eclipse.jetty" % "jetty-webapp"        % "8.1.7.v20120910"  % "container,test",
    "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container,test" artifacts Artifact("javax.servlet", "jar", "jar"),
    "ch.qos.logback"    % "logback-classic"     % "1.0.6",
    "org.specs2"        %% "specs2"             % "1.12.1"           % "test",
    "com.h2database"    % "h2"                  % "1.3.167"
  )
}

The project/plugins.sbt file is 
libraryDependencies <+= sbtVersion(v => "com.github.siasia" %% "xsbt-web-plugin" % "0.12.0-0.2.11.1")

//Uncoment this line to enable the sbt idea plugin
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.1.0")

//Uncoment this line to enable the sbt eclipse plugin
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")


The sbt script is 

prayag@prayag:/backup/workspace.programming/workspace.scala/lift_25_sbt/scala_29/lift_basic$ sudo vi sbt


java -Xmx1024M -Xss2M -XX:MaxPermSize=512m -XX:+CMSClassUnloadingEnabled -jar `dirname $0`/sbt-launch-0.12.jar "$@"

The command ‘sbt update ~jetty-run’ will download all necessary libraries (Scala, Lift, Jetty, etc) like mvn install does in maven, compile the application, and then launch Jetty as an embedded application – there’s no need to install Jetty separately, (~jetty-run isn't working in my case).
prayag@prayag:/backup/workspace.programming/workspace.scala/lift_25_sbt/scala_29/lift_basic$ ./sbt update ~jetty-run


STEP 3 : Run app with sbt
sbt tasks can be viewed with $ sbt tasks command.
prayag@prayag:/backup/workspace.programming/workspace.scala/lift_25_sbt/scala_29/lift_basic$ ./sbt
> update
> container:start
[info] Compiling 4 Scala sources to /backup/workspace.programming/workspace.scala/lift_25_sbt/scala_29/lift_basic/target/scala-2.9.1/classes...
[info] 'compiler-interface' not yet compiled for Scala 2.9.1.final. Compiling...
[info]   Compilation completed in 37.636 s
2012-11-16 23:14:24.820:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
[info] jetty-6.1.22
[info] NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
[info] Started SelectChannelConnector@0.0.0.0:8080
[success] Total time: 56 s, completed 16-Nov-2012 23:14:30

Open http://localhost:8080 in a web browser to see the application running.


References
Getting Started, https://www.assembla.com/spaces/liftweb/wiki/Getting_Started

Tuesday, 16 October 2012

Getting started with liftweb framework


Required 
Java
maven2 or sbt
jetty - a Java servlet engine
scala

STEP 1 Install Java and configure PATH
http://www.oracle.com/technetwork/java/javase/downloads/jdk7u9-downloads-1859576.html

STEP 2 Install scala 2.9.2
Download scala from http://www.scala-lang.org/downloads

$ wget  http://www.scala-lang.org/files/archive/scala-2.9.2.tgz

$ sudo mkdir /opt/scala292
Open the dowloaded file (Archive manager - file-roller) and extract to /opt/scala/

Create a sybolic link (future proof the install):
$ ln -s /opt/scala/scala-2.9.2 /opt/scala292/current

Define environment variable SCALA_HOME by editing /etc/profile and adding the line:
export SCALA_HOME=/opt/scala292/current

Add the Scala executables to your path by editing /etc/profile and adding the line:
export PATH=$PATH:$SCALA_HOME/bin

restart computer, and enter command
scala -version
Scala code runner version 2.9.2  -- Copyright 2002-2011, LAMP/EPFL


STEP 3 Install maven
$ sudo apt-get install maven2

OR
Download maven from http://maven.apache.org/download.html and configure PATH.
(mine /etc/profile is)

JAVA_HOME=/usr/java/jdk1.7.0; export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH; export PATH
export PATH=$PATH:/home/prayag/apache-maven-3.0.4/bin


STEP 4 Install jetty, an HTTP server, HTTP client, and javax.servlet container
$ sudo apt-get install jetty


STEP 5 Create liftweb app with mvn
$ mkdir /home/prayag/workspace_lift
$ cd /home/prayag/workspace_lift

Issue the following maven2 command for a lift project template downloaded from http://scala-tools.org/repo-snapshots :

mvn archetype:generate \
 -DarchetypeGroupId=net.liftweb \
 -DarchetypeArtifactId=lift-archetype-basic_2.9.1 \
 -DarchetypeVersion=2.4-M5 \
 -DarchetypeRepository=http://scala-tools.org/repo-releases \
 -DremoteRepositories=http://scala-tools.org/repo-releases \
 -DgroupId=com.zam.gwitter \
 -DartifactId=gwitter \
 -Dversion=1.0

The architecture of app will be as follows :

5 - A) The dependencies in pom.xml will be as follows :
<repositories>
    <repository>
      <id>scala-tools.releases</id>
      <name>Scala-Tools Dependencies Repository for Releases</name>
      <url>http://scala-tools.org/repo-releases</url>
    </repository>
    <repository>
      <id>java.net.maven2</id>
      <name>java.net Maven2 Repository</name>
      <url>http://download.java.net/maven/2/</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>scala-tools.releases</id>
      <name>Scala-Tools Plugins Repository for Releases</name>
      <url>http://scala-tools.org/repo-releases</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>net.liftweb</groupId>
      <artifactId>lift-mapper_2.9.1</artifactId>
      <version>2.4-M5</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>0.9.26</version>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>1.2.138</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.7</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.scala-tools.testing</groupId>
      <artifactId>specs_2.9.1</artifactId>
      <version>1.6.9</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jetty</artifactId>
      <version>6.1.25</version>
      <scope>test</scope>
    </dependency>
    <!-- for LiftConsole -->
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-compiler</artifactId>
      <version>${scala.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

5 - B) The gwitter/src/main/webapp/WEB-INF/web.xml file will be as follows :
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<filter>
  <filter-name>LiftFilter</filter-name>
  <display-name>Lift Filter</display-name>
  <description>The Filter that intercepts lift calls</description>
  <filter-class>net.liftweb.http.LiftFilter</filter-class>
</filter>
   

<filter-mapping>
  <filter-name>LiftFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>


5 - C) The gwitter/src/main/webapp/index.html will be as follows :
<div class="lift:surround?with=default;at=content">
  <h2>Welcome to your project!</h2>
  <p>
    <div class="lift:helloWorld.howdy">
      Welcome to gwitter at <span id="time">The current time</span>
    </div>
  </p>
</div>



5 - D) The com/zam/gwitter/model/User.scala will be as follows :
package com.zam.gwitter {
package model {

import _root_.net.liftweb.mapper._
import _root_.net.liftweb.util._
import _root_.net.liftweb.common._

/**
 * The singleton that has methods for accessing the database
 */
object User extends User with MetaMegaProtoUser[User] {
  override def dbTableName = "User" // define the DB table name
  override def screenWrap = Full(<lift:surround with="default" at="content">
          <lift:bind /></lift:surround>)
  // define the order fields will appear in forms and output
  override def fieldOrder = List(id, firstName, lastName, email,
  locale, timezone, password, textArea)

  // comment this line out to require email validations
  override def skipEmailValidation = true
}

/**
 * An O-R mapped "User" class that includes first name, last name, password and we add a "Personal Essay" to it
 */
class User extends MegaProtoUser[User] {
  def getSingleton = User // what's the "meta" server

  // define an additional field for a personal essay
  object textArea extends MappedTextarea(this, 2048) {
    override def textareaRows  = 10
    override def textareaCols = 50
    override def displayName = "Personal Essay"
  }
}
}
}

5 - E)  The com/zam/gwitter/snippet/HelloWorld.scala snippet will be as follows:
package com.zam.gwitter {
package snippet {

import _root_.scala.xml.{NodeSeq, Text}
import _root_.net.liftweb.util._
import _root_.net.liftweb.common._
import _root_.java.util.Date
import com.zam.gwitter.lib._
import Helpers._

class HelloWorld {
  lazy val date: Box[Date] = DependencyFactory.inject[Date] // inject the date

  // bind the date into the element with id "time"
  def howdy = "#time *" #> date.map(_.toString)

  /*
   lazy val date: Date = DependencyFactory.time.vend // create the date via factory

   def howdy = "#time *" #> date.toString
   */
}//end of class
}
}

5 - F)  The com/zam/gwitter/lib/DependencyFactory.scala will be as follows :
package com.zam.gwitter {
package lib {

import net.liftweb._
import http._
import util._
import common._
import _root_.java.util.Date

/**
 * A factory for generating new instances of Date.  You can create
 * factories for each kind of thing you want to vend in your application.
 * An example is a payment gateway.  You can change the default implementation,
 * or override the default implementation on a session, request or current call
 * stack basis.
 */
object DependencyFactory extends Factory {
  implicit object time extends FactoryMaker(Helpers.now _)

  /**
   * objects in Scala are lazily created.  The init()
   * method creates a List of all the objects.  This
   * results in all the objects getting initialized and
   * registering their types with the dependency injector
   */
  private def init() {
    List(time)
  }
  init()
}

/*
/**
 * Examples of changing the implementation
 */
sealed abstract class Changer {
  def changeDefaultImplementation() {
    DependencyFactory.time.default.set(() => new Date())
  }

  def changeSessionImplementation() {
    DependencyFactory.time.session.set(() => new Date())
  }

  def changeRequestImplementation() {
    DependencyFactory.time.request.set(() => new Date())
  }

  def changeJustForCall(d: Date) {
    DependencyFactory.time.doWith(d) {
      // perform some calculations here
    }
  }
}
*/
}
}


STEP 6 Run a liftweb app
Issue mvn jetty:run and access the web application in your browser via http://localhost:8080

STEP 7 RESULT





REFERENCES
1 - Lift + Scala, Installation + First contact, 11. AUGUST 2010 available at http://tuxpool.blogspot.com/2010/08/lifting-scala-installation-first.html

2 - Using Maven, available at https://www.assembla.com/wiki/show/liftweb/Using_Maven

Tuesday, 18 September 2012

Spring REST JSON Server

I was in process of making a Json server in Spring 3. With lots of research and hack I did it with configuration as following :

Creating Maven Web Project in eclipse
[Step 1] File->New ->Maven Project








[Step 2 ] Select an Archetype (maven-archetype-webapp)
Type webapp in Filter, and select the one with artifactId maven-archetype-webapp.








[Step 3 ] Specify Archetype parameters(groupId, artifactId)






There won't be any java and test folders by default, for which they have be created manually and the project needs to get eclipsified with $ mvn eclipse:eclipse.
(maven-archetype-webapp eclipse problem, stackoverflow)

Structure of the app is :


prayag@prayag:~/git/SpringRESTServer/SpringRESTServer$ ls -l
total 24
-rw-rw-r-- 1 prayag prayag 12642 Nov  2 12:31 pom.xml
drwxrwxr-x 4 prayag prayag  4096 Sep 19 11:24 src
drwxrwxr-x 3 prayag prayag  4096 Nov  2 12:32 target
prayag@prayag:~/git/SpringRESTServer/SpringRESTServer$ ls -l src/main/
total 12
drwxrwxr-x 3 prayag prayag 4096 Sep 18 10:23 java
drwxrwxr-x 4 prayag prayag 4096 Sep 19 12:32 resources
drwxrwxr-x 3 prayag prayag 4096 Sep 18 10:20 webapp
prayag@prayag:~/git/SpringRESTServer/SpringRESTServer$ ls -l src/main/webapp/
total 4
drwxrwxr-x 3 prayag prayag 4096 Sep 19 12:47 WEB-INF



[STEP 4 ] add spring and jackson dependency to pom.xml

<project>

[...]

<!-- jackson mapper -->

  <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.0</version>
  </dependency>

   <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-core-asl</artifactId>
   <version>1.9.0</version>
  </dependency>

<!-- jackson mapper -->

[...]

</project>

[STEP 5 ] configure DD (/WEB-INF/web.xml) 

<?xml version="1.0" encoding="UTF-8"?>
<!-- Use this definition if using a Java EE 6 container This also stops Eclipse 
 from complaining that 3.0 is not a valid version <web-app version="3.0" 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"> -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

 version="2.5">
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/root-context.xml</param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

  <servlet>
  <servlet-name>appServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/servlet-context.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

  <servlet-mapping>
  <servlet-name>appServlet</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>


[STEP 6 ] configure  /WEB-INF/servlet-context.xml (a view resolver)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
xmlns:p="http://www.springframework.org/schema/p">

<!-- Root Context: defines shared resources visible to all other web components -->
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
</list>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>

<import resource="classpath:/WEB-INF/controllers.xml" />

</beans>

STEP 7 : create @controller (BootController.java)

package com.zcode.springrestserver.web.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcode.springrestserver.web.domain.User;


/**

 * @author prayag
 * 
 */
@Controller
public class BootController {
@RequestMapping(value = "/", method = RequestMethod.GET, headers = "Accept=*/*")
public @ResponseBody
User login() {
User user = new User();
user.setName("prayag");

return user;

}
}

STEP 8 : create a model (User.java)

/**
 * 
 */
package com.zcode.springrestserver.web.domain;


/**

 * @author prayag
 * 
 */

public class User {
private long id;
private String name;

public long getId() {

return id;
}

public String getName() {

return name;
}

public void setId(long id) {

this.id = id;
}

public void setName(String name) {

this.name = name;
}

}



[STEP 9 ] Maven Compile 

prayag@prayag:~/git/SpringRESTServer/SpringRESTServer$ /usr/eclipse/apache-maven-3.0.4/bin/mvn clean compile
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringRESTServer Maven Webapp 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ SpringRESTServer ---
[INFO] Deleting /home/prayag/git/SpringRESTServer/SpringRESTServer/target
[INFO] 
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ SpringRESTServer ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 7 resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ SpringRESTServer ---
[INFO] Compiling 11 source files to /home/prayag/git/SpringRESTServer/SpringRESTServer/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.544s
[INFO] Finished at: Fri Nov 02 12:44:59 NPT 2012
[INFO] Final Memory: 12M/30M
[INFO] ------------------------------------------------------------------------



[STEP 10 ] run app in jetty server


prayag@prayag:~/git/SpringRESTServer/SpringRESTServer$ /usr/eclipse/apache-maven-3.0.4/bin/mvn jetty:run
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building SpringRESTServer Maven Webapp 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> maven-jetty-plugin:6.1.25:run (default-cli) @ SpringRESTServer >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ SpringRESTServer ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 7 resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ SpringRESTServer ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.5:testResources (default-testResources) @ SpringRESTServer ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/prayag/git/SpringRESTServer/SpringRESTServer/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ SpringRESTServer ---
[INFO] Compiling 1 source file to /home/prayag/git/SpringRESTServer/SpringRESTServer/target/test-classes
[INFO] 
[INFO] <<< maven-jetty-plugin:6.1.25:run (default-cli) @ SpringRESTServer <<<
[INFO] 
[INFO] --- maven-jetty-plugin:6.1.25:run (default-cli) @ SpringRESTServer ---
Downloading: http://repository.sourcesense.com/nexus/content/repositories/public/junit/junit/3.8.2/junit-3.8.2.jar
Downloading: http://repository.sourcesense.com/nexus/content/repositories/public/org/codehaus/plexus/plexus-utils/1.1/plexus-utils-1.1.jar
Downloading: http://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/1.1/plexus-utils-1.1.jar
Downloading: http://repo.maven.apache.org/maven2/junit/junit/3.8.2/junit-3.8.2.jar
Downloaded: http://repo.maven.apache.org/maven2/junit/junit/3.8.2/junit-3.8.2.jar (118 KB at 26.2 KB/sec)
Downloaded: http://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/1.1/plexus-utils-1.1.jar (165 KB at 31.3 KB/sec)
[INFO] Configuring Jetty for project: SpringRESTServer Maven Webapp
[INFO] Webapp source directory = /home/prayag/git/SpringRESTServer/SpringRESTServer/src/main/webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = /home/prayag/git/SpringRESTServer/SpringRESTServer/target/classes
2012-11-02 13:03:41.540:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
[INFO] Context path = /SpringRESTServer
[INFO] Tmp directory =  determined at runtime
[INFO] Web defaults = org/mortbay/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] web.xml file = /home/prayag/git/SpringRESTServer/SpringRESTServer/src/main/webapp/WEB-INF/web.xml
[INFO] Webapp directory = /home/prayag/git/SpringRESTServer/SpringRESTServer/src/main/webapp
[INFO] Starting jetty 6.1.25 ...
2012-11-02 13:03:41.787:INFO::jetty-6.1.25
2012-11-02 13:03:43.135:INFO::No Transaction manager found - if your webapp requires one, please configure one.
2012-11-02 13:03:44.740:INFO:/SpringRESTServer:Initializing Spring root WebApplicationContext
13:03:44.742 [main] INFO  o.s.web.context.ContextLoader - Root WebApplicationContext: initialization started
13:03:44.800 [main] INFO  o.s.w.c.s.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Fri Nov 02 13:03:44 NPT 2012]; root of context hierarchy
13:03:44.844 [main] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/root-context.xml]
13:03:45.073 [main] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [WEB-INF/jpa-context.xml]
13:03:45.183 [main] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [WEB-INF/repository-context.xml]
13:03:45.235 [main] DEBUG o.s.d.r.c.AbstractRepositoryConfigDefinitionParser - Triggering auto repository detection
13:03:45.293 [main] DEBUG o.s.d.r.c.AbstractRepositoryConfigDefinitionParser$RepositoryComponentProvider - Identified candidate component class: file [/home/prayag/git/SpringRESTServer/SpringRESTServer/target/classes/com/zcode/springrestserver/web/repository/UserRepository.class]
13:03:45.299 [main] DEBUG o.s.d.r.c.AbstractRepositoryConfigDefinitionParser - Registering repository: userRepository - Interface: com.zcode.springrestserver.web.repository.UserRepository - Factory: org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean, - Custom implementation: null
13:03:45.299 [main] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [WEB-INF/api-context.xml]
13:03:45.318 [main] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [WEB-INF/service-context.xml]
13:03:45.331 [main] INFO  o.s.b.f.s.DefaultListableBeanFactory - Overriding bean definition for bean 'placeholderConfig': replacing [Generic bean: class [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer]; scope=; abstract=false; lazyInit=false; autowireMode=1; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [WEB-INF/jpa-context.xml]] with [Generic bean: class [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in ServletContext resource [/WEB-INF/root-context.xml]]
13:03:45.594 [main] INFO  o.s.b.f.c.PropertyPlaceholderConfigurer - Loading properties file from ServletContext resource [/WEB-INF/db.properties]
13:03:45.711 [main] INFO  o.s.w.c.s.XmlWebApplicationContext - Bean 'dataSource' of type [class org.apache.commons.dbcp.BasicDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
13:03:45.733 [main] INFO  o.s.w.c.s.XmlWebApplicationContext - Bean 'org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter#1069693' of type [class org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
13:03:45.752 [main] INFO  o.s.o.j.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'springPU'
13:03:45.965 [main] INFO  o.h.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
13:03:45.971 [main] INFO  org.hibernate.cfg.Environment - Hibernate 3.6.6.Final
13:03:45.973 [main] INFO  org.hibernate.cfg.Environment - hibernate.properties not found
13:03:45.975 [main] INFO  org.hibernate.cfg.Environment - Bytecode provider name : javassist
13:03:45.977 [main] INFO  org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
13:03:46.067 [main] INFO  org.hibernate.ejb.Version - Hibernate EntityManager 3.6.6.Final
13:03:46.076 [main] INFO  org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
        name: springPU
        ...]
13:03:46.191 [main] WARN  org.hibernate.ejb.Ejb3Configuration - Defining hibernate.transaction.flush_before_completion=true ignored in HEM
13:03:46.233 [main] INFO  org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.zcode.springrestserver.web.domain.User
13:03:46.264 [main] INFO  o.h.cfg.annotations.EntityBinder - Bind entity com.zcode.springrestserver.web.domain.User on table User
13:03:46.302 [main] INFO  org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
13:03:46.320 [main] INFO  org.hibernate.validator.util.Version - Hibernate Validator 4.0.0.GA
13:03:46.342 [main] INFO  o.h.v.e.r.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
13:03:46.427 [main] INFO  o.h.v.e.r.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
13:03:46.431 [main] INFO  o.h.v.e.r.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
13:03:46.436 [main] INFO  o.h.c.s.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
13:03:46.439 [main] INFO  o.h.c.ConnectionProviderFactory - Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
13:03:46.441 [main] INFO  o.h.e.c.InjectedDataSourceConnectionProvider - Using provided datasource
13:03:46.898 [main] INFO  org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQL5Dialect
13:03:46.921 [main] INFO  o.h.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
13:03:46.921 [main] INFO  org.hibernate.cfg.SettingsFactory - Database ->
       name : MySQL
    version : 5.0.45-log
      major : 5
      minor : 0
13:03:46.921 [main] INFO  org.hibernate.cfg.SettingsFactory - Driver ->
       name : MySQL-AB JDBC Driver
    version : mysql-connector-java-5.1.17 ( Revision: ${bzr.revision-id} )
      major : 5
      minor : 1
13:03:46.947 [main] INFO  o.h.t.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
13:03:46.948 [main] INFO  o.h.t.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
13:03:46.948 [main] INFO  org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
13:03:46.948 [main] INFO  org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
13:03:46.948 [main] INFO  org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
13:03:46.948 [main] INFO  org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
13:03:46.949 [main] INFO  org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
13:03:46.949 [main] INFO  org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
13:03:46.949 [main] INFO  org.hibernate.cfg.SettingsFactory - Connection release mode: auto
13:03:46.949 [main] INFO  org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
13:03:46.949 [main] INFO  org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
13:03:46.950 [main] INFO  org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
13:03:46.950 [main] INFO  org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
13:03:46.950 [main] INFO  org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
13:03:46.950 [main] INFO  org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
13:03:46.953 [main] INFO  o.h.h.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
13:03:46.953 [main] INFO  org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
13:03:46.953 [main] INFO  org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: enabled
13:03:46.954 [main] INFO  org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
13:03:46.954 [main] INFO  org.hibernate.cfg.SettingsFactory - Query cache: disabled
13:03:46.954 [main] INFO  org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
13:03:46.956 [main] INFO  o.h.c.i.b.RegionFactoryCacheProviderBridge - Cache provider: org.hibernate.cache.HashtableCacheProvider
13:03:46.956 [main] INFO  org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
13:03:46.957 [main] INFO  org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
13:03:46.959 [main] INFO  org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
13:03:46.959 [main] INFO  org.hibernate.cfg.SettingsFactory - Statistics: disabled
13:03:46.959 [main] INFO  org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
13:03:46.960 [main] INFO  org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
13:03:46.960 [main] INFO  org.hibernate.cfg.SettingsFactory - Named query checking : enabled
13:03:46.960 [main] INFO  org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): disabled
13:03:46.971 [main] INFO  o.hibernate.impl.SessionFactoryImpl - building session factory
13:03:46.974 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [blob] overrides previous : org.hibernate.type.BlobType@171ef98
13:03:46.974 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Blob] overrides previous : org.hibernate.type.BlobType@171ef98
13:03:46.974 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [clob] overrides previous : org.hibernate.type.ClobType@1290ef4
13:03:46.974 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [java.sql.Clob] overrides previous : org.hibernate.type.ClobType@1290ef4
13:03:46.974 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_materialized_blob] overrides previous : org.hibernate.type.WrappedMaterializedBlobType@94e4f4
13:03:46.974 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType@143691d
13:03:46.975 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [wrapper_characters_clob] overrides previous : org.hibernate.type.CharacterArrayClobType@aa168c
13:03:46.975 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [characters_clob] overrides previous : org.hibernate.type.PrimitiveCharacterArrayClobType@ae43b8
13:03:46.975 [main] INFO  org.hibernate.type.BasicTypeRegistry - Type registration [materialized_clob] overrides previous : org.hibernate.type.MaterializedClobType@e00321
13:03:47.090 [main] INFO  o.h.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
13:03:47.093 [main] INFO  o.h.tool.hbm2ddl.SchemaUpdate - Running hbm2ddl schema update
13:03:47.093 [main] INFO  o.h.tool.hbm2ddl.SchemaUpdate - fetching database metadata
13:03:47.096 [main] INFO  o.h.tool.hbm2ddl.SchemaUpdate - updating schema
13:03:47.098 [main] INFO  o.h.v.e.r.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
13:03:47.131 [main] INFO  o.h.tool.hbm2ddl.TableMetadata - table found: spring.User
13:03:47.131 [main] INFO  o.h.tool.hbm2ddl.TableMetadata - columns: [id, authority, username, created, lastmodified, password, deleted, fullname, disabled, version]
13:03:47.131 [main] INFO  o.h.tool.hbm2ddl.TableMetadata - foreign keys: []
13:03:47.132 [main] INFO  o.h.tool.hbm2ddl.TableMetadata - indexes: [primary]
13:03:47.133 [main] INFO  o.h.tool.hbm2ddl.SchemaUpdate - schema update complete
13:03:47.173 [main] INFO  o.s.w.c.s.XmlWebApplicationContext - Bean 'entityManagerFactory' of type [class org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
13:03:47.189 [main] INFO  o.s.w.c.s.XmlWebApplicationContext - Bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
13:03:47.191 [main] INFO  o.s.w.c.s.XmlWebApplicationContext - Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
13:03:47.197 [main] INFO  o.s.b.f.s.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d6a0e0: defining beans [placeholderConfig,entityManagerFactory,dataSource,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,userRepository,org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor#0,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,userAPI,userService]; root of factory hierarchy
13:03:47.306 [main] DEBUG o.s.d.j.r.query.SimpleJpaQuery - Looking up query for method findByUserNameAndPassword
13:03:47.619 [main] INFO  o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 2875 ms
2012-11-02 13:03:47.788:INFO:/SpringRESTServer:Initializing Spring FrameworkServlet 'appServlet'
13:03:47.788 [main] INFO  o.s.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
13:03:47.790 [main] INFO  o.s.w.c.s.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Fri Nov 02 13:03:47 NPT 2012]; parent: Root WebApplicationContext
13:03:47.790 [main] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/servlet-context.xml]
13:03:47.828 [main] INFO  o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [WEB-INF/controllers.xml]
13:03:47.935 [main] INFO  o.s.b.f.s.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1ba3523: defining beans [org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,com.zcode.springrestserver.web.controller.BootController#0,com.zcode.springrestserver.web.controller.PersistenceController#0]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@d6a0e0
13:03:48.284 [main] INFO  o.s.w.s.m.a.DefaultAnnotationHandlerMapping - Root mapping to handler 'com.zcode.springrestserver.web.controller.BootController#0'
13:03:48.285 [main] INFO  o.s.w.s.m.a.DefaultAnnotationHandlerMapping - Mapped URL path [/persistence] onto handler 'com.zcode.springrestserver.web.controller.PersistenceController#0'
13:03:48.285 [main] INFO  o.s.w.s.m.a.DefaultAnnotationHandlerMapping - Mapped URL path [/persistence.*] onto handler 'com.zcode.springrestserver.web.controller.PersistenceController#0'
13:03:48.285 [main] INFO  o.s.w.s.m.a.DefaultAnnotationHandlerMapping - Mapped URL path [/persistence/] onto handler 'com.zcode.springrestserver.web.controller.PersistenceController#0'
13:03:48.286 [main] INFO  o.h.v.e.r.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
13:03:48.930 [main] INFO  o.s.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 1141 ms
2012-11-02 13:03:48.986:INFO::Started SelectChannelConnector@0.0.0.0:8080
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 3 seconds.


OR
To run with eclipse webtools(ie fuking Run on server.. option), add the following plugin block to build of pom.xml and fire mvn eclipse:eclipse.

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.8</version>
<configuration>
<wtpversion>2.0</wtpversion>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>

[STEP 11 ] Goto browser and hit http://localhost:8080/SpringRESTServer/

Expected Result 
{"id":0,"name":"prayag"}




Source Code
The full source code is available at github - https://github.com/iPrayag/spring-rest-server

References :
1 - JSON / Ajax in Spring MVC, available at http://www.gotoquiz.com/web-coding/programming/java-programming/jsonajax-in-spring-mvc/


2 - REST with Spring - ContentNegotiatingViewResolver vs. HttpMessageConverter+ResponseBody Annotation, available at
http://www.gotoquiz.com/web-coding/programming/java-programming/jsonajax-in-spring-mvc/