Showing posts with label Example. Show all posts
Showing posts with label Example. Show all posts

Thursday, 18 April 2013

Calling Javascript From Java (Example)

This post explains how to call Javascript from Java. The code example is available at GitHub in the Java-Javascript-Calling directory.

Code Example

We create some small Javascript code in a string. This code dumps "Hello World!" and defines a function called myFunction() adding 3 to the provided value:
public class JavascriptCalling {

    public static final String MY_JS
        = "print(\"Hello world!\\n\");"
        + "var myFunction = function(x) { return x+3; };";

    public static void main(String[] args)
            throws ScriptException, NoSuchMethodException {

        // Retrieving the Javascript engine
        ScriptEngine se = new ScriptEngineManager()
            .getEngineByName("javascript");

        if ( Compilable.class.isAssignableFrom(se.getClass()) ) {

            // We can compile our JS code
            Compilable c = (Compilable) se;
            CompiledScript cs = c.compile(MY_JS);

            System.out.println("From compiled JS:");
            cs.eval();

        } else {

            // We can't compile our JS code
            System.out.println("From interpreted JS:");
            se.eval(MY_JS);

        }

        // Can we invoke myFunction()?
        if ( Invocable.class.isAssignableFrom(se.getClass()) ) {

            Invocable i = (Invocable) se;
            System.out.println("myFunction(2) returns: "
                + i.invokeFunction("myFunction", 2));

        } else {

            System.out.println(
                "Method invocation not supported!");

        }

    }

}
The above starts by retrieving the Javascript engine. Next, if one can compile the Javascript, our code is compiled. The script is executed, which prints "Hello World!". Last, if the engine allows invocation, we call our function defined in our Javascript code.

The result is:

Thursday, 28 March 2013

Java ServiceLoader Example

Defining an API and developing the corresponding implementation has become an uber mainstream practice when developing large Java applications. Modularization is such an useful design principle, especially to avoid spaghetti code, for testing and debugging, and for re-implementation of old code.

Many developers seek to separate API interfaces and abstract classes from their implementation in separate packages. Yet, this almost always leads to cycles between java packages (api refers to impl, and vice-versa). There has been many frameworks, such as OSGi, supporting modularization, but the documentation has not always been good and complete. Many developers have struggled with class loading issues too.

Fortunately, Java has delivered the ServiceLoader utility since release 6. The example described in this post is available from Github in the Java-ServiceLoader directory. It is inspired from here.

Service & Implementation

We define a simple interface and its implementation:
package com.service.API;

public interface MyService {
    long getTime();
}


package com.service.API.Impl;

import com.service.API.MyService;

public final class MyServiceImpl implements MyService {

    public MyServiceImpl() { };

    @Override
    public long getTime() {
        return System.currentTimeMillis();
    }

}
The API and the implementation are located in different packages. Only the implementation refers to the API. The implementation must have a public parameterless constructor.

Service Loading

Next, we declare the implementation in a file having the fully qualified name of the API under the META-INF/services directory in the .jar:


The file contains fully qualified name of the implementation:

    com.service.API.Impl.MyServiceImpl

Next, we load the service using the ServiceLoader:
public class MyApp {

    public static <T> T loadService(Class<T> api) {

        T result = null;

        ServiceLoader<T> impl = ServiceLoader.load(api);

        for (T loadedImpl : impl) {
            result = loadedImpl;
            if ( result != null ) break;
        }

        if ( result == null ) throw new RuntimeException(
            "Cannot find implementation for: " + api);

        return result;

    }

    public static final MyService myService = loadService(MyService.class);

    public static void main(String[] args) {

        System.out.println("Time is: " + myService.getTime());

    }

}
The service implementation is loaded with the loadService static method. The main method prints the current time in milliseconds. It is that simple!

Sunday, 18 November 2012

Spring Internationalization Example (with Annotations)

Spring InternationalizationThis post describes how to implement message internationalization in Spring. The code example is available from GitHub in the Spring-MVC-Internationalization directory. It is based on the Spring MVC with annotations example.

Internationalization

We define two resource bundles (setA and setB) containing string translations for German, French and English. These are created in the src/main/resources maven directory.

Configuration

We need to create:
  • a ResourceBundleMessageSource bean to load the string translations
  • a LocaleChangeInterceptor bean which will intercept requests and extract a parameter value (if available) to detect language changes
  • a SessionLocaleResolver bean to store the user's locale preference in the session
  • to register the LocaleChangeInterceptor in the interceptor registry
 We extend our web configuration:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    ...

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource result
            = new ResourceBundleMessageSource();

        String[] basenames = {
            "i18n.setA.setA",
            "i18n.setB.setB"
        };

        result.setBasenames(basenames);

        return result;

    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor result = new LocaleChangeInterceptor();
        result.setParamName("lang");

        return result;

    }

    @Bean
    public LocaleResolver localeResolver() {

        SessionLocaleResolver result = new SessionLocaleResolver();
        result.setDefaultLocale(Locale.ENGLISH);

        return result;

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}

Controller

We simply our controller a lot:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

}

JSP Page

We only keep the index.jsp page, where we add links to change the language of displayed messages:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<!doctype html>
<html lang="en">
<head>
  <title>Welcome To Spring MVC Internationalization !!!</title>
</head>
<body>
  <h1>Spring MVC Internationalization !!!</h1>
  <p>Choose:
      <a href="<c:url value='?lang=en'/>">English</a>
      | <a href="<c:url value='?lang=fr'/>">French</a>
      | <a href="<c:url value='?lang=de'/>">German</a>
  </p>

  <p>Greetings: <spring:message code="greetings" text="missing" /></p>
  <p>Text 2: <spring:message code="text2" text="missing" /></p>
  <p>Current: <c:out value="${pageContext.response.locale}" /></p>
</body>
</html>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8383/spring-mvc-internationalization/

The main page will be displayed:


If you click on German, the German text is displayed:


More Spring related posts here.

Sunday, 4 November 2012

Fetching JSON With Ajax In Spring MVC Context

This post explains how to fetch a JSON using Ajax from a Spring MVC web application. It is based on the Spring MVC With Annotations and Serving Static Resources With Spring MVC examples. The code is available on GitHub in the Spring-Fetching-JSON-With-Ajax directory.

Main Index Page

We use a simple index.jsp page, where we set a button that fetches a JSON, and a <div> where the result will be displayed:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script type="text/javascript"
    src="<c:url value='/resources/js/FetchingJsonWithAjax.js'/>">
  </script>
  <title>Welcome To Fetching JSON With Ajax !!!</title>
</head>
<body>
    <h1>Fetching JSON With Ajax !!!</h1>
    <div id="theJson"></div>
    <button type="button" onclick="fetch_json()">
        Fetch JSON
    </button>
</body>
</html>

Javascript

On the button, we attach the fetch_json() Javascript method, which is called when the button is clicked:
var fetch_json = function() {

    $.ajax({
        type: 'GET',
        url:  "/spring-fetching-json-with-ajax/getJSON",
        dataType: 'json',
        async: true,
        success: function(result) {

            var tmp = "Fetch time is: " + result.milliTime + " !"
               + "and the JSON is:"
               + JSON.stringify(result);

            $("#theJson").html(tmp);

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Issue fetching the JSON: "
                + textStatus + " "
                + errorThrown + " !");
        }

    });

}
If successful, we set the result on the <div>, else we pop-up a message with the error.

Controller

The controller is kept simple, and a MilliTime object is returned for the Ajax call:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";
    }

    @RequestMapping(value="/getJSON", method = RequestMethod.GET)
    public @ResponseBody MilliTimeItem getJSON() {
        return new MilliTimeItem(System.currentTimeMillis());
    }

}

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-fetching-json-with-ajax/

After clicking on the Fetch JSON button, something similar to the following will be displayed:



More Spring related posts here.

Serving Static Resources With Spring MVC

This post explains how to server static content from a Spring MVC web application. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-Serving-Static-Resources directory.

JSP Page

We keep only the main index.jsp page:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script type="text/javascript"
    src="<c:url value='/resources/js/SomeJavascript.js'/>">
  </script>
  <title>Welcome To Spring Serving Static Resources !!!</title>
</head>
<body>
    <h1>Spring - Serving Static Resources !!!</h1>
    <img border="0"
      src="<c:url value='/resources/img/MyArt.png'/>" alt="My Art" />
</body>
</html>
Regarding static resources:
  • We link JQuery from Google's CDN.
  • We link our own SomeJavascript.js and make sure the URL is properly constructed.
  • In the body, we add an image.

Resources

Spring Project Structure For Resources
In the Spring project itself, we put all the resources under a separate resources directory which does not stand under WEB-INF.
  • Images are stored under /resources/img.
  • Javascript is storted under /resources/js.
Our Javascript is a simple pop-up messages displayed when the HTML document is loaded:
$(document).ready(function() {
    alert("JS loaded successfully!");
});

Web Configuration & Controller

We need to modify our web configuration to add a static resource handler and configure it by specifying where to fetch these:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    ...

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

      registry
        .addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");
    }

}
We also simplify our controller:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";
    }

}

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-serving-static-resources/

The image and the pop-up will be displayed:



More Spring related posts here.

Monday, 29 October 2012

Spring MVC Form Validation (With Annotations)

This post provides a simple example of a HTML form validation. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-MVC-Form-Validation directory.

Data

For this example we will use a bean and JSR303 validation annotations:
public class MyUser {

    @NotNull
    @Size(min=1,max=20)
    private String name;

    @Min(0)
    @Max(120)
    private int age;

    public MyUser(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public MyUser() {
        name = "";
        age = 0;
    }

    // Setters & Getters

}

Pages

Our form will contain input elements, but also the possibility to display error messages:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!doctype html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>My User Form!</title>
</head>
<body>
  <form:form method="post" action="myForm" commandName="myUser">
    <table>
      <tr>
        <td>Name: <font color="red"><form:errors path="name" /></font></td>
      </tr>
      <tr>
        <td><form:input path="name" /></td>
      </tr>
      <tr>
        <td>Age: <font color="red"><form:errors path="age" /></font></td>
      </tr>
      <tr>
        <td><form:input path="age" /></td>
      </tr>
      <tr>
        <td><input type="submit" value="Submit" /></td>
      </tr>
    </table>
  </form:form>
</body>
</html>
Our success page is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Form Processed Successfully!</title>
</head>
<body>
    Form processed for <c:out value="${myUser.name}" /> ! <br />
    <a href="<c:url value='/'/>">Home</a>
</body>
</html>
Our home page:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Welcome !!!</title>
</head>
<body>
  <h1>
    Spring Form Validation !!!
  </h1>
<a href="<c:url value='/myForm'/>">Go to the form!</a>
</body>
</html>

Controller

Notice that we need to use @ModelAttribute to make sure an instance of MyUser is always available in the model. In the validateForm(), we need to use @ModelAttribute to move the content of the form to the MyUser project.
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

    @ModelAttribute("myUser")
    public MyUser getLoginForm() {
        return new MyUser();
    }

    @RequestMapping(value = "/myForm", method = RequestMethod.GET)
    public String showForm(Map model) {
        return "myForm";
    }

    @RequestMapping(value = "/myForm", method = RequestMethod.POST)
    public String validateForm(
        @ModelAttribute("myUser") @Valid MyUser myUser,
        BindingResult result, Map model) {

        if (result.hasErrors()) {
            return "myForm";
        }

        model.put("myUser", myUser);

        return "success";

    }

}

Maven Dependencies

We need the following dependencies. The Hibernate validator dependency is necessary to process JSR303 annotations:
<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>1.0.0.GA</version>
  <type>jar</type>
</dependency>

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>4.3.0.Final</version>
</dependency>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8383//spring-mvc-form-validation/.

If the end user enters invalid values, error messages will be displayed:


More Spring related posts here.

Returning a JSON in Spring (With Annotations)

This post provides the simplest example to return a JSON from a Spring controller. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-Returning-A-JSON directory.

For a full Spring MVC REST calls with Ajax example, see here.

Dependencies

On top of current dependencies, we add the Jackson mapper dependency:
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.10</version>
</dependency>
This dependency enables the conversion of Java objects into a JSON representation.

Data

For this example, we use a simple SomeData class:
public class SomeData {

    private String name;
    private long time;

    public SomeData(String name, long time) {
        this.name = name;
        this.time = time;
    }

    public SomeData() {
        name = "";
        time = System.currentTimeMillis();
    }

    // Setters & Getters

}

Controller

We modify our controller as following:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

    @RequestMapping(value="/getJSON/{name}", method = RequestMethod.GET)
    public @ResponseBody SomeData getJSON(@PathVariable String name) {

        SomeData result
            = new SomeData(name, System.currentTimeMillis());

        return result;

    }

}
The getJSON() method has special annotations usage:
  • @RequestMapping's value contains {name} which will be extracted by Spring an inserted as the parameter value in the method.
  • @ResponseBody's indicates that the body of the response to the user's request must be filled with what is returned by the method. Here, we return a SomeData object. Since we have added the Jackson dependency, Spring will automatically detect it and perform the conversion of this object into its JSON representation.
  • @PathVariable extracts the parameter's name from the URL's {name} and sets its as the parameter value in the getJSON() method.

JSP Index Page

Our index page remains very simple:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome !!!</title>
</head>
<body>
    <h1>
    Welcome To Spring Returning A JSON !!!
    </h1>
    <a href="<c:url value='/getJSON/Arthur'/>">Get JSON for Arthur !!!</a>
</body>
</html>
It contains a link making a call to /getJSON/Arthur.

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8383/spring-returning-a-json/.

The home page will display:


Click on the link to retrieve the JSON:



More Spring related posts here.

Friday, 26 October 2012

Spring FreeMarker Integration Example (With Annotations)

This post provides a simple example of FreeMarker integration within a Spring application. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-FreeMarker-Integration directory.

FreeMarker also offers two great tutorials: the Template Author's Guide and the Programmer's Guide.

Configuration

We need to modify our Web configuration to set a FreeMarker viewer and a FreeMarker configurer:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {

        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setCache(false);
        // resolver.setPrefix("");
        resolver.setSuffix(".ftl");

        return resolver;

    }

    @Bean
    public FreeMarkerConfigurer getFreemarkerConfig() {

        FreeMarkerConfigurer result = new FreeMarkerConfigurer();
        result.setTemplateLoaderPath("WEB-INF/pages/");

        return result;

    }

}
Our controller remains very simple:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {

        model.addAttribute("MsTime", System.currentTimeMillis());

        return "Home";

    }

}

FreeMarker Template

We use a simple FreeMarker template:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring FreeMarker Example !!!</title>
</head>
<body>
    This is the Spring FreeMarker Example !!!

    Time is: ${MsTime}!
</body>
</html>

Maven Dependency

We need the following dependency:
 <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.19</version>
</dependency>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8282/spring-freemarker-integration/.

The home page will display:



More Spring related posts here.

Saturday, 15 September 2012

Spring Security Configuration Introduction

This post describes the basic Spring security configuration steps all Spring applications must implement.

Setting Filters

Spring security relies on user request filters. These must be configured in the web.xml file under the contextConfigLocation elements:
<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Security Configuration

A <name>-security.xml file must be created in /WEB-INF with this initial structure:
<beans:beans
  xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="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
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    ...
</beans:beans>
<name> must be the name of the servlet as configured in web.xml.

Spring configuration can only be performed with XML documents. However, one can mix Java configuration and Spring XML configuration like this when using MVC:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "my.packages")
@ImportResource("WEB-INF/<name>-security.xml")
public class WebConfig extends WebMvcConfigurerAdapter {
    ...
}
The above imports the Spring security configuration.

REM: the tutorial available here recommends configuring the <name>-security.xml file in the contextConfigLocation section of web.xml. However, it does not work when using Java configuration. One must use @ImportResource as described above.

Maven Dependencies

The following maven dependencies are required for Spring security:
<properties>
    ...
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>
...
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>${spring.version}</version>
    <type>jar</type>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>${spring.version}</version>
</dependency>

For a concrete Spring Security example, click here • More Spring related posts here.

Wednesday, 12 September 2012

Spring Sitemesh Integration Example

This post is a follow-up to the quick introduction to Sitemesh concepts. It provides a simple example of Sitemesh integration in a simple Spring application. The code is available on GitHub in the Spring-Sitemesh-Integration directory.

Configuration

We need to add the sitemesh filter configuration in the web.xml file. We apply the filter to all pages:
<filter>
    <filter-name>sitemesh</filter-name>
    <filter-class>
        com.opensymphony.module.sitemesh.filter.PageFilter
    </filter-class>
</filter>

<filter-mapping>
    <filter-name>sitemesh</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
We create a WEB-INF/sitemesh.xml configuration file. We specify the location of the decorators.xml file, together with the page parser and a delivered decorater mapper:
<sitemesh>
    <property name="decorators-file" value="/WEB-INF/decorators.xml"/>
    <excludes file="${decorators-file}"/>
    <page-parsers>
        <parser default="true"
            class="com.opensymphony.module.sitemesh.parser.FastPageParser"/>
        <parser content-type="text/html"
            class="com.opensymphony.module.sitemesh.parser.FastPageParser"/>
    </page-parsers>

    <decorator-mappers>
        <mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">
            <param name="config" value="${decorators-file}"/>
        </mapper>
    </decorator-mappers>
</sitemesh>
We create a WEB-INF/decorators.xml configuration file to specify our decoration JSP page:
<decorators defaultdir="/decorators">
    <decorator name="default" page="MyDecorator.jsp">
        <pattern>/*</pattern>
    </decorator>
</decorators>

Decorator

We define our decorator JSP page, which adds a default header and footer. It also retrieves the decorated document's title, head and body:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<!DOCTYPE html>
<html>
<head>
    <title><decorator:title default="SiteMesh Integration"/></title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <decorator:head/>
</head>
<body>

    <div id="header">
        <h1>Header Added By Sitemesh</h1>
    </div>

    <div id="content">
        <decorator:body/>
    </div>

    <div id="Footer">
        <h2>Some Copyright Added By Sitemesh</h2>
    </div>

</body>
</html>

Pages To Decorate

We define a simple Home.jsp page:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Home Page !!!</title>
    </head>
    <body>
        This is the home page content !!!<br /><br />
        <a href="<c:url value='/AnotherPage'/>">Another Page</a>
    </body>
</html>
...with a link to AnotherPage.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Another Page !!!</title>
    </head>
    <body>
        This is the content of another page !!!
    </body>
</html>

Maven Dependency

We need the following dependency:
 <dependency>
    <groupId>opensymphony</groupId>
    <artifactId>sitemesh</artifactId>
    <version>2.4.2</version>
</dependency>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse: http://localhost:8282/spring-sitemesh-integration/.

The home page will display:

The other page displays:
More Spring related posts here.

Tuesday, 11 September 2012

Select From JPA Criteria API Example

This post describes how to generate Select From queries using the JPA Criteria API. All code examples are available from Github in the JPA directory. Some error messages will be displayed when running some examples because of a known and harmless issue.

This code example relies on a simple item:
@Entity
@AutoProperty
public class SomeItem {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long Id;

    private String data;

    // Constructors, Setters & Getters, Pojomatic...

}
The following code creates and executes a simple Select From query using the JPA Criteria API:
// Creating some data
SomeItem A = new SomeItem("rttt");
SomeItem B = new SomeItem("qqqq");
SomeItem C = new SomeItem("zzzz");

JPA.INSTANCE.save(A);
JPA.INSTANCE.save(B);
JPA.INSTANCE.save(C);

CriteriaBuilder cb = JPA.INSTANCE.EM.getCriteriaBuilder();

// Constructing Select * from SomeItem
CriteriaQuery<SomeItem> q = cb.createQuery(SomeItem.class);
Root<SomeItem> c = q.from(SomeItem.class);
q.select(c);

// Executing the query
TypedQuery<SomeItem> query = JPA.INSTANCE.EM.createQuery(q);
List<SomeItem> results = query.getResultList();

// Printing results
for ( SomeItem si : results ) {
    System.out.println(si);
}
The generated output is:
SomeItem{Id: {1}, data: {rttt}}
SomeItem{Id: {2}, data: {qqqq}}
SomeItem{Id: {3}, data: {zzzz}}
More about query parameters here.

Thursday, 6 September 2012

Spring MVC Controller JUnit Testing

JUnit testing Spring MVC controllers is not an easy task. But recently, a new project (now included in Spring 3.2) offers new tools to facilitate this. This post illustrates how to test a simple controller via JUnit tests.

This code is a variation of the code used in JUnit Testing Spring Service and DAO (with In-Memory Database). It is available from Gihut in the Spring-MVC-JUnit-Testing directory.

Test Configuration Classes

These are identical to those required for Service and DAO testing.

Controller

Our controller:
@Controller
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(value = "/")
    public String home(Model model) {

        return "index";

    }

    @RequestMapping(value = "/roundtrip")
    public String persistenceStatus(Model model) {

        MilliTimeItem retr = myService.createAndRetrieve();
        model.addAttribute("RoundTrip", retr);

        return "roundtrip";

    }

}

Controller Testing

The following creates an instance of MockMvc to test simulated user requests:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ JpaTestConfig.class, TestConfig.class })
public class MyControllerTest {

    private MockMvc mockMvc;

    @Before
    public void setup() {

        mockMvc = MockMvcBuilders
            .annotationConfigSetup(JpaTestConfig.class, TestConfig.class)
            .build();

    }

    @Test
    public void testHome() throws Exception {

        mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(forwardedUrl("WEB-INF/pages/index.jsp"));

    }

    @Test
    public void testPersistenceStatus() throws Exception {

        mockMvc.perform(get("/roundtrip"))
            .andExpect(status().isOk())
            .andExpect(forwardedUrl("WEB-INF/pages/roundtrip.jsp"))
            .andExpect(model().attributeExists("RoundTrip"));

    }

}
The / request verifies the returned status and the URL mapping to the JSP page. The /roundtrip request makes sure the returned model does contain the Roundtrip attribute.

Dependencies

The Spring MVC test artifact is not yet available from maven's central repository. It should be obtained from another repository:
<repositories>
    <repository>
        <id>spring.test-mvc</id>
        <url>http://repo.springsource.org/libs-milestone</url>
    </repository>
</repositories>
The required dependency are:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test-mvc</artifactId>
    <version>1.0.0.M1</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

More Spring related posts here.

How To Add An External Repository In A Maven pom.xml?

By default, a maven project has access to the local repository and the central repository (see here for an introduction to maven concepts). It is possible to reference additional external repositories in the pom.xml to have access to its artifacts.
For example, it is currently not possible to access the following artifact from the central repository:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test-mvc</artifactId>
    <version>1.0.0.M1</version>
    <scope>test</scope>
</dependency>
One should access it from: http://repo.springsource.org/libs-milestone. This can be achieved by adding the following to your pom.xml:
<project>
    ...
    <repositories>
        <repository>
            <id>spring.test-mvc</id>
            <url>http://repo.springsource.org/libs-milestone</url>
        </repository>
    </repositories>
</project>

Tuesday, 4 September 2012

JUnit Testing Spring Service and DAO (with In-Memory Database)

This post describes how to implement JUnit tests for a Spring Web Application's Services and DAO. It is built on top of the Spring MVC-Service-DAO-Persistence Architecture Example. This example is available from Github in the Spring-Web-JPA-Testing directory.

Reminder

  • Test Fixture - The fixed state used as a baseline for running tests.
  • Unit test - These tests verify that pieces of code (components) perform some functionalities as expected. In a Java environment, these are typically implemented at the class level.
  • Integration test - Integration testing is any type of test checking that a set of interacting components perform expected functionalities together correctly.

Configuration

We need a JPA Hibernate configuration for in-memory testing:
@Configuration
@EnableTransactionManagement
public class JpaTestConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setDataSource(this.dataSource());
        lcemfb.setPackagesToScan(new String[] {"com.jverstry"});
        lcemfb.setPersistenceUnitName("MyTestPU");

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
        lcemfb.setJpaVendorAdapter(va);

        Properties ps = new Properties();
        ps.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
        ps.put("hibernate.hbm2ddl.auto", "create");
        lcemfb.setJpaProperties(ps);

        lcemfb.afterPropertiesSet();

        return lcemfb;

    }

    @Bean
    public DataSource dataSource(){

        DriverManagerDataSource ds = new DriverManagerDataSource();

        ds.setDriverClassName("org.hsqldb.jdbcDriver");
        ds.setUrl("jdbc:hsqldb:mem:testdb");
        ds.setUsername("sa");
        ds.setPassword("");

        return ds;

    }

    @Bean
    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager tm = new JpaTransactionManager();

        tm.setEntityManagerFactory(
            this.entityManagerFactoryBean().getObject() );

        return tm;

    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }

}
We need to exclude the production configuration from package scanning (no "com.jverstry" scanning):
@Configuration
@ComponentScan(basePackages = {
    "com.jverstry.Controller",
    "com.jverstry.DAO",
    "com.jverstry.Item",
    "com.jverstry.Service"
})

public class TestConfig {

    @Bean
    public MyService getMyService() {
        return new MyServiceImpl();
    }

}

Spring Testing Tools

  • @RunWith - This is a JUnit annotation allowing one to run a test with a different runner than the one provided by JUnit.
  • SpringJUnit4ClassRunner - This is a JUnit test runner for Spring applications. Typically, test classes are annoted with @RunWith(SpringJUnit4ClassRunner.class). 
  • @ContextConfiguration - This annotation can be used to specify how to load an applicationContext in Spring test class. This can be configured via XML files or Java configuration objects.

Service Testing

The following class tests the createAndRetrieve() method of our injected MyService implementation:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ JpaTestConfig.class, TestConfig.class })
public class MyServiceImplTest {

    @Autowired
    private MyService myService;

    @Test
    public void testCreateAndRetrieve() {

        MilliTimeItem retr = myService.createAndRetrieve();

        assertNotNull(retr);

    }

}

DAO Testing

The following class tests our DAO implementation. Our implementation is injected with an EntityManager created from our test configuration class defined above.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ JpaTestConfig.class, TestConfig.class })
public class MyPersistenceDAOTest {

    @Autowired
    private MyPersistenceDAO myDAO;

    @Test
    public void testCreateMilliTimeItem() {

        // This operation should not throw an Exception
        long id = myDAO.createMilliTimeItem();

    }

    @Test
    public void testGetMilliTimeItem() {

        long id = myDAO.createMilliTimeItem();
        MilliTimeItem retr = myDAO.getMilliTimeItem(id);

        assertNotNull(retr);
        assertEquals(id,retr.getID());

    }

}

Caveat

When starting to write JUnit tests for Spring, one can come across the following error messages:
Java.lang.ClassFormatError:
Absent Code attribute in method that is not native or abstract in class file javax/validation/Validation
The above is often caused by the following maven dependency:
         <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
            <type>jar</type>
         </dependency>
It should be replaced with:
           <dependency>
               <groupId>org.apache.geronimo.specs</groupId>
               <artifactId>geronimo-jpa_2.0_spec</artifactId>
               <version>1.1</version>
               <scope>provided</scope>
           </dependency>
Another error message is:
javax.validation.ValidationException: Unable to find a default provider
This is solved by adding the following maven dependency:
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.0.Final</version>
        </dependency>

For Spring MVC Controller JUnit testing, see here • More Spring related posts here.

Monday, 3 September 2012

Spring MVC-Service-DAO-Persistence Architecture Example

It is considered good practice to use modularity across Spring web applications. It keeps them maintainable and testable. This can be achieved by using controllers, services and data access objects (DAO). Typically, a user request is handled by a controller, which calls a service, which calls a data access object, which calls the persistence layer implementation.

Using services means that application functionalities can be tested without a test framework simulating user calls to controllers. Separating services from the persistence layer implementation via DAO, allows using an in-memory database (for example) by substituting production DAO implementations, by test DAO implementation pointing to an in-memory database.

The code example used in this post is available from Github in the Spring-MVC-Service-DAO-Persistence-Architecture directory. It is a variation of the Spring Web JPA Hibernate In-Memory example.

MVC Controller Calls The Service Implementation

The following controller is injected with an implementation of MyService. It handles /roundtrip user calls by calling its create() and Retrieve(id) methods, which creates and retrieves an instance of a MilliTimeItem object. It contains a unique ID and a timestamp in milliseconds.
@Controller
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";
    }

    @RequestMapping(value = "/roundtrip")
    public String persistenceStatus(Model model) {

        long id = myService.create();
        MilliTimeItem retr = myService.retrieve(id);
 
        model.addAttribute("RoundTrip", retr);
 
        return "roundtrip";

    }

}

Service Implementation calls Data Access Objects (DAO)

The DAO is injected in the MyService implementation. The createAndRetrieve() calls the DAO createMilliTimeItem() and getMilliTimeItem() methods. It returns the created and retrieved item.
public class MyServiceImpl implements MyService {

    @Autowired
    private MyPersistenceDAO myDAO;

    @Transactional
    long create();
 
    @Transactional
    MilliTimeItem retrieve(long id);

}

Data Access Object Implementation Calls The Persistence Layer

The DAO implementation is injected with the JPA EntityManager:
@Repository
public class MyPersistenceDAOImpl implements MyPersistenceDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public long createMilliTimeItem() {
 
        MilliTimeItem mti = new MilliTimeItem();
        mti.setMilliTime(System.currentTimeMillis());

        em.persist(mti);
        long result = mti.getID();
        em.detach(mti);
 
        return result;
 
    }

    @Override
    public MilliTimeItem getMilliTimeItem(long id) {
        return em.find(MilliTimeItem.class, id);
    }

}

Running the Example

After compiling this example with Maven, it can be run with mvn tomcat:run. Then, browse http://localhost:8585/spring-mvc-service-dao-persistence-architecture/.

The generated output is:
Created MilliTimeItem's ID: 1
Created MilliTimeItem's value: 1346691836108

More Spring related posts here.

Spring Web JPA Hibernate In-Memory Example

This post introduces the web version of the Standalone Hibernate JPA In-Memory example. It relies on a very simple implementation of the Spring MVC framework. This example is available from Github in the Spring-Web-JPA-Roundtrip directory.

Configuration

Instead of using the traditional JPA persistence.xml configuration file, we use Java configuration. On top of the traditional WebConfig class, we have a JpaConfig class annotated with @EnableTransactionManagement to enable database transactions.

The LocalContainerEntityManagerFactoryBean is the easiest mean to configure JPA. Notice that the persistence.xml database connection information is moved to the DataSource. The PlatformTransactionManager is required to process @Transactional annotated method (discussed further).

PersistenceExceptionTranslationPostProcessor converts any vendor specific exceptions into Spring DataAccessException for easier handling.
@Configuration
@EnableTransactionManagement
public class JpaConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setDataSource(this.dataSource());
        lcemfb.setPackagesToScan(new String[] {"com.jverstry"} );
        lcemfb.setPersistenceUnitName("MyPU");

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
        lcemfb.setJpaVendorAdapter(va);

        Properties ps = new Properties();
        ps.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
        ps.put("hibernate.hbm2ddl.auto", "create");
        lcemfb.setJpaProperties(ps);

        lcemfb.afterPropertiesSet();

        return lcemfb;

    }

    @Bean
    public DataSource dataSource(){

        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("org.hsqldb.jdbcDriver");
        ds.setUrl("jdbc:hsqldb:mem:testdb");
        ds.setUsername("sa");
        ds.setPassword("");

        return ds;

    }

    @Bean
    public PlatformTransactionManager transactionManager() {

        JpaTransactionManager tm = new JpaTransactionManager();

        tm.setEntityManagerFactory(
            this.entityManagerFactoryBean().getObject() );

        return tm;

    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

}

Data Item, Controller & Repository

The persisted data relies on Pojomatic:
@Entity
@AutoProperty
public class Item implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long ID;

    private String name = "";

    // Setter, Getters, Pojomatic methods...


}
The controller calls the injected repository class for a CRUD roundtrip, and retrieves the generated messages in the model:
@Controller
public class MyController {

    @Autowired
    private MyRepository rep;

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";
    }

    @RequestMapping(value = "/roundtrip")
    public String Roundtrip(Model model) {

        model.addAttribute("Messages", rep.performRoundtrip());

        return "roundtrip";

    }

}
The repository annotated class, performs a CRUD (Create, Read, Update, Delete):
@Repository
public class MyRepository {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public List<String> performRoundtrip() {

        List<String> l = new ArrayList<String>();

        try {

            l.add("Before create");
            create(l);

            l.add("Before read I");
            read(l);

            l.add("Before update");
            update(l);

            l.add("Before read II");
            read(l);

            l.add("Before delete");
            delete(l);

            l.add("Before read III");
            read(l);

        } catch (Exception ex) {

            l.add(ex.toString());

        }

        return l;

    }

    private Item i = null;

    @Transactional
    public void create(List<String> l) {
        i = new Item();
        i.setName("Item A");
        l.add("- Before saving   : " + i);
        em.persist(i);
        l.add("- After saving    : " + i);
    }

    @Transactional
    public void read(List<String> l) {
        Item retr = em.find(Item.class, this.i.getID());
        l.add("- Retrieved       : " + retr);
    }

    @Transactional
    public void update(List<String> l) {
        i.setName("Item B");
        l.add("- Updated         : " + i);
        em.persist(i);
    }

    @Transactional
    public void delete(List<String> l) {
        l.add("- Deleting        : " + i);
        em.remove(i);
    }

}

JSP Page

The following roundtrip.jsp displays the messages collected during the roundtrip:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Roundtrip !!!</title>
    </head>
    <body>
        <c:forEach items="${Messages}" var="element">
            ${element}<br />
        </c:forEach><br />
        <a href="<c:url value='/'/>" />Home</a>
    </body>
</html>

Running the example

Once compiled, the example can be run with mvn tomcat:run. Then, browse http://localhost:8585/spring-web-jpa-roundtrip/.

The generated output is:
Before create
 - Before saving : Item{ID: {0}, name: {Item A}}
 - After saving : Item{ID: {1}, name: {Item A}}
Before read I
 - Retrieved : Item{ID: {1}, name: {Item A}}
Before update
 - Updated : Item{ID: {1}, name: {Item B}}
Before read II
 - Retrieved : Item{ID: {1}, name: {Item B}}
Before delete
 - Deleting : Item{ID: {1}, name: {Item B}}
Before read III
 - Retrieved : null

More Spring related posts here.

Wednesday, 29 August 2012

Spring MVC with Annotations Example

This post describes a simple Spring MVC application example with annotation configuration. This example is available from Github in the Spring-MVC-With-Annotations directory. Typically, a complete application's architecture includes several layers: MVC, Service, DAO, Persistence Layer.

Configuration

In our previous example, we still use a servlet-context.xml file. In this example, we get rid of it using the @EnableWebMvc annotation.

The web.xml file:
<?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">

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.jverstry.Configuration</param-value>
    </context-param>

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

    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

    <welcome-file-list>
        <welcome-file></welcome-file>
    </welcome-file-list>

</web-app>
We do not set a default welcome file. It is delegated to our controller.

The Java configuration class:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {

        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("WEB-INF/pages/");
        resolver.setSuffix(".jsp");

        return resolver;

    }

}
The @ComponentScan annotation tells Spring to scan the content of packages for Spring annotated classes.

JSP pages

We have two JSP pages in  the WEB-INF/pages/ directory.

index.jsp
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Welcome !!!</title>
</head>
<body>
  <h1>
    Welcome To Spring MVC With Annotations !!!
  </h1>
</body>
</html>
getTime.jsp 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Get Time !!!</title>
    </head>
    <body>
        The time in milliseconds is: <c:out value="${TimeIs}" /> !
    </body>
</html>

Controller & Service

Our controller:
@Controller
public class MyController {

    private MyService myService;

    @Autowired
    public void setMyService(MyService myService) {
        this.myService = myService;
    }

    @RequestMapping(value = "/")
    public String home() {
        return "index";
    }

    @RequestMapping(value = "/getTime")
    public String helloWorld(Model model) {
        model.addAttribute("TimeIs", myService.getCurrentTimeInMilliseconds());
        return "getTime";
    }

}
The above, maps index.jsp to '/' user requests.

Our service and implementation:
public interface MyService {
    long getCurrentTimeInMilliseconds();
}

public class MyServiceImpl implements MyService {

    @Override
    public long getCurrentTimeInMilliseconds() {
        return System.currentTimeMillis();
    }

}

@Configuration
public class MyServicesConfiguration {

    private MyService myService = new MyServiceImpl();

    @Bean
    public MyService getMyService() {
        return myService;
    }

}

Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.2</version>
        </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

Running The Example

After compiling the project, one can run it using the maven tomcat:run goal. Then, browse:

  http://localhost:8383/spring-mvc-with-annotations/getTime

It will display something similar to:

  The time in milliseconds is: 1346261454171 !

For the same example with Spring Security, click here • More Spring related posts here.

Thursday, 23 August 2012

JPA Many-To-Many Relationships

This post illustrates many-to-many relationships between two classes. Don't forget to set the ownership on one side.
@Entity
@AutoProperty
public class ManyToManyA implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
 
    @Property(policy=PojomaticPolicy.NONE) 
    @ManyToMany(cascade=CascadeType.ALL)
    private Collection<ManyToManyB> listOfB
        = new ArrayList<ManyToManyB>();

    private String s;

    // Setters, Getters, Constructors, Pojomatic...

}


@Entity
@AutoProperty
public class ManyToManyB implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
 
    @Property(policy=PojomaticPolicy.NONE) 
    @ManyToMany(cascade=CascadeType.ALL, mappedBy="listOfB")
    private Collection<ManyToManyA> listOfA
        = new ArrayList<ManyToManyA>();
 
    private String s;

    // Setters, Getters, Constructors, Pojomatic...

}
The following:
ManyToManyA a1 = new ManyToManyA("AA1");
ManyToManyA a2 = new ManyToManyA("AA2");
ManyToManyA a3 = new ManyToManyA("AA3");
  
ManyToManyB b1 = new ManyToManyB("BB1");
ManyToManyB b2 = new ManyToManyB("BB2");

a1.getListOfB().add(b1);
b1.getListOfA().add(a1);
  
a3.getListOfB().add(b1);
b1.getListOfA().add(a3);
  
a2.getListOfB().add(b2);
b2.getListOfA().add(a2);
  
a3.getListOfB().add(b2);
b2.getListOfA().add(a3);
  
JPA.INSTANCE.save(a1);
JPA.INSTANCE.save(a2);
JPA.INSTANCE.save(a3);
JPA.INSTANCE.clear();
  
System.out.println("Retriving ManyToMany A's and their B's");

ManyToManyA retrA1
    = JPA.INSTANCE.get(ManyToManyA.class, a1.getId());
  
System.out.println(retrA1);
for (ManyToManyB origB : retrA1.getListOfB()) {
    ManyToManyB retrB
        = JPA.INSTANCE.get(
            ManyToManyB.class, origB.getId());
    System.out.println(retrB);
} System.out.println(" ");
  
ManyToManyA retrA2
    = JPA.INSTANCE.get(ManyToManyA.class, a2.getId());
  
System.out.println(retrA2);
for (ManyToManyB origB : retrA2.getListOfB()) {
    ManyToManyB retrB
        = JPA.INSTANCE.get(
            ManyToManyB.class, origB.getId());
    System.out.println(retrB);
} System.out.println(" ");
  
ManyToManyA retrA3
    = JPA.INSTANCE.get(ManyToManyA.class, a3.getId());
  
System.out.println(retrA3);
for (ManyToManyB origB : retrA3.getListOfB()) {
    ManyToManyB retrB
        = JPA.INSTANCE.get(
            ManyToManyB.class, origB.getId());
    System.out.println(retrB);
} System.out.println(" ");
  
System.out.println("Retriving ManyToMany B's and their A's");
  
ManyToManyB retrB1
= JPA.INSTANCE.get(ManyToManyB.class, b1.getId());
  
System.out.println(retrB1);
for (ManyToManyA origA : retrB1.getListOfA()) {
    ManyToManyA retrA
        = JPA.INSTANCE.get(
            ManyToManyA.class, origA.getId());
    System.out.println(retrA);
} System.out.println(" ");
  
ManyToManyB retrB2
= JPA.INSTANCE.get(ManyToManyB.class, b2.getId());
  
System.out.println(retrB2);
for (ManyToManyA origA : retrB2.getListOfA()) {
    ManyToManyA retrA
        = JPA.INSTANCE.get(
            ManyToManyA.class, origA.getId());
    System.out.println(retrA);
} System.out.println(" ");
Generates:
Retriving ManyToMany A's and their B's
ManyToManyA{id: {1}, s: {AA1}}
ManyToManyB{id: {1}, s: {BB1}}
 
ManyToManyA{id: {3}, s: {AA2}}
ManyToManyB{id: {2}, s: {BB2}}
 
ManyToManyA{id: {2}, s: {AA3}}
ManyToManyB{id: {1}, s: {BB1}}
ManyToManyB{id: {2}, s: {BB2}}
 
Retriving ManyToMany B's and their A's
ManyToManyB{id: {1}, s: {BB1}}
ManyToManyA{id: {1}, s: {AA1}}
ManyToManyA{id: {2}, s: {AA3}}
 
ManyToManyB{id: {2}, s: {BB2}}
ManyToManyA{id: {2}, s: {AA3}}
ManyToManyA{id: {3}, s: {AA2}}
The above examples are available from Github in the JPA directory. They rely on Pojomatic too. Some errors messages will be displayed because of a known and harmless issue.

JPA Many-To-One Relationships (Unidirectional and Bidirectional)

This post illustrates simple many-to-one relationships between two classes.

Unidirectional

@Entity
@AutoProperty
public class ManyToOneUnidirectionalA implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
 
    @ManyToOne
    private ManyToOneUnidirectionalB b;
 
    private String s;

    // Setters, Getters, Constructors, Pojomatic...

}


@Entity
@AutoProperty
public class ManyToOneUnidirectionalB implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
 
    private String s;

    // Setters, Getters, Constructors, Pojomatic...

}
The following:
ManyToOneUnidirectionalA a1 = new ManyToOneUnidirectionalA("AA1");
ManyToOneUnidirectionalA a2 = new ManyToOneUnidirectionalA("AA2");
  
ManyToOneUnidirectionalB b = new ManyToOneUnidirectionalB("BBB");
  
a1.setB(b);
a2.setB(b);
  
JPA.INSTANCE.save(b);
JPA.INSTANCE.save(a1);
JPA.INSTANCE.save(a2);
JPA.INSTANCE.clear();
  
ManyToOneUnidirectionalA retrA1
    = JPA.INSTANCE.get(ManyToOneUnidirectionalA.class, a1.getId());
  
System.out.println("Retrieving ManyToOne Unidirectional A's");
System.out.println(retrA1);
  
ManyToOneUnidirectionalA retrA2
    = JPA.INSTANCE.get(ManyToOneUnidirectionalA.class, a2.getId());
  
System.out.println(retrA2);

System.out.println("Retrieving ManyToOne Unidirectional B");
ManyToOneUnidirectionalB retrB
    = JPA.INSTANCE.get(ManyToOneUnidirectionalB.class, b.getId());
  
System.out.println(retrB);
Generates:
Retrieving ManyToOne Unidirectional A's
ManyToOneUnidirectionalA{id: {1}, b: {ManyToOneUnidirectionalB{id: {1}, s: {BBB}}}, s: {AA1}}
ManyToOneUnidirectionalA{id: {2}, b: {ManyToOneUnidirectionalB{id: {1}, s: {BBB}}}, s: {AA2}}
Retrieving ManyToOne Unidirectional B
ManyToOneUnidirectionalB{id: {1}, s: {BBB}}

Bidirectional

A owns the relationship. We need to avoid Pojomatic circular reference issues too:
@Entity
@AutoProperty
public class ManyToOneBidirectionalA implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
 
    @Property(policy=PojomaticPolicy.NONE) 
    @ManyToOne
    private ManyToOneBidirectionalB b;
 
    private String s;

    // Setters, Getters, Constructors, Pojomatic...

}


@Entity
@AutoProperty
public class ManyToOneBidirectionalB implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
 
    @Property(policy=PojomaticPolicy.NONE) 
    @OneToMany(cascade=CascadeType.ALL, mappedBy="b")
    private Collection<ManyToOneBidirectionalA> a;
   
    private String s;

    // Setters, Getters, Constructors, Pojomatic...

}
The following:
ManyToOneBidirectionalA a11 = new ManyToOneBidirectionalA("BiAAA");
ManyToOneBidirectionalA a22 = new ManyToOneBidirectionalA("BiAAA");
ManyToOneBidirectionalB b2 = new ManyToOneBidirectionalB("BiBBB");
  
Collection<ManyToOneBidirectionalA> c
    = new ArrayList<ManyToOneBidirectionalA>();
c.add(a11);
c.add(a22);
b2.setA(c);
  
a11.setB(b2);
a22.setB(b2);
  
JPA.INSTANCE.save(b2);
JPA.INSTANCE.clear();

ManyToOneBidirectionalB retrB
    = JPA.INSTANCE.get(ManyToOneBidirectionalB.class, b2.getId());
  
System.out.println("Retrieving ManyToOne Bidirectional B");
System.out.println(retrB);
  
for (ManyToOneBidirectionalA orig : b2.getA()) {
    ManyToOneBidirectionalA retrA
        = JPA.INSTANCE.get(
     ManyToOneBidirectionalA.class, orig.getId());
    System.out.println(retrA);
}  
  
System.out.println("Retrieving ManyToOne Bidirectional A's");
  
ManyToOneBidirectionalA retrA11
    = JPA.INSTANCE.get(ManyToOneBidirectionalA.class, a11.getId());
  
System.out.println(retrA11);
System.out.println(retrA11.getB());
  
ManyToOneBidirectionalA retrA22
    = JPA.INSTANCE.get(ManyToOneBidirectionalA.class, a22.getId());
  
System.out.println(retrA22);
System.out.println(retrA22.getB());
Generates:
Retrieving ManyToOne Bidirectional B
ManyToOneBidirectionalB{id: {1}, s: {BiBBB}}
ManyToOneBidirectionalA{id: {1}, s: {BiAAA}}
ManyToOneBidirectionalA{id: {2}, s: {BiAAA}}
Retrieving ManyToOne Bidirectional A's
ManyToOneBidirectionalA{id: {1}, s: {BiAAA}}
ManyToOneBidirectionalB{id: {1}, s: {BiBBB}}
ManyToOneBidirectionalA{id: {2}, s: {BiAAA}}
ManyToOneBidirectionalB{id: {1}, s: {BiBBB}}
The above examples are available from Github in the JPA directory. They rely on Pojomatic too. Some errors messages will be displayed because of a known and harmless issue.