Archive

Archive for the ‘Spring’ Category

jQuery Autocomplete example with Spring MVC

First create Spring REST controller to process the request.


@RestController
@RequestMapping(value = "/json")
public class RESTController
{

@ResponseBody
@RequestMapping(value = "/city", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<List<SearchBean>> getStateList( @RequestParam("term") String term, Locale locale )
{

Response<List<SearchBean>> returnResponse = null;
List<City> cityList = null;
List<SearchBean> suggestCityList = null;
String cityName = "";
SearchBean searchBean = null;
try
{
cityList = new ArrayList<City>();
suggestCityList = new ArrayList<SearchBean>();
cityList = Data.getCityList( locale );  // load city Objects list

for ( City city : cityList )
{
cityName = city.getName();
if ( ( cityName.toLowerCase( locale ).startsWith( term.toLowerCase( locale ) )   )
{
searchBean = new SearchBean();
searchBean.setLabel( cityName );
suggestCityList.add( searchBean );
}
}
returnResponse = new Response<>( suggestCityList, "", Response.SUCCESS );
}
catch ( CustomGenericException e )
{
// TODO: handle exception

returnResponse = new Response<>( null, "", Response.ERROR );
}
return returnResponse;

}

}

SearchBean class is just a pojo class with two parameters.

now , initialize the autocomplete function.


function loadSmartkeySuggestion(element,_url,minLength,dataType){$(element).autocomplete({

source: function( request, response ) {
$.ajax({
url:_url ,
dataType: dataType,
data: {
term: request.term
},
success: function( data ) {
if(data.status == 1) // if data is available
response( data.data );
}
});
},
minLength: minLength

});}

Advertisements
Categories: jQuery, Spring Tags:

Spring Security : Basic Http Authentication

Suppose we need to create an API which requires user authentication to access that. Spring security is there to implement this on the fly.

First create your REST service

Service.java


@RestController
@RequestMapping("/api")
public class Service
{
private static final Logger LOGGER = LoggerFactory.getLogger( Service.class );

/**
* Clear the template cache
*
* @return response object with status and message
*/
@ResponseBody
@RequestMapping(value = "/foo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<String> accessApi()
{
Response<String> returnResponse = null;
try
{

returnResponse = new Response<String>( "", "Successfull", Response.SUCCESS );
}
catch ( Exception )
{
// TODO: handle exception
returnResponse = new Response<String>( "", "Error", Response.ERROR );
LOGGER.error( ex.getMessage() );
}

return returnResponse;
}

}

Now create security config class.


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

@Autowired
MyBasicAuthenticationEntryPoint myBasicAuthenticationEntryPoint;

@Autowired
public void configureGlobal( AuthenticationManagerBuilder auth ) throws Exception
{
auth.inMemoryAuthentication().withUser( "user" ) // #1
.password( "password" ).roles( "USER" );
}

@Override
protected void configure( HttpSecurity http ) throws Exception
{
// @formatter:off
http
.authorizeRequests()
.antMatchers("/api/foo").hasRole("USER")
.anyRequest().permitAll()
.and()
.httpBasic()
.authenticationEntryPoint( myBasicAuthenticationEntryPoint );
// @formatter:on
}

}

Now add bean to MvcConfig class.


@Bean
public MyBasicAuthenticationEntryPoint myBasicAuthenticationEntryPoint()
{
return new MyBasicAuthenticationEntryPoint();
}

Then add SecurityConfig class to WebAppInitializer.


public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses()
{
return new Class<?>[] {SecurityConfig.class };
}

}

Then add


public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer
{

}

Now create entry point.


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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint
{

@Override
public void commence( final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException ) throws IOException, ServletException
{
response.setHeader( "Access-Control-Allow-Origin", "*" );
response.setHeader( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE" );
response.setHeader( "Access-Control-Max-Age", "3600" );
response.setHeader( "Access-Control-Allow-Headers", "x-requested-with" );

response.addHeader( "WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"" );
response.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
final PrintWriter writer = response.getWriter();
writer.println( "HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage() );
}

@Override
public void afterPropertiesSet() throws Exception
{
setRealmName( "FooService" );
super.afterPropertiesSet();
}
}

Now redirect to http:localhost/example/api/foo URL will request your credentials.

Spring Core Basics – Part 1

spring-2

First go to command line and create a simple project with maven.

mvn archetype:generate -DgroupId=com.supun.common -DartifactId=SpringExamples 
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

This post has the setting up instruction of maven. Now edit the pom.xml file as follows.


<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.supun.common</groupId>
 <artifactId>SpringExamples</artifactId>
 <version>1.0-SNAPSHOT</version>
 <packaging>jar</packaging>

<name>SpringExamples</name>
 <url>http://maven.apache.org</url>

<properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>

<dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>4.0.5.RELEASE</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
 <version>4.0.5.RELEASE</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>4.0.5.RELEASE</version>
 </dependency>
 </dependencies>
</project>


Now import this project to your Eclipse workspace. It will automatically download the dependencies.

Then create a Beans.xml file inside the src/main/java folder as follows.


<?xml version="1.0" encoding="UTF-8"?>

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

<bean id="helloWorld" class="com.supun.common.HelloWorld" >
 <property name="message" value="Hello Spring"/>
 </bean>
</beans>

Now create HelloWorld.java class.


package com.supun.common;

public class HelloWorld {

private String message;

public void getMessage(){
 System.out.println("Your Message : " + message);
 }


public void setMessage(String message) {
 this.message = message;
 }
}


Now change the App.java class as follows.


package com.supun.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
 public static void main(String[] args) {
 ApplicationContext context = 
 new ClassPathXmlApplicationContext("Beans.xml");

HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

obj.getMessage();
 }
}

Now run the App.java class. The output is : Your Message : Hello Spring

In this example the spring configuration are added from the xml file.

This is how the spring framework is working.

spring_ioc_container

The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.These objects are called Spring Beans

In above example, the HelloWorld.java class is a POJO class. The metadata is taken from the Beans.xml.This metadata can be stored in the java file too.

Spring Bean Definition 

The objects that form the backbone of your application and that are managed by the Spring IoC      container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions which you have already seen.

The bean definition contains the information called configuration metadata which is needed for the container to know the followings:

  • How to create a bean
  • Bean’s lifecycle details
  • Bean’s dependencies

All the above configuration metadata translates into a set of the following properties that make up each bean definition.

Properties Description
class This attribute is mandatory and specify the bean class to be used to create the bean.
name This attribute specifies the bean identifier uniquely. In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s).
scope This attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter.
constructor-arg
properties
autowiring mode
lazy-initialization mode A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.
initialization method A callback to be called just after all necessary properties on the bean have been set by the container. It will be discussed in bean life cycle chapter.
destruction method A callback to be used when the container containing the bean is destroyed. It will be discussed in bean life cycle chapter.

Spring IoC container is totally decoupled from the format in which this configuration metadata is actually written. There are following three important methods to provide configuration metadata to the Spring Container:

  1. XML based configuration file.

<?xml version="1.0" encoding="UTF-8"?>

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

<!-- A simple bean definition -->
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with lazy init set on -->
<bean id="..." class="..." lazy-init="true">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with initialization method -->
<bean id="..." class="..." init-method="...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with destruction method -->
<bean id="..." class="..." destroy-method="...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- more bean definitions go here -->

</beans>

2.Annotation-based configuration.

Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

3.Java Based configuration.

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The simplest possible @Configuration class would be as follows:

 

Categories: AOP, DI, Maven, Spring

Spring Fundamentals – A quick walkthrough

spring-egitimi

Spring behaves as a factory of beans, in other words it act as a bean container. Sp pretty much any POJOs we are creating can be contained in the Spring Container. Inside this container, there can be number of objects contained. The container deals with this objects and take care about object instantiate, manage object life cycle and the destruction of the objects.

To manage the object life cycle inside the Spring container, the container should handle the objects. It is done via the creation of the objects which is done through the container.

Spring-Container

Imagine a scenario where we need to create objects out of the spring container. This can be done using “New” keyword outside the container. But the Spring approach is much different. The container will create the objects inside it and pass to the outer objects. It is more like factory pattern. The container acts as a factory and uses some configuration files to do the task.

factrypttrn

Just like this factory pattern the Spring Bean Factory do the object creation.

sprngbeanfactry

The XML file has the bean configuration. According to that configuration, Spring Container  create new Spring Beans and hands over them to the outer object. So the object life cycle is totally handled by the Spring Bean Container. 

Categories: Spring

Understanding Dependency Injection (DI)

spring_triangle

Suppose we have an application to do the drawings of different shapes. The following would be the traditional way of implementing it.

di_1

But in this case we have to instantiate Triangle or a Circle when we need to access the draw method. Then there is an another approach to solve this problem using an Interface or an abstract class. Following is the sample code.

package com.technodyne.common;

public abstract class Shape {

public abstract void draw();
}

Now add the following classes extending the Shape abstract class. 

package com.technodyne.common;

public class Circle extends Shape {

@Override
 public void draw() {
 // TODO Auto-generated method stub

 }

}

and


package com.technodyne.common;

public class Triangle extends Shape {

@Override
 public void draw() {
 // TODO Auto-generated method stub

 }

}

And here is the implementation class for the application.


package com.technodyne.common;

public class DiApplication {

public void drawAction(){

Shape shapeTriangle = new Triangle();
 shapeTriangle.draw();

Shape shapeCircle = new Circle();
 shapeCircle.draw();
 }
 }

But still we should do the instantiate of the Circle and Triangle objects. Therefore as a quick alternative, we can add the following method to do our task. This method doesn’t involve in any object creation. It just execute the draw method of the object which is passed to the method.


public void myDrawMethod(Shape shape){
 shape.draw();
 }

Inside this method we have removed the dependency of Circle or Triangle  objects. But still we need to pass the object to the method. Which means that somewhere in this code snippets, we have to do the instantiate. So the proper approach would be removing object creation from the class.

For that, a separate class can be used to execute the draw method.


package com.technodyne.common;

public class Drawing {

private Shape shape;

/**
 * @param shape the shape to set
 */
 public void setShape(Shape shape) {
 this.shape = shape;
 }

 public void drawShape(){
 this.shape.draw();
 }

}

This Drawing class doesn’t do the object creation. When we pass the triangle object to the Setter, it will execute the draw method inside the triangle class. this will allow to insert new objects to the Drawing class as long as that class is a type of Shape. The drawing class doesn’t own the relationship of Shape types.

Categories: AOP, Java, Spring

Fixing Error : SpringMVC apache tomcat catalina installtask not found

While working with SpringMVC, I recently found some issues which are raised when we try to build the application using apache ant. I am using apache tomcat as my servlet container. Here is the build.xml file that i am using.


<?xml version="1.0"?>

<project name="springapp" basedir="." default="usage">
 <property file="build.properties"/>

<property name="src.dir" value="src"/>
 <property name="web.dir" value="war"/>
 <property name="build.dir" value="${web.dir}/WEB-INF/classes"/>
 <property name="name" value="springapp"/>

<path id="master-classpath">
 <fileset dir="${web.dir}/WEB-INF/lib">
 <include name="*.jar"/>
 </fileset>
 <!-- We need the servlet API classes: -->
 <!-- * for Tomcat 5/6 use servlet-api.jar -->
 <!-- * for other app servers - check the docs -->
 <fileset dir="${appserver.lib}">
 <include name="servlet*.jar"/>
 </fileset>
 <pathelement path="${build.dir}"/>
 </path>

<target name="usage">
 <echo message=""/>
 <echo message="${name} build file"/>
 <echo message="-----------------------------------"/>
 <echo message=""/>
 <echo message="Available targets are:"/>
 <echo message=""/>
 <echo message="build --> Build the application"/>
 <echo message="deploy --> Deploy application as directory"/>
 <echo message="deploywar --> Deploy application as a WAR file"/>
 <echo message="install --> Install application in Tomcat"/>
 <echo message="reload --> Reload application in Tomcat"/>
 <echo message="start --> Start Tomcat application"/>
 <echo message="stop --> Stop Tomcat application"/>
 <echo message="list --> List Tomcat applications"/>
 <echo message=""/>
 </target>

<target name="build" description="Compile main source tree java files">
 <mkdir dir="${build.dir}"/>
 <javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"
 deprecation="false" optimize="false" failonerror="true">
 <src path="${src.dir}"/>
 <classpath refid="master-classpath"/>
 </javac>
 </target>

<target name="deploy" depends="build" description="Deploy application">
 <copy todir="${deploy.path}/${name}" preservelastmodified="true">
 <fileset dir="${web.dir}">
 <include name="**/*.*"/>
 </fileset>
 </copy>
 </target>

<target name="deploywar" depends="build" description="Deploy application as a WAR file">
 <war destfile="${name}.war"
 webxml="${web.dir}/WEB-INF/web.xml">
 <fileset dir="${web.dir}">
 <include name="**/*.*"/>
 </fileset>
 </war>
 <copy todir="${deploy.path}" preservelastmodified="true">
 <fileset dir=".">
 <include name="*.war"/>
 </fileset>
 </copy>
 </target>

<!-- ============================================================== -->
<!-- Tomcat tasks - remove these if you don't have Tomcat installed -->
<!-- ============================================================== -->

<path id="catalina-ant-classpath">
 <!-- We need the Catalina jars for Tomcat -->
 <!-- * for other app servers - check the docs -->
 <fileset dir="${appserver.lib}">
 <include name="catalina-ant.jar"/>
 </fileset>
 </path>

<taskdef name="install" classname="org.apache.catalina.ant.InstallTask">
 <classpath refid="catalina-ant-classpath"/>
 </taskdef>
 <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask">
 <classpath refid="catalina-ant-classpath"/>
 </taskdef>
 <taskdef name="list" classname="org.apache.catalina.ant.ListTask">
 <classpath refid="catalina-ant-classpath"/>
 </taskdef>
 <taskdef name="start" classname="org.apache.catalina.ant.StartTask">
 <classpath refid="catalina-ant-classpath"/>
 </taskdef>
 <taskdef name="stop" classname="org.apache.catalina.ant.StopTask">
 <classpath refid="catalina-ant-classpath"/>
 </taskdef>

<target name="install" description="Install application in Tomcat">
 <install url="${tomcat.manager.url}"
 username="${tomcat.manager.username}"
 password="${tomcat.manager.password}"
 path="/${name}"
 war="${name}"/>
 </target>

<target name="reload" description="Reload application in Tomcat">
 <reload url="${tomcat.manager.url}"
 username="${tomcat.manager.username}"
 password="${tomcat.manager.password}"
 path="/${name}"/>
 </target>

<target name="start" description="Start Tomcat application">
 <start url="${tomcat.manager.url}"
 username="${tomcat.manager.username}"
 password="${tomcat.manager.password}"
 path="/${name}"/>
 </target>

<target name="stop" description="Stop Tomcat application">
 <stop url="${tomcat.manager.url}"
 username="${tomcat.manager.username}"
 password="${tomcat.manager.password}"
 path="/${name}"/>
 </target>

<target name="list" description="List Tomcat applications">
 <list url="${tomcat.manager.url}"
 username="${tomcat.manager.username}"
 password="${tomcat.manager.password}"/>
 </target>

<!-- End Tomcat tasks -->

</project>

And here is the build.properties file.

# Ant properties for building the springapp

appserver.home=C:/apache-tomcat-7.0.27
# for Tomcat 5 use $appserver.home}/server/lib
# for Tomcat 6 use $appserver.home}/lib
appserver.lib=${appserver.home}/lib

deploy.path=${appserver.home}/webapps

tomcat.manager.url=http://localhost:8080/manager
tomcat.manager.username=tomcat
tomcat.manager.password=s3cret

But this gave me the above error mentioned in the topic of this post. And here is the way to solve it. Change this t


<taskdef name="install" classname="org.apache.catalina.ant.InstallTask">
 <classpath refid="catalina-ant-classpath"/>
 </taskdef>

into this.


<taskdef name="install" classname="org.apache.catalina.ant.DeployTask">
<classpath refid="catalina-ant-classpath"/>
</taskdef>

The reason is that the installTask class has been outdated. This might be OK with older Tomcat versions. But not with the new versions. 🙂 🙂

Categories: eclipse, Spring, Spring MVC, XML

Handling static content in Spring MVC

Since Spring MVC is built in framework, there is an specific way to deal with it in some scenarios. Adding the static content like css,js, images is little bit tricky with spring mvc. Before adding these resources, there should be an specific folder structure to it. It should be as follows.

src/
 springmvc/
  java/
   HomeController.java
WebContent/
  resources/
   img/
    image.jpg
  WEB-INF/
    jsp/
      index.jsp
    web.xml
    mvc-dispatcher-servlet.xml

Or as follows.

Everything you need to be static should be kept inside the webapp/resources folder. Now add the configuration to the mvc-dispatcher servlet.xml. Finally it should be like this.


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

<context:component-scan base-package="com.supun.springwater.controller" />
 <mvc:resources mapping="/resources/**" location="/resources/" />

 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
 <bean id="viewResolver"
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="viewClass"
 value="org.springframework.web.servlet.view.JstlView" />
 <property name="prefix">
 <value>/WEB-INF/pages/</value>
 </property>
 <property name="suffix">
 <value>.jsp</value>
 </property>
 </bean>

</beans>

Now link the static content to ur application as follows.


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link type="image/x-icon" href="./images/favicon.ico" rel="shortcut icon" lang="en"/>
 <title>Home</title>
<link href="<c:url value="/resources/css/view.css" />" rel="stylesheet" type="text/css" />
<link href="<c:url value="/resources/css/gh-buttons.css" />" rel="stylesheet" type="text/css" />

Now add the dependencies for JSTL in your pom.xml as follows.


<!-- standard.jar -->
 <dependency>
 <groupId>taglibs</groupId>
 <artifactId>standard</artifactId>
 <version>1.1.2</version>
 </dependency>

 <!-- JSTL -->
 <dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>jstl</artifactId>
 <version>1.1.2</version>
 </dependency>

Now clean the project and reimport to eclipse using following commands.

mvn eclipse:clean & mvn eclipse:eclipse -Dwtpversion=2.0 . Then run the application in your application server.

 

Categories: Spring, Spring MVC, XML Tags: