Showing posts with label Spring REST. Show all posts
Showing posts with label Spring REST. Show all posts

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/




Sunday, 16 September 2012

Document base ... does not exist or is not a readable directory

I am having problems trying to get a simple Spring Controller to run on Tomcat 7.0 on kubuntu. I am using maven.

Error 


Sep 17, 2012 12:08:14 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /home/prayag/jdk1.6.0_23/jre/lib/i386/client:/home/prayag/jdk1.6.0_23/jre/lib/i386:/home/prayag/jdk1.6.0_23/jre/../lib/i386:/home/prayag/jdk1.6.0_23/jre/lib/i386/client:/home/prayag/jdk1.6.0_23/jre/lib/i386::/usr/java/packages/lib/i386:/lib:/usr/lib
Sep 17, 2012 12:08:15 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:RestServer' did not find a matching property.
Sep 17, 2012 12:08:15 PM org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Sep 17, 2012 12:08:15 PM org.apache.coyote.AbstractProtocolHandler init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 17, 2012 12:08:15 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 641 ms
Sep 17, 2012 12:08:15 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 17, 2012 12:08:15 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.12
Sep 17, 2012 12:08:15 PM org.apache.catalina.core.StandardContext resourcesStart
SEVERE: Error starting static Resources
java.lang.IllegalArgumentException: Document base /home/prayag/workspace_java/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/RestServer does not exist or is not a readable directory
 at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:140)
 at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4814)
 at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:4994)
 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
 at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
 at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:774)
 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
 at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1033)
 at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:291)
 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
 at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
 at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:727)
 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
 at org.apache.catalina.startup.Catalina.start(Catalina.java:620)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:303)
 at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:431)
Sep 17, 2012 12:08:15 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in resourceStart()
Sep 17, 2012 12:08:15 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
Sep 17, 2012 12:08:15 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/RestServer] startup failed due to previous errors
Sep 17, 2012 12:08:15 PM org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Sep 17, 2012 12:08:15 PM org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Sep 17, 2012 12:08:15 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 371 ms



DIAGNOSIS
Hack 1 : Check eclipse .metadata/.plugins
prayag@Prayag:~$ ls -la /home/prayag/workspace_java/.metadata/.plugins/org.eclipse.wst.server.core

total 32
drwxrwxrwx  3 prayag prayag 4096 Nov 27 11:22 .
drwxrwxrwx 98 prayag prayag 4096 Nov 26 16:48 ..
-rwxrwxrwx  1 prayag prayag  424 Sep 25 17:44 modules.xml
-rwxrwxrwx  1 prayag prayag   67 Nov 22 14:56 monitors.xml
drwxrwxrwx  2 prayag prayag 4096 Nov 27 11:22 publish
-rwxrwxrwx  1 prayag prayag   71 Nov 27 11:22 publish.xml
-rwxrwxrwx  1 prayag prayag   66 Nov 27 11:22 servers.xml
-rwxrwxrwx  1 prayag prayag   75 Nov 27 11:22 tmp-data.xml



Hack 2 :  Check .project file

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
  <name>RestServer</name>
  <comment>NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.</comment>
  <projects/>
  <buildSpec>
    <buildCommand>
      <name>org.eclipse.jdt.core.javabuilder</name>
    </buildCommand>
    <buildCommand>
      <name>org.eclipse.m2e.core.maven2Builder</name>
    </buildCommand>
    <buildCommand>
      <name>org.springframework.ide.eclipse.core.springbuilder</name>
    </buildCommand>
    <buildCommand>
      <name>com.google.gdt.eclipse.core.webAppProjectValidator</name>
    </buildCommand>
  </buildSpec>
  <natures>
    <nature>org.eclipse.jdt.core.javanature</nature>
    <nature>org.springframework.ide.eclipse.core.springnature</nature>
    <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
    <nature>org.eclipse.m2e.core.maven2Nature</nature>
    <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
  </natures>
</projectDescription>


Hack 3 : Check eclipse workspace Servers folder
prayag@Prayag:~/workspace_java$ ls -la Servers/
total 16
drwxrwxr-x  3 prayag prayag 4096 Nov 27 11:22 .
drwxrwxr-x 16 prayag prayag 4096 Nov 27 10:31 ..
-rw-rw-r--  1 prayag prayag  200 May 11  2012 .project
drwxrwxr-x  2 prayag prayag 4096 Nov 26 16:46 .settings

Check .project file inside Servers folder
prayag@Prayag:~/workspace_java$ sudo vi Servers/.project
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
        <name>Servers</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
        </buildSpec>
        <natures>
        </natures>
</projectDescription>


Solution
prayag@Prayag:~/workspace_java$ rm -rf Servers/

restart server

References
Unable to “Run on Server” a webapp from Eclipse, available at http://stackoverflow.com/a/12292469/432903

Problem running simple Servlet on Tomcat, at http://www.coderanch.com/t/86668/Tomcat/running-simple-Servlet-Tomcat