Webcam Access using Java and Maven

After lots of implementations on JMF,OpenCV and JavaCV i came across “Webcam Capture” a Generic Webcam Java Utility which has the capability of maven dependency management which is the best part i have seen. Following are the core features of the api.

Core Features

Simple and thread-safe API – write only few lines of code and start capturing images.
Work standalone – no additional software has to be installed to use it.
System independent – it will run without problems on most widely used operating systems – Windows (2k/XP/Vista/7, both 32- and 64-bit), Linux (x86, x64 and 32-bit ARM) and Mac OS X.
Built-in video driver – default built-in video grabber is provided, so you don’t need to install any additional software (such as JMF, etc).
Implementation independent – write your code once and don’t care which capture framework you will be using in future (LTI-CIVIL, JMF, QTJ, etc).
Automated resources management – you do not have to remember to deallocate resources used by your capturing device, library will always do that for you (while VM has been closed gracefully).
Motion detector – build in motion detector makes it easy to implement motion detecting features.
Available in Maven Central – it is available in Maven Central so your project can be deployed there too.
Re-streamer – simple JPEG/MJPEG re-streamer is build in, just run it and enjoy hosting your live stream.
Swing ready – contains Swing component to display images, together with painter API and thread-safe API which prevents Swing EDT from blocking issues when using camera.

How To Start

Webcam Capture is avilable in Maven Central, so if you can add its dependency to your project if you are using one of the dependency manager like Maven add the following code to your pom.xml file.

    <dependency>
      <groupId>com.github.sarxos</groupId>
      <artifactId>webcam-capture</artifactId>
      <version>0.3.7</version>
    </dependency>

here is the code for “MotionDetection” using Webcam Capture API

package com.spark.webcam;

import java.io.IOException;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamMotionEvent;
import com.github.sarxos.webcam.WebcamMotionListener;


/**
 * Detect motion.
 * 
 * @author Mantha Pavan Kumar
 */
public class DetectMotionExample implements WebcamMotionListener {

	public DetectMotionExample() {
		WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
		detector.setInterval(100); // one check per 100 ms
		detector.addMotionListener(this);
		detector.start();
	}

	@Override
	public void motionDetected(WebcamMotionEvent wme) {
		System.out.println("Detected motion I, alarm turn on you have");
	}

	public static void main(String[] args) throws IOException {
		new DetectMotionExample();
		System.in.read(); // keep program open
	}
}

and for further details please visit: http://webcam-capture.sarxos.pl/ and follow the site.
Happy Coding 🙂

Advertisements

Spring Integration with JPA/Hibernate using maven – I

Hi all here is my post regarding integration of some of the best frameworks available in the market, Spring+JPA/Hibernate.
Spring’s Basic concept: Inversion of Control

The basic concept of spring is the Inversion of Control pattern (dependency injection). In Spring, programmers don’t need to create user objects but they need to describe how they should be created (in applicationContext.xml or using annotations). Programmers need not directly connect components and services together in code but describe which services are needed by which components in a configuration file or using annotations. The spring container is responsible for all this. Spring creates all the objects, connects them together by setting the necessary properties, and determines when methods will be invoked.
So using Spring framework the integration between technologies become loosely coupled.

Requirements:
Spring 3.1
JPA2.x/Hibernate 3.x
Eclipse 4.2 with Maven
Mysql Database

The major parts of the Credentials application explained below are:

The Entity classes
The DAO class which will contain common db operation code and functions
The service class – which is the actual business class.. This will contain actual business logic in it. In our example, we save Credentials bean information using this class.
Explained in the next tutorial
The client – The client can be a jsp / jsf web components or it can be a simple java program, which gets the service bean from spring and calls business method.
The spring’s applicationContext.xml descriptor which specifies what are the objects to be created when starting the application and where they should be injected.

Let’s go through the tutorial step by step.You can download the full project code at the end of the tutorial:
i explain how to Retrieve and Insert and leave Delete and Update to be coded yourself(for fun).

Step1:create a maven project in eclipse.
step2:update the pom.xml file as shown below.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.spring</groupId>
	<artifactId>SpringIntegration</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringIntegration</name>
	<description>SpringIntegration</description>

	<properties>
		<org.slf4j-version>1.6.1</org.slf4j-version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.18</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-crypto</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.10</version>
		</dependency>


		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Hibernate Validator -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.CR1</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.4.0.GA</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.0-beta-1</version>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>7.4.0.v20110414</version>
				<configuration></configuration>
			</plugin>
		</plugins>
		<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings 
					only. It has no influence on the Maven build itself. -->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>
											org.apache.maven.plugins
										</groupId>
										<artifactId>
											maven-compiler-plugin
										</artifactId>
										<versionRange>
											[2.3.2,)
										</versionRange>
										<goals>
											<goal>compile</goal>
											<goal>testCompile</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore></ignore>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<!-- needed for XmlSchema -->
	<repositories>
		<repository>
			<id>ibiblio</id>
			<name>ibiblio maven repository</name>
			<url>http://ibiblio.org/maven/</url>
			<layout>legacy</layout>
		</repository>
		<repository>
			<id>apache</id>
			<name>Apache maven repository</name>
			<url>http://www.apache.org/dist/java-repository/</url>
			<layout>legacy</layout>
		</repository>
	</repositories>

</project>

Step3:put web.xml in src/main/webapp/WEB-INF/ as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">

	<!-- Defines all the spring context information for all servlets and Filters 
		that share the info -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:application-context.xml</param-value>
	</context-param>

	<!-- creates spring container listener shared by all servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- request processing servlet -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>pages/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

put all the configuration files in the src/main/resources folder of your maven project.

Step4: lets code our first configuration file “application-context.xml” as shown below.

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- component scan for @component,@Repositry,@Service -->
	<context:component-scan base-package="com.spark" />
	
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://localhost:3306/test" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<!-- JPA EntityManagerFactory -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
		p:dataSource-ref="dataSource">
		<property name="persistenceUnitName" value="MyPersistenceUnit"/> 
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="database" value="MYSQL" />
				<property name="showSql" value="true" />
			</bean>
		</property>
	</bean>

	<!-- Transaction manager for a single JPA EntityManagerFactory (alternative 
		to JTA) -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
		p:entityManagerFactory-ref="entityManagerFactory" />

	<!-- Activates various annotations to be detected in bean classes for eg 
		@Autowired -->
	<context:annotation-config />

	<!-- enable the configuration of transactional behavior based on annotations -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

	<!-- Property Configurator -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>

</beans>

Step5:lets code our second configuration file “spring-context.xml” which internally imports one more configuration file “controllers.xml”, this spring-context.xml file goes as a parameter for DispatcherServlet class of Spring framework.

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

	<!-- Enables the Spring MVC @Controller programming Model -->
	<annotation-driven />

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/" />
		<beans:property name="suffix" value=".html" />
	</beans:bean>

	<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />

</beans:beans>

Step6: controllers.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- Activates various annotations to be detected in bean classes -->	
	<context:annotation-config />
	<context:spring-configured />
	<!-- enable the configuration of transactional behavior based on annotations -->
	<tx:annotation-driven/>

	<!-- Scans within the base package of the application for @Components to configure as beans -->
	<context:component-scan base-package="com.spark" />
	
	
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="10000000" />
	</bean>
	
	
</beans>

Step7: Lets put the log4j.properties


log4j.rootCategory=debug, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=C://templog/clinicComponet.log
log4j.appender.logfile.MaxFileSize=1MB

# Keep three backup files
log4j.appender.logfile.MaxBackupIndex=3
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

#Pattern to output : date priority [category] - <message>line_separator
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - <%m>%n

So now we have finished coding our configuration just start with our logic
create the followiing packages in src/main/java folder of maven project as follows.

com.spark.controller
com.spark.dao
com.spark.service
com.spark.model

Lets start coding Java now. first step is coding our model class(POJO) as below.

/**
 * 
 */
package com.spark.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 * @author Sony
 * 
 */

@Entity
@Table(name = "credentials")
@NamedQueries({
@NamedQuery(name="Credentials.getAllRecords",
    query="SELECT o FROM Credentials o")          
})
public class Credentials implements Serializable{

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "ID")
	private int id;

	@Column(name = "username")
	private String username;

	@Column(name = "password")
	private String password;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

once our pojo is ready lets decide the business logic that is our service class. we will code an interface and its implementation class as follows

/**
 * 
 */
package com.spark.service;

import java.util.List;

import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
public interface CredentialsService {

    void save(Credentials credentials);
    Credentials findById(Long id);       
    List<Credentials> findAll();   
}

and following is the implementation class

/**
 * 
 */
package com.spark.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.spark.dao.CredentialsDao;
import com.spark.dao.CredentialsDaoImpl;
import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
@Service("credentialService")
public class CredentialsServiceImpl implements CredentialsService {

	@Autowired
	CredentialsDao credentialsDao;
	
	public CredentialsDao getCredentialsDao() {
		return credentialsDao;
	}

	public void setCredentialsDao(CredentialsDao credentialsDao) {
		this.credentialsDao = credentialsDao;
	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#save(com.spark.model.Credentials)
	 */
	@Override
	public void save(Credentials credentials) {
		// TODO Auto-generated method stub
		credentialsDao.save(credentials);

	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#findById(java.lang.Long)
	 */
	@Override
	public Credentials findById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#findAll()
	 */
	@Override
	public List<Credentials> findAll() {
		// TODO Auto-generated method stub
		return credentialsDao.findAll();
	}

}

Now its time to code our core database logic. The database logic is handled by JPA EntityManager, the object is injected into the EntityManager using the @PersistenceContext annotation its the responsibility of the Spring container to inject the EntityManager Implementation object after it scans the annotation. We will code the dao layer same as we did with service layer with an interface and its implementation class. please note that the dao is annotated as @Transactional that means the database operations will be executed under a transactional context
when spring scans the annotation.

/**
 * 
 */
package com.spark.dao;

import java.util.List;

import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
public interface CredentialsDao {

    public List<Credentials> findAll();
    public void save(Credentials credentials);
    public Credentials findById(int id);

}

following is the implementation class for the interface.

/**
 * 
 */
package com.spark.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
@Transactional
@Component
public class CredentialsDaoImpl implements CredentialsDao {
	
	@PersistenceContext
	private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#findAll()
	 */
	@Override
	public List<Credentials> findAll() {
		// TODO Auto-generated method stub
		List<Credentials> credentials = null;
		try {
			credentials = entityManager.createNamedQuery("Credentials.getAllRecords").getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return credentials;
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#save(com.spark.model.Credentials)
	 */
	@Override
	public void save(Credentials credentials) {
		// TODO Auto-generated method stub
		try {
			
			entityManager.persist(credentials);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#findById(int)
	 */
	@Override
	public Credentials findById(int id) {
		// TODO Auto-generated method stub
		return null;
	}

}

Now its time to code controller which is responsible for deligating the requests to service layer and there to dao layer. In the retrieve method the response returned from the method will be a JSON String

/**
 * 
 */
package com.spark.controller;

import java.util.List;

import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.beans.factory.annotation.Autowired;
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.spark.model.Credentials;
import com.spark.service.CredentialsService;

/**
 * @author Sony
 *
 */
@Controller
public class SpringController {

	@Autowired(required=true)
	CredentialsService credentialsService;
	
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public @ResponseBody String handleInsertRequest(@Valid String username,@Valid String password){
		
		String returnStatus = "Details Saved Successfully";
				
		Credentials credentials = new Credentials();
		credentials.setUsername(username);
		credentials.setPassword(password);
		
		credentialsService.save(credentials);
		
		return returnStatus;
	}
	
	@RequestMapping(value="/retrieve",method=RequestMethod.POST)
	public @ResponseBody String handleRetrieveRequest(){
				
		List<Credentials> credentials = credentialsService.findAll();
		
		JSONObject responseDetailsJson = new JSONObject();
	    JSONArray jsonArray = new JSONArray();

	    for (int i = 0; i < credentials.size(); i++)
	    {
	      JSONObject formDetailsJson = new JSONObject();
	      formDetailsJson.put("username", credentials.get(i).getUsername());
	      formDetailsJson.put("password", credentials.get(i).getPassword());

	      jsonArray.add(formDetailsJson);
	    }
	    responseDetailsJson.put("credentials", jsonArray);
	    
	    return responseDetailsJson.toString();
		
	}
}

I will post the the UI related stuff(JSP) in the next tutorial to call the controller.

Happy Coding 🙂

Android Rest Client to call Spring MVC Project – Part 2

Hi all in the previous post i have shown you how to create a mavenized Spring MVC Project with full configuration in that the Spring controller is returning a JSON String, now this is the string we want to collect in android client by calling it using Spring-Rest-Template.

The Jar files required for this application are
android-support-v4.jar
spring-android-auth-1.0.0.RELEASE.jar
spring-android-core-1.0.0.RELEASE.jar
spring-android-rest-template-1.0.0.RELEASE.jar

For JSON Support add the following jar files
jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

commons-httpclient-3.1.jar is used to HttpHeader Support.

package com.example.springandroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class MainActivity extends ListActivity {

	private static String[] content = { "JavaSE", "JavaEE", "JavaME" };

	public static final int ADD_MENU = Menu.FIRST + 1;
	public static final int REFRESH_MENU = Menu.FIRST + 2;
	public static final int EDIT_MENU = Menu.FIRST + 3;
	public static final int REMOVE_MENU = Menu.FIRST + 4;

	private ArrayList<String> arrayList = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getUpdates.start();

		registerForContextMenu(getListView());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(Menu.NONE, ADD_MENU, Menu.NONE, "Add Content");
		menu.add(Menu.NONE, REFRESH_MENU, Menu.NONE, "Refresh Content");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, EDIT_MENU, Menu.NONE, "Edit Content");
		menu.add(Menu.NONE, REMOVE_MENU, Menu.NONE, "Remove Content");
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ADD_MENU:
			addContent();
			return true;

		case REFRESH_MENU:
			initAdapter();
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();

		@SuppressWarnings("rawtypes")
		ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
		switch (item.getItemId()) {
		case EDIT_MENU:
			final String item1 = arrayList.get(info.position);
			// item1 = item1.toUpperCase();
			final View addView = getLayoutInflater().inflate(
					R.layout.activity_main, null);
			final EditText name = (EditText) addView.findViewById(R.id.title);
			new AlertDialog.Builder(this)
					.setTitle("Add Content")
					.setView(addView)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								@SuppressWarnings("unchecked")
								public void onClick(DialogInterface dialog,
										int whichButton) {
									@SuppressWarnings("rawtypes")
									ArrayAdapter adapter = (ArrayAdapter) getListAdapter();

									name.setText(item1);
									adapter.insert(name.getText().toString(),
											info.position);
								}
							}).setNegativeButton("Discard", null).show();
			adapter.remove(arrayList.get(info.position));

			return (true);
		case REMOVE_MENU:
			adapter.remove(arrayList.get(info.position));
			return (true);
		}
		return super.onContextItemSelected(item);
	}

	private Thread getUpdates = new Thread() {
		public void run() {

			String url = "http://10.40.230.54:8080/AndroidSpring/spring/retrieve";

			HttpHeaders requestHeaders = new HttpHeaders();
			requestHeaders.setContentType(new MediaType("text", "xml"));

			HttpEntity<String> requestEntity = new HttpEntity<String>(
					requestHeaders);

			RestTemplate restTemplate = new RestTemplate();
			restTemplate.getMessageConverters().add(
					new StringHttpMessageConverter());
			ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class);
			final String result = responseEntity.getBody();
			Log.d("Message", result); // prints the response collected from the server

			
			try {
				
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						JSONObject jsonObject;
						try {
							jsonObject = new JSONObject(result);
							Log.d("JSON is", ""+jsonObject.toString());
							
							initAdapter();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
					}
				});

				
			} catch (Exception e) {
			}
		}
	};

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void initAdapter() {
		arrayList = new ArrayList<String>();
		Log.d("String Array Length:", "" + content.length);
		for (String contents : content) {
			arrayList.add(contents);
		}
		setListAdapter(new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, arrayList));
	}

	private void addContent() {
		final View addView = getLayoutInflater().inflate(
				R.layout.activity_main, null);
		new AlertDialog.Builder(this).setTitle("Add Content").setView(addView)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@SuppressWarnings({ "rawtypes", "unchecked" })
					public void onClick(DialogInterface dialog, int whichButton) {
						ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
						EditText name = (EditText) addView
								.findViewById(R.id.title);
						adapter.add(name.getText().toString());
						
					}
				}).setNegativeButton("Discard", null).show();
	}
	
	
}

if you want to send parameters to Spring app. Please code the controller relavently i am giving the android call to Spring controller

private Thread addToDataBase = new Thread(){
		public void run(){
			String url = "http://10.40.230.54:8080/AndroidSpring/spring/insert?username={username}&password={password}";

			HttpHeaders requestHeaders = new HttpHeaders();
			requestHeaders.setContentType(new MediaType("text", "xml"));

			HttpEntity<String> requestEntity = new HttpEntity<String>(
					requestHeaders);

			RestTemplate restTemplate = new RestTemplate();
			restTemplate.getMessageConverters().add(
					new StringHttpMessageConverter());
			/*ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class);*/
			Map<String, Object> uriVariables = new HashMap<String, Object>();
		    uriVariables.put("username", "Administrator");
		    uriVariables.put("password", "Administrator123");

		    ResponseEntity<String> responseEntity = restTemplate.exchange(url,
					HttpMethod.POST, requestEntity, String.class,uriVariables);
			Log.d("Message", responseEntity.getBody());
		}
	};

Happy Coding 🙂

Android Rest Client to call Spring MVC Project – Part 1

Hi All, This time i had very tough time to show my proof of concept to one of my colleague regarding java Spring mvc and Android. the requirement is quite direct we have to create a Spring MVC project and deploy it to server and call the spring controller using Android Activity. Thanks to spring it has released Spring-rest-template api using which we can call the business logic that is deployed in the server as spring controller. so here is my example code to you how to call spring mvc using Android Rest Client

in this part i will be explaining u how to create a spring mvc project using maven dependencies.

Note: dont code network related logic in the main thread of android activity it will lead to android.os.NetworkOnMainThreadException

Create a mavenized Spring Project as below:
Step1: POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.android.spring</groupId>
	<artifactId>AndroidSpring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>AndroidSpring</name>
	<description>AndroidSpring</description>

	<properties>
		<org.slf4j-version>1.6.1</org.slf4j-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.18</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-crypto</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.10</version>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Hibernate Validator -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.CR1</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.4.0.GA</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.0-beta-1</version>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>7.4.0.v20110414</version>
				<configuration></configuration>
			</plugin>
		</plugins>
		<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>
											org.apache.maven.plugins
										</groupId>
										<artifactId>
											maven-compiler-plugin
										</artifactId>
										<versionRange>
											[2.3.2,)
										</versionRange>
										<goals>
											<goal>compile</goal>
											<goal>testCompile</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore></ignore>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<!-- needed for XmlSchema -->
	<repositories>
		<repository>
			<id>ibiblio</id>
			<name>ibiblio maven repository</name>
			<url>http://ibiblio.org/maven/</url>
			<layout>legacy</layout>
		</repository>
		<repository>
			<id>apache</id>
			<name>Apache maven repository</name>
			<url>http://www.apache.org/dist/java-repository/</url>
			<layout>legacy</layout>
		</repository>
	</repositories>

</project>

Step2:Place all configuration files in src/main/resources of ur maven project
code for application-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
			http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

	<!-- component scan for detecting @controller annotations -->
	<context:component-scan base-package="com.spark.android"></context:component-scan>
	
	<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
	<task:executor id="myExecutor" pool-size="5"/>
	<task:scheduler id="myScheduler" pool-size="10"/>
	
	<tx:annotation-driven/>
	
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="MyPersistenceUnit" />
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="showSql" value="true" />
				<property name="generateDdl" value="false" />
				<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
			</bean>
		</property>
	</bean>
	
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://localhost:3306/android" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
</beans>

code for controllers.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- Activates various annotations to be detected in bean classes -->	
	<context:annotation-config></context:annotation-config>

	<!-- Scans within the base package of the application for @Components to configure as beans -->
	<context:component-scan base-package="com.spark.android" />
	
	
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="10000000" />
	</bean>
	
	
</beans>

code for spring-context.xml

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

	<!-- Enables the Spring MVC @Controller programming Model -->
	<annotation-driven />

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/" />
		<beans:property name="suffix" value=".html" />
	</beans:bean>

	<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />

</beans:beans>

For database interaction i decided to make use of JPA over Hibernate, so create a folder META-INF(All caps) in your src/main/resources/ and pleace persistence.xml file in it with the following code.

persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
	version="2.0">
	
	<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
	<class>com.spark.android.model.Credentials</class>
	</persistence-unit>
	
</persistence>

now that we have completed our configuration its time for us to write the model classes and business logic for handling requests from android client and return responce. Here we use JSON for communication layer. notice that you put the code in appropriate packages.
source code for controller

/**
 * 
 */
package com.spark.android.controller;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.android.model.Credentials;

/**
 * @author Mantha Pavan Kumar
 *
 */
@Controller
public class AndroidSpringController {

	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public @ResponseBody String handleInsertRequest(){
		
		Credentials credentials = new Credentials();
		credentials.setUsername("PavanKumar");
		credentials.setPassword("pavan~123!");
		
		JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( credentials );  
		
		return jsonObject.toString();
	}
}

and following is the model class(POJO)

/**
 * 
 */
package com.spark.android.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author Mantha Pavan Kumar
 *
 */
@Entity
@Table(name="contacts")
public class Credentials implements Serializable{

	private int id;
	private String username;
	private String password;
	
	/**
	 * @return
	 */
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getId() {
		return id;
	}
	/**
	 * @param id
	 */
	public void setId(int id) {
		this.id = id;
	}
	/**
	 * @return
	 */
	@Column(name="username")
	public String getUsername() {
		return username;
	}
	/**
	 * @param username
	 */
	public void setUsername(String username) {
		this.username = username;
	}
	/**
	 * @return
	 */
	@Column(name="password")
	public String getPassword() {
		return password;
	}
	/**
	 * @param password
	 */
	public void setPassword(String password) {
		this.password = password;
	}
}

once this is ready now lets start coding your web.xml file as our project is a web application. create a folder WEB-INF(all caps) in src/main/webapps/

code for web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">

	<!-- Defines all the spring context information for all servlets and Filters 
		that share the info -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:application-context.xml</param-value>
	</context-param>

	<!-- creates spring container listener shared by all servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- request processing servlet -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>pages/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

now its time to test the application open cmd and navigate to the project folder and issue “mvn clean install package”
without quotes it will download all jar files needed by your application and it builds the war file(bueauty of maven)
now your project is ready for deployment issue the command “mvn tomcat:run” without quotes your tomcats starts and your war will be deployed now your Spring MVC project is up and running lets see how to code Android REST client and communicate with Spring Web App in Part-II.

Happy Coding 🙂

What is Slick2D ?

Hi All if you are interested in game development in java then your wait come to an end with slick2d

Slick2D is an easy to use set of tools and utilites wrapped around LWJGL(Light Weight Java Game Library) OpenGL bindings to make 2D Java game development easier.

Slick2D includes support for images, animations, particles, sounds, music and much much more. Additionally there are many community based projects that add additional functionality such as entitiy support, themable widgets and box2d wrappers.

With an active forum and new features in development Slick2D is a great choice for your Java 2d game.

for further details read about slick2D @ “http://www.slick2d.org/&#8221;

in my further posts ill be posting some kind of graphics and game techniques using Slick2D and LWJGL stay in touch..

Happy Coding 🙂

Calling a remote Servlet using Android Activity.

Hi all, in the past i received some queries regarding “how to call EJB from Android?”, at that time i am not sure but i just replied by saying call a servlet from your Android and its the servlet that internally calls EJB, Yes its true there is no direct implementation to call EJB from Android but we can call a servlet from Android and from there its your logic to call any business components like EJB,etc. following is my tutorial which will take you how to call Servlet from Android
Note:This tutorial will create Servlets with specification 3.0 with no web.xml and uses annotations to map the requests from client.

1.Create a dynamic web project with servlet specification 3.0 and create a servlet in src folder of your project as shown below.
2.Deploy the servlet in local server(Apache-tomcat 7.x) and test the working by hitting the below url http://localhost:8080/AndroidServlet/androidServlet

package com.spark.android.servlets;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class AndroidServlet
 * @author Mantha Pavan Kumar
 */
@WebServlet("/androidServlet")
public class AndroidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AndroidServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter printWriter = response.getWriter();
		printWriter.println("Sample Page !");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Now its time to create android project(using Eclipse), Assuming all the prerequisites of android are already installed in your environment lets start the project.

3.create Android Application project
4.In the main.xml file add the below content

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/button" />

    <TextView
        android:id="@+id/outputTxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#CC0033"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

5. in res/values/strings.xml add the below content

<resources>

    <string name="app_name">SimpleHttpGetServlet</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
	<string name="button">Invoke Servlet</string>
</resources>

6.Now in the MainActivity.java place the below content

package com.example.simplehttpgetservlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
    Button button;
    TextView outputText;
 
    public static final String URL = "http://10.40.230.98:8080/AndroidServlet/androidServlet";
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        findViewsById();
 
        button.setOnClickListener(this);
    }
 
    private void findViewsById() {
        button = (Button) findViewById(R.id.button);
        outputText = (TextView) findViewById(R.id.outputTxt);
    }
 
    public void onClick(View view) {
        GetXMLTask task = new GetXMLTask();
        task.execute(new String[] { URL });
    }
 
    private class GetXMLTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String output = null;
            for (String url : urls) {
                output = getOutputFromUrl(url);
            }
            return output;
        }
 
        private String getOutputFromUrl(String url) {
            String output = null;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
 
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                output = EntityUtils.toString(httpEntity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return output;
        }
 
        @Override
        protected void onPostExecute(String output) {
            outputText.setText(output);
        }
    }
}

7.Finally we give persmissions to our android app to access internet in the AndroidManifest.xml as below.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.simplehttpgetservlet"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thats it launch your AVD by running the Android project and click the button, you will see the response from servlet.
Happy coding 🙂

Creating JavaWebService and JavaClient using Apache Axis2

Hi all, I have got lots of requests to demonstrate creation of webservices using java and Apache Axis2 api so here i go.

1. Setup the Development Environment

1.1. First you need to set up the development environment. Following things are needed if you want to create Web Services using Axis2 and Eclipse IDE(Juno 4.2).

Some Eclipse versions have compatibility issues with Axis2. This tutorial is tested with Apache Axis2 1.5.2, Eclipse Helios and Apache Tomcat 6.

1) Apache Axis2 Binary Distribution – Download
2) Apache Axis2 WAR Distribution – Download
3) Apache Tomcat – Download
4) Eclipse IDE(Juno 4.2) – Download
5) Java installed in your Computer – Download

Then click on the Web Service –-> Axis2 Preferences and browse the top level directory of Apache Axis2 Binary Distribution.
2. Creating the Web Service Using Bottom-Up Approach

2.1 First create a new Dynamic Web Project (File –> New –-> Other…) and choose Web –> Dynamic Web Project.
2.2 Set Apache Tomcat as the Target Runtime and click Modify to install Axis2 Web Services project facet.
2.3 Select Axis2 Web Services
2.4 Click OK and then Next. There you can choose folders and click Finish when you are done

3. Create Web Service Class

/**
 *
 */
package com.spark.webservice;

/**
 * @author Mantha Pavan Kumar
 *
 */
public class JavaWebService {

	/**
	 * @param firstnumber
	 * @param secondNumber
	 * @return
	 */
	public int addNumbers(int firstnumber,int secondNumber){

		return firstnumber+secondNumber;
	}
}

Then, select File –> New –-> Other and choose Web Service.
Click Next and make sure Generate a default service.xml file is selected.
You can go to http://localhost:8080/JavaWebService/services/listServices to see your running service which is deployed by Axis2. You can see the WSDL by clicking the link JavaWebService.

Creating a Web service client
Select File –> New –> Other… and choose Web Service Client
Set he newly created Axis2 Web service (http://localhost:8080/JavaWebService/services/listServices) as the Service definition. Then configure the Server runtime as previously and click finish.

This will generate two new classes called JavaWebServiceStub.java and JavaWebServiceCallbackHandler.java. Now we can create test class for client and use our web service. Create new class called ServiceTest.java and paste following code.

/**
 *
 */
package com.spark.webservice;

import java.rmi.RemoteException;

import org.apache.axis2.AxisFault;

import com.spark.webservice.JavaWebServiceStub.AddNumbers;
import com.spark.webservice.JavaWebServiceStub.AddNumbersResponse;

/**
 * @author Mantha Pavan Kumar
 *
 */
public class ServiceTest {

	/**
	 * @param args
	 * @throws RemoteException
	 */
	public static void main(String[] args) throws RemoteException {
		// TODO Auto-generated method stub

		JavaWebServiceStub serviceStub = new JavaWebServiceStub();
		AddNumbers addNumbers = new AddNumbers();
		addNumbers.setFirstnumber(10);
		addNumbers.setSecondNumber(20);

		AddNumbersResponse addNumbersResponse = serviceStub.addNumbers(addNumbers);
		System.out.println( addNumbersResponse.get_return());

	}

}

Now you can run the above code as java application and you will get the output
follow these screen shots for creation of webservices Creation of Java WebService
Happy Coding 🙂