Tuesday, July 17, 2012

RESTEasy Spring Integration - Tutorial Part 1 - Introduction

This is step by step tutorial explaining how to integrate RESTEasy with Spring.
First tutorial part covers setting up simple REST Service, and request processing by Spring components.

Spring implementation is based version 3 with dependency injection. I do not use Spring annotations, but javax.inject instead. I find this approach more flexible, since is not tightly coupled with particular technology.

RESTEasy can be deployed in a various ways - I will concentrate on the most popular one - which is the web application with component scan. At the begining we will start with web 2.4 and later on update to 3.0.

Stand alone deployment, without spring would consists of two main parts - servlet for request processing, bootstrap listener which handles configuration, and finally REST Services itself. Bootstrap listener scans classpath and looks for classes annotated with @Path - those are potential candidates for REST Service. They will be registered in request dispatcher in order to handle incoming HTTP calls. Since this is stand alone deployment, RESTEasy will simply create instances of found REST Services - this means, that those instances and not deployed in any particular container (except tomcat). For example they cannot access Spring context - especially because there is none ;). But if developer would like to access Spring context within such setup, he would need to manually load Spring context from REST Service class. This is typical approach when accessing Spring from servlet, but there is much better solution:

Let Spring manage services and their dependencies, and RESTEasy handles REST/HTTP related stuff.

In the stand alone example, the REST Services (annotated with @Path) were created by RESTEasy classpath scanner. Now we will use Spring to instantiate REST Services and all dependent components.
When the web application starts, as first step the SpringContextLoaderListener is being triggered - it initializes Spring context and all declared components.
In the second step, the RESTEasy bootstrap is being triggered - but this is special one, designed for usage with spring. It does not scan classpath for @Path annotated classes - instead it queries Spring for all beans with @Path annotation, and Spring returns references to those beans. This is a big difference, when compared to standalone setup. RESTEasy will not create new instance of REST Service, it will reference beans created by Spring. Basically this is the main difference between standalone deployment and one based on Spring - REST Service instances are created by Spring, so they are running within Spring container, and have access to all Spring components, like any other Spring bean. RESTEasy only forwards incoming calls to those Spring beans.

Hints:
  • Service, component, spring managed bean, REST Service - all are synonyms, and technically they are Plain Java Objects Objects managed by Spring
  • Do not instantiate services with new operator. This would create new class outside of Spring context, and such class cannot access Spring manged beans, and therefore injections will not work (will remain null).
  • Do not register REST servlet on root context ("/*"), always use some path ("/rest/*"). You might need to add another servlet in the future, and this new servlet will conflict with one registered on root context. You can remove extra path with proper Apache configuration.

Tutorial Application

This is a web application which exposes simple REST Service. Its implementation forwards incoming calls to Spring component, which handles business logic - in our case it is answer to traditional "Hello World" message.

REST Service exposes two methods:
  • GET - /Hello/text -  request/response attributes are passed as text in URL. Request has single msg path parameter.  Response contains message from request with appended "Hello" text.
  • POST - /Hello/javabean - request/response attributes are passed in body as JSON/XML documents. Request contains msg and additionally gender attribute. Response contains message from request with appended "Hello Sir" or "Hello Madam" - depending on provided gender. Response includes also server time, it's not formatted - this will be covered later.

Curl examples:
>> GET REQUEST <<
curl -i http://localhost:8080/resteasy_spring_p1/rest/Hello/text?msg=Hi%20There
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 17

>> RESPONSE <<
Hi There--> Hello

>> POST REQUEST <<
curl -i -X POST -H "Content-Type: application/json" -d '{"msg":"Hi There","gender":"MALE"}' 
  http://localhost:8080/resteasy_spring_p1/rest/Hello/javabean
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Transfer-Encoding: chunked

>> RESPONSE <<
{"response":"Hi There--> Hello Sir","serverTime":1341305935291}

Project Structure (Maven)













  • org.mmiklas.resttutorial.model - POJOs / transfer objects for REST Service

    • org.mmiklas.resttutorial.rest - REST Service (Resource) implementation
    • org.mmiklas.resttutorial.server - Spring component containing backed implementation
    • resources - XML configuration files for logger and Spring
    • webapp/WEB-INF - deployment descriptor










    Spring Configuration


    Spring configuration consists of single XML file which enables classpath component scan. Dependencies between Spring components are declared by annotations - @Named declares Spring component, and @Inject references existing component.

    src/main/resources/tutorial-spring-context.xml 
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="..">
        <context:component-scan base-package="org.mmiklas.resttutorial" />
    </beans>

    Deployment Descriptor


    web.xml has following functions (later on we will update it to 3.0, now its 2.4):
    • initializes Spring context from XML file
    • initializes RESTEasy and enables Spring integration
    • registers RESTEasy dispatcher servlet on "/rest/*" context

    src/main/webapp/WEB-INF/web.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <web-app xmlns="...">
    
        <display-name>Spring REST Easy Tutorial</display-name>
    
        <!-- Custom name for main spring configuration -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:tutorial-spring-context.xml
            </param-value>
        </context-param>
    
        <!-- RESTEasy configuration -->
        <listener>
            <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
            </listener-class>
        </listener>
    
        <!-- RESTEasy <-> Spring connector (RESTEasy can access Spring beans) -->
        <listener>
            <listener-class>org.jboss.resteasy.plugins.spring.SpringContextLoaderListener
            </listener-class>
        </listener>
    
        <!-- RESTEasy HTTP Request processor -->
        <context-param>
            <param-name>resteasy.servlet.mapping.prefix</param-name>
            <param-value>/rest</param-value>
        </context-param>
        <servlet>
            <servlet-name>restservlet</servlet-name>
            <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
            </servlet-class>
        </servlet>
    
        <!-- NEVER map servlet to root context "/*" ! -->
        <servlet-mapping>
            <servlet-name>restservlet</servlet-name>
            <url-pattern>/rest/*</url-pattern>
        </servlet-mapping>
    </web-app>
    

    Transfer Objects (POJOs)

    Transfer objects will be serialized and deserialized from/to JSON. The configuration in both cases is made with JAXB annotations, new JSON parsers are supporting those - but make sure that you have latest version, because it was not always the case.


    package org.mmiklas.resttutorial.model;
    
    public enum Gender {
        MALE, FEMALE;
    }


    package org.mmiklas.resttutorial.model;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class HelloMessage {
    
        private String msg;
    
        private Gender gender;
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public Gender getGender() {
            return gender;
        }
    
        public void setGender(Gender gender) {
            this.gender = gender;
        }
    }
    


    package org.mmiklas.resttutorial.model;
    
    import java.util.Date;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class HelloResponse {
    
        private String response;
    
        private Date serverTime;
    
        public HelloResponse(String response, Date serverTime) {
            this.response = response;
            this.serverTime = serverTime;
        }
    
        public String getResponse() {
            return response;
        }
    
        public Date getServerTime() {
            return serverTime;
        }
    
    }
    

    REST Service


    REST implementation is based only on standard Java API - it does not have Spring or RESTEasy dependencies. This is really good approach to use standardized API as far as possible - it does not matter whenever you are planning to stick with particular framework forever - clean standardized code is easier to read.

    @Named annotation defines HelloRestService class as Spring component, and @Path declares this class additionally as REST Service provider. Spring will create instance of our class, and RESTEasy will expose its methods over HTTP.

    sayTextHello accepts GET messages on ..../Hallo/text and reads query parameter msg.

    sayJavaBeanHello accepts POST messages on ..../Hallo/javabean and supports XML and JSON documents. XML is supported by default, since Java contains required providers (marshaller/unmarshaller). JSON must be enabled - since it's not JDK part - I will describe that in next chapter.
     
    package org.mmiklas.resttutorial.rest;
    
    import javax.inject.Inject;
    import javax.inject.Named;
    import javax.ws.rs.Consumes;
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.QueryParam;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import org.mmiklas.resttutorial.model.HelloMessage;
    import org.mmiklas.resttutorial.model.HelloResponse;
    import org.mmiklas.resttutorial.server.HelloSpringService;
    
    @Named
    @Path("/Hello")
    public class HelloRestService {
    
        @Inject
        private HelloSpringService halloService;
    
        // curl http://localhost:8080/resteasy_spring_p1/rest/Hello/text?msg=Hi%20There
        @GET
        @Path("text")
        @Produces(MediaType.APPLICATION_FORM_URLENCODED)
        public Response sayTextHello(@QueryParam("msg") String msg) {
            String resp = halloService.sayTextHello(msg);
            return Response.ok(resp).build();
        }
    
        // curl -X POST -H "Content-Type: application/json" -d '{"msg":"Hi There","gender":"MALE"}'
        //   http://localhost:8080/resteasy_spring_p1/rest/Hello/javabean
        @POST
        @Path("javabean")
        @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
        @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
        public Response sayJavaBeanHello(HelloMessage msg) {
            HelloResponse resp = halloService.sayJavaBeanHello(msg);
            return Response.ok(resp).build();
        }
    }
    

    Spring Component (Backend)


    Spring implementation is self explanatory - service is declared with @Named. @Component would work as well, but it's not standarized annotation.
    @Named
    public class HelloSpringService {
    
        public String sayTextHello(String msg) {
            return msg + "--> Hello";
        }
    
        public HelloResponse sayJavaBeanHello(HelloMessage msg) {
            return new HelloResponse(msg.getMsg() + "--> Hello " + 
        (msg.getGender() == Gender.MALE ? "Sir" : "Madam"), new Date());
        }
    }

    JSON Provider


    sayJavaBeanHello REST method supports JSON media type. In order to enable it, we only need to have proper jar in classpath:
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>2.3.2.Final</version>
    </dependency>

    RESTEasy scans during bootstrap phase classpath and searches for content providers - they are divided into two groups - marshaller and unmarshaller:
    • unmarshaller class in annotated with @Provider, @Consumes and implements MessageBodyReader interface
    • marshaller class in annotated with @Provider, @Produces and implements MessageBodyWriter interface
    @Provider annotation is only marker declaring, that given class has some interesting functionality - first the implementing interface specifies it - annotation alone is not sufficient. @Produces and @Consumes are defining mime type which is supported by our provider - the same annotations can be found on rest methods.

    Both interfaces above have generic type (T), which is currently set to Object - it provides possibility to register dedicated provider for the same mime type, but different class type. For example we can register different provider for User and Group and both for mime type JSON.

    @Provider
    @Produces(MediaType.APPLICATION_JSON)
    public class MyMarshaller implements MessageBodyWriter<Object> {
    
        @Override
        public boolean isWriteable(Class<?> type, Type genericType, 
                Annotation[] annotations, MediaType mediaType) {
            return false;
        }
    
        @Override
        public long getSize(Object t, Class<?> type, Type genericType, 
                Annotation[] annotations, MediaType mediaType) {
            return 0;
        }
    
        @Override
        public void writeTo(Object t, Class<?> type, Type genericType, 
                Annotation[] annotations, MediaType mediaType,
                MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) 
                        throws IOException, WebApplicationException {
        }
    }

    @Provider
    @Consumes(MediaType.APPLICATION_JSON)
    public class MyUnmarshaller implements MessageBodyReader<Object> {
    
        @Override
        public boolean isReadable(Class<?> type, Type genericType, 
                Annotation[] annotations, MediaType mediaType) {
            return false;
        }
    
        @Override
        public Object readFrom(Class<Object> type, Type genericType, 
                Annotation[] annotations, MediaType mediaType,
                MultivaluedMap<String, String> httpHeaders, InputStream entityStream) 
                        throws IOException, WebApplicationException {
            return null;
        }
    }

    Maven build - 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/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>org.mmiklas.resteasy</groupId>
        <artifactId>resteasy_spring_p1</artifactId>
        <packaging>war</packaging>
        <version>1.0</version>
        <name>RESTEasy Spring - Tutorial - Part 1</name>
    
        <dependencies>
            <!-- Logger -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.16</version>
            </dependency>
    
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>3.1.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>3.1.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>3.1.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>javax.inject</groupId>
                <artifactId>javax.inject</artifactId>
                <version>1</version>
            </dependency>
    
            <!-- RESTEasy -->
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>jaxrs-api</artifactId>
                <version>2.3.2.Final</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-jaxrs</artifactId>
                <version>2.3.2.Final</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-jackson-provider</artifactId>
                <version>2.3.2.Final</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-spring</artifactId>
                <version>2.3.2.Final</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.resteasy</groupId>
                <artifactId>resteasy-jaxb-provider</artifactId>
                <version>2.3.2.Final</version>
            </dependency>
        </dependencies>
    </project>
    

    Project Source Download


    resteasy_spring_p1_src.zip
    https://github.com/maciejmiklas/resteasy_spring_p1.git

    Monday, July 16, 2012

    Ubuntu 12.04 - touchpad left button delayed reaction on Dell Precision laptop

    The Ubuntu installation on my Dell Precision T4600 (bought on 2012.06) worked just fine - besides one thing - touchpad left button. When I've tried to select text or drag window I needed to wait about one second before cursor has changed to "hand icon". The solution is, to disable, or change delay for third mouse button simulation - so far so good... but there is no such option. In my case helped something that does not make sense, but it has worked.
    Just execute those two commands:

    sudo apt-get install gpointing-device-settings
    gpointing-device-settings

    This installs and starts the mouse settings application - there is no need to do any changes, it probably overwrites some config files and problem was solved - at least in my case.

    Problem is related to this ubuntu bug

    Wednesday, May 23, 2012

    Wicket Notification Dialog - JavaScript refactoring

    This blog contains update to Wicket - Disappearing Notification Dialog post.
    I've moved JavaScript from Java code to separate file - it is in general good patern to not mix up those.


    Previous post has following JavaScript:
    effectBehavior.setCallback(new JQueryAjaxBehavior(this) {
    
        @Override
        public CharSequence getCallbackScript() {
            String fadeOut = "function(){$('" + dialogContainerId + ":visible').fadeOut();}";
            String callbackScript = "setTimeout(" + fadeOut + ", "
                            + Long.toString(config.getNotificationDisplayTimeMilis()) + ");";
            return callbackScript;
        }
    });
    Now we will move this JavaScript to notifier.js file, define there JS functions and call those functions from Java code.
    notifier.js
    function fadeOutDialog() {
        $("${dialogContainerId}:visible").fadeOut();
    }
    
    function playBounce() {
        setTimeout(fadeOutDialog, "${notificationDisplayTimeMilis}");
    }
    and modified getCallbackScript method:
    effectBehavior.setCallback(new JQueryAjaxBehavior(this) {
    
        @Override
        public CharSequence getCallbackScript() {
            return "playBounce()";
        }
    });
    Additionally to execute playBounce() from notifier.js we need to register it on our HTML page and pass arguments  ${dialogContainerId} and ${notificationDisplayTimeMilis}
    We will create JavaScriptTemplate as global variable in Notifier class, and overwrite renderHead  method which will append JavaScript into page header and also will set required properties:
        private JavaScriptTemplate notifierJs = 
          new JavaScriptTemplate(new PackageTextTemplate(Notifier.class, "notifier.js"));
    
        @Override
        public void renderHead(IHeaderResponse response) {
            Map<String, String> cssVariables = new HashMap<String, String>();
            cssVariables.put("dialogContainerId", dialogContainerId);
            cssVariables.put("notificationDisplayTimeMilis", 
                       Integer.toString(config.getBounceTimeMilis()));
            response.renderString(notifierJs.asString(cssVariables));
        }

    Monday, May 21, 2012

    Apache HTTP Commons and Cookie support for REST Services

    Apache HTTP commons is a framework for managing client HTTP connections - compared to standard Java Sockets it offers easier way to handle persistent connections, pooling, and high level socket API. It also support cookies - and I would like to concentrate on this subject now, especially in REST context.

    This is the typical way how most Java applications are using HTTP client. 
    public class RestClient {
    
        static HttpClient httpClient = null;
        static {
            ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
            httpClient = new DefaultHttpClient(cm);
        }
    
        public HttpResponse executeGet(URI url) throws Exception {
            return httpClient.execute(new HttpGet(url));
        }
    }
    For the most cases it is also a preferred way - HttpClient is thread save, and keeping single instance saves resources and increases performance.

    Bu there is a catch, if your have a multi-thread server application, which shares single instance of HttpClient and you have to also manage cookies.
    Multiple threads use single HttpClient to connect to different URLs at the same time - HttpClient is thread save, so this is allowed - but have you checked how DefaultHttpClient manages cookies? It simulates browser, but in our case this browser is being used simultaneously by several users....

    HttpClient executes call against remote REST service and in response it receives a Cookie - this Cookie is valid for given domain and path and our request was executed on concreate URL - everything looks normal. When we use the same instance of HttpClient to execute another call on the same URL it will send back cookies, that were returned by previous response. If cookies were issued for sub-domain or root path, they will be also send. This is the way how normal browser would behave. And here is a catch! Our HttpClient behaves like browser but we are using it in multi-thread environment, where we communicate with many different services within different scopes - now this can have advantages, but it can be also source for serious problems.

    Lets consider few scenarios - we will use as example a small application which executes calls for different users, each one is identified by integer ID (URI part).

    Scenario A  - cookies with root path
    HttpClient client sends request to http://registration.foo.com/register/234234, as response it receives some data and also cookie:

    Set-Cookie: USER_ID=234234; Expires=Thu, 01 Jan 2049 00:00:01 GMT; Path=/; Domain=.foo.com

    Request above stored cookie in HttpClient instance - its CookieStore exactly. Some time later the same instance of HttpClient is being used to execute following request: http://registration.foo.com/register/333222. Since domain and path for request match, response to this request will forward cookie which was set by previous call.
    The question is - do you really wanted to send this cookie back within this response (different User ID in URL)?
    Actually we have just used standard HttpClient and the rest was caused by service that we've called - it set cookie on wrong path, which did not contain  User ID. But still, this might be an issue - depends how this cookie will be interpreted - it might be used as User ID instead of ID from URL (nasty, but hey - it's REST - there are no rules).

    Scenario B - identical URL for different context (users)
    We call REST service which uses for all methods the same URL, User IDs are part of PUT/POST request's body. In this case our multi-thread application will use the same URL to execute calls for different users. HttpClient will send back all cookies for each request! Message body contains different User ID, but this is not relevant for CookieStore - only URL matters. Now imagine what happens when our REST interface will try to use cookie to open HTTP session - yes - we would mix up sessions.



    Using single HttpClient is in general good idea, but we have to be careful when it comes to cookies. Most REST services do not use them, but in this case we should simply disable cookie support, just to be sure.

    We can also create new instance of HttpClient for each request (conversational state). This is just fine, until you use shared ThreadSafeClientConnManager instance for each new HttpClient.


    Monday, May 14, 2012

    Wicket - Notification Dialog Component

    In previous post I've given example of Info Dialog, which is being triggered trough AJAX request, shows notification message over current HTML page, bounces few times and finally disappears.
    Java Code below contains the same dialog, but this time it's being re-factored to reusable component - the Notifier.

    The Notifier can be included in parent page for all other pages, this parent page will have show-dialog method, which will forward calls to our Notifier panel.


    Abstract parent class for all pages - MyParentPage.java

    public abstract class MyParentPage extends WebPage {
    
      private Notifier notifier;
    
      public MyParentPage() {
        notifier = new Notifier("notifierDialog", new NotifierConfig());
        add(notifier);
      }
    
      protected void showNotification(AjaxRequestTarget target, String infoHeader,
              String infoContent) {
        notifier.showNotification(target, infoHeader, infoContent);
      }
    }


    MyParentPage.html

    <html>
    <body>
      <div wicket:id="notifierDialog" />
      <div class="xyz"></div>
      <wicket:child />
    </body>
    </html>


    Notifier Component - Notifier.java

    /**
     * Notify Dialog component - add this panel to any wicket page in order to support ajax
     * notifications.
     * 
     * Integration example:
     * 
     * 1) Add Notifier to markup in your WebPage or Panel
     *    Notifier notifier = new Notifier("notifierDialog", new NotifierConfig());
     *    add(notifier);
     * 
     * 2) Add Notifier as div in corresponding HTML page - on the top of the page
     *    <div wicket:id="notifierDialog" />
     *  
     * 3) In order to show info message call:
     *    #createNotifierMessage(WebMarkupContainer)
     * 
     * @author mmiklas
     */
    public class Notifier extends Panel {
    
      /** Panel configuration */
      private NotifierConfig config;
    
      /** Parent for all display widgets in this dialog */
      private WebMarkupContainer dialogContainer = null;
    
      /** HTML ID of {@link #dialogContainer} */
      private String dialogContainerId = null;
    
      /** Dialog header model - use it to replace dialog's header message */
      Model<String> headerModel = null;
    
      /** Dialog content model - use it to replace dialogs content text */
      Model<String> messageModel = null;
    
      /**
       * Displays notification dialog with given header and message.
       * <p>
       * Dialog display command is being rendered as AJAX response
       * {@link AjaxRequestTarget#appendJavaScript(CharSequence)}. This response contains
       * dialog body, which will replace currently empty "notifier"-div, and also jquery
       * code, which plays bounce effect and hides dialog after one second.
       */
      public void showNotification(AjaxRequestTarget target, String header, String message) {
        Validate.notNull(target, "target");
        Validate.notNull(header, "header");
        Validate.notNull(message, "message");
    
        // update text models
        headerModel.setObject(header);
        messageModel.setObject(message);
    
        // replace empty #notifier with real content
        target.add(dialogContainer);
        dialogContainer.setVisible(true);
    
        // after setting dialog to visible play bounce effect
        JQueryEffectBehavior effectBehavior = new JQueryEffectBehavior(dialogContainerId,
                "bounce", config.getBounceTimeMilis());
    
        // dialog should disappear after one second - I did not
        // find any better way to add callback java script.
        effectBehavior.setCallback(new JQueryAjaxBehavior(this) {
    
          @Override
          public CharSequence getCallbackScript() {
            String fadeOut = "function(){$('" + dialogContainerId + ":visible').fadeOut();}";
            String callbackScript = "setTimeout(" + fadeOut + ", "
                    + Long.toString(config.getNotificationDisplayTimeMilis()) + ");";
            return callbackScript;
          }
    
          @Override
          protected JQueryEvent newEvent(AjaxRequestTarget target) {
            return null;
          }
        });
    
        target.appendJavaScript(effectBehavior.toString());
      }
    
      public Notifier(String id, NotifierConfig config) {
        super(id);
        Validate.notNull(config, "config");
        this.config = config;
    
        // div containing notify dialog
        dialogContainer = createDialogContainer();
        add(dialogContainer);
    
        // HTML ID for java script references
        dialogContainerId = "#" + dialogContainer.getMarkupId();
    
        // initialize jquery
        initEffectLib(dialogContainerId);
    
        // labels building info dialog
        headerModel = createNotifierHeader(dialogContainer);
        messageModel = createNotifierMessage(dialogContainer);
      }
    
      /**
       * @return body of the info dialog. HTML ID: "notifierMessage"
       */
      private Model<String> createNotifierMessage(WebMarkupContainer dialogContainer) {
        Model<String> model = new Model<String>();
        Label notifierMessage = new Label("notifierMessage", model);
        dialogContainer.add(notifierMessage);
        return model;
      }
    
      /**
       * @return header of the info dialog. HTML ID: "notifierHeader"
       */
      private Model<String> createNotifierHeader(WebMarkupContainer dialogContainer) {
        Model<String> model = new Model<String>();
        Label notifierHeader = new Label("notifierHeader", model);
        dialogContainer.add(notifierHeader);
        return model;
      }
    
      @Override
      protected void onBeforeRender() {
        super.onBeforeRender();
    
        // showNotification(....) renders #notifier (div) with info dialog
        // content. Java script will hide this dialog on client side after one second
        // (callback after bounce effect).
        // Page refresh would re-render whole HTML page, this would include in this case
        // also #notifier containing recent dialog - wicket component remembers last ajax
        // update on #notifier - and this is the whole dialog.
        //
        // Setting visibility to false on #notifier ensures, that old dialog will not
        // re-appear on page refresh
        dialogContainer.setVisible(false);
    
      }
    
      /** Initializes jquery effects library */
      private void initEffectLib(String infoDialogId) {
        add(new JQueryBehavior(infoDialogId, "effect"));
      }
    
      /**
       * @return hidden dialog container. It must be rendered as empty div, in order to
       *         replace it with info dialog content
       */
      private WebMarkupContainer createDialogContainer() {
        WebMarkupContainer container = new WebMarkupContainer("notifier");
        container.setOutputMarkupId(true);
        container.setOutputMarkupPlaceholderTag(true);
        container.setVisible(false);
        return container;
      }
    }
    


    Notifier Config Class

    public class NotifierConfig {
    
      private int notificationDisplayTimeMilis = 1000;
    
      private int bounceTimeMilis = 500;
    
      public int getNotificationDisplayTimeMilis() {
        return notificationDisplayTimeMilis;
      }
    
      public void setNotificationDisplayTimeMilis(int notificationDisplayTimeMilis) {
        if (notificationDisplayTimeMilis < 0) {
          return;
        }
        this.notificationDisplayTimeMilis = notificationDisplayTimeMilis;
      }
    
      public int getBounceTimeMilis() {
        return bounceTimeMilis;
      }
    
      public void setBounceTimeMilis(int bounceTimeMilis) {
        if (bounceTimeMilis < 0) {
          return;
        }
        this.bounceTimeMilis = bounceTimeMilis;
      }
    
    }


    Notifier.html

    <!DOCTYPE html>
    <html xmlns:wicket="http://wicket.apache.org">
    
    <wicket:head>
        <wicket:link>
            <link rel="stylesheet" type="text/css" href="notifier.css" />
        </wicket:link>
    </wicket:head>
    
    <body>
        <wicket:panel>
            <div wicket:id="notifier" class="notifier-content">
                <div wicket:id="notifierHeader" class="notifier-header">Message Header</div>
                <div wicket:id="notifierMessage" class="notifier-message">Message Body Text</div>
            </div>
        </wicket:panel>
    </body>
    </html>


    notifier.css

    .notifier-content {
        font-size: 12px;
        height: 100px;
        width: 240px;
        padding: 4px;
        position: fixed;
        background-color: #EDEDED;
        border-color: #BFBFBF;
        border-width: 1px;
        border-style: solid;
        border-radius: 4px;
    }
    
    .notifier-header {
        background-color: #F5A729;
        border-color: #E78F08;
        border-style: solid;
        border-width: 1px;
        color: white;
        font-weight: bold;
        border-radius: 4px;
        margin: 0;
        padding: 4px;
        text-align: center;
    }
    
    .notifier-message {
        padding-top: 6px;
    }

    Friday, May 11, 2012

    Memcached Spring integration

    This is very simple example showing how to integrate Spring with memcached.

    MemcachedClientFactoryBean is a Spring factory, which creates instance of MemcachedClient. Client class manages connections to memcached server farm, and takes care of .... mostly everything that is required for daily usage ;)

    Configured Transcoder serializes Java objects - they are available on memcached server in binary form.

    Spring bean below has single injection -  "memcached.client", this is the bean name of the factory, but spring recognises, that injected bean is a factory and does not inject factory itself, but uses it to create Bean instance - in this case memcached client.
    <?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:context="http://www.springframework.org/schema/context"
    
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context.xsd">
    
        <bean id="memcached.client" class="net.spy.memcached.spring.MemcachedClientFactoryBean">
            <property name="servers" value="host1:1122,host2:1122" />
            <property name="protocol" value="BINARY" />
            <property name="transcoder">
                <bean class="net.spy.memcached.transcoders.SerializingTranscoder" />
            </property>
            <property name="locatorType" value="ARRAY_MOD" />
            <property name="opTimeout" value="2000" />
            <property name="failureMode" value="Cancel" />
            <property name="useNagleAlgorithm" value="false" />
            <property name="timeoutExceptionThreshold" value="20" />
        </bean>
    </beans> 
    @Named
    public class MemcachedSpringBeanExample {
    
        private MemcachedClient memcached;
    
        @Inject
        protected MemcachedSpringBeanExample(@Named("memcached.client") MemcachedClient memcached) {
            this.memcached = memcached;
        }
    
        public void doSomething(UasAccountId uasAccountId, LastLoginHistory histiry) {
            memcached.add("my_bean_key", 2000, new Object[] { "val1", "val2" });
        }
    }

    Wednesday, May 9, 2012

    Wicket - disappearing Notification Dialog with bounce effect (jquery)


    The example below displays notification dialog, which appears over HTML content, bounces few times and finally disappears. There is also small CSS to give it some nice look.
    Such dialog can be used as a central point for asynchronous application notifications.

    The implementation is based on single Wicket Web Page - this should be redesigned to reusable component, but simple page is usefull to get an idea.

    At the beginning the dialog is hidden - Wicket Web Markup Container is being rendered as empty div (effectDialog).
    Clicking on "Show Dialog" button sends Wicket Ajax Event to the server, and as response browser receives new HTML part, which replaces empty effectDialog. This new HTML code contains our Info Dialog, and also jQuery code. This code will play bounce effect once dialog is painted, and hide it after one second.

    
    

    Java Code

    public class FeedbackWebPage extends WebPage {
    
      public FeedbackWebPage() {
        String infoHeader = "Info Header";
        String infoContent = "Variables containing text content for our dialog "
            + "should be extracted to proper Wicket Model - we keep it simple"
            + " for demonstration proposals";
    
        // div containing info dialog
        final WebMarkupContainer infoDialog = new WebMarkupContainer("effectDialog");
    
        // hide dialog, but leave empty HTML tag in order to display it later
        infoDialog.setOutputMarkupId(true);
        infoDialog.setOutputMarkupPlaceholderTag(true);
        infoDialog.setVisible(false);
        add(infoDialog);
    
        // HTML ID for java script references
        final String infoDialogId = "#" + infoDialog.getMarkupId();
    
        // initialize jquery
        add(new JQueryBehavior(infoDialogId, "effect"));
    
        // labels building info dialog
        Label feedbackHeader = new Label("feedbackHeader", infoHeader);
        infoDialog.add(feedbackHeader);
        Label feedbackMessage = new Label("feedbackMessage", infoContent);
        infoDialog.add(feedbackMessage);
    
        // submit button - it will show our dialog
        Form<Void> form = new Form<Void>("form");
        add(form);
        form.add(new AjaxButton("open-dialog", form) {
    
          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
    
            // replace empty #effectDialog with real content
            infoDialog.setVisible(true);
            target.add(infoDialog);
    
            // after setting dialog to visible play bounce effect
            JQueryEffectBehavior effectBehavior = new JQueryEffectBehavior(infoDialogId,
                "bounce", 500);
    
            // dialog should disappear after one second 
            effectBehavior.setCallback(new JQueryAjaxBehavior(this) {
    
              @Override
              public CharSequence getCallbackScript() {
    
                // add timer, to hide dialog after one second
                // TODO move this JavaScript to notifier.js (next blog post)
                String callbackScript = "setTimeout(function(){$(\"" + infoDialogId
                    + ":visible\").fadeOut();}, 1000);";
                return callbackScript;
              }
    
              @Override
              protected JQueryEvent newEvent(AjaxRequestTarget target) {
                return null;
              }
            });
    
            String jsEffect = effectBehavior.toString();
            target.appendJavaScript(jsEffect);
          }
    
          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
          }
        });
    
      }
    }
    

    HTML Page - FeedbackWebPage.html

    <!DOCTYPE html>
    <html xmlns:wicket="http://wicket.apache.org">
    
    <wicket:head>
        <wicket:link>
            <link rel="stylesheet" type="text/css" href="feedbackWebPage.css" />
        </wicket:link>
    </wicket:head>
    
    <body>
        <div wicket:id="effectDialog" class="ed-content">
            <div wicket:id="feedbackHeader" class="ed-header">Message Header</div>
            <div wicket:id="feedbackMessage" class="ed-message">Message Body Text</div>
        </div>
        <table border="1">
            <tr><th>COL1</th> <th>COL2</th> <th>COL3</th> </tr>
            <tr><td>value 1</td> <td>test message</td> <td>some more text</td></tr>
            <tr><td>value 1</td> <td>test message</td> <td>some more text</td></tr>
            <tr><td>value 1</td> <td>test message</td> <td>some more text</td></tr>
            <tr><td>value 1</td> <td>test message</td> <td>some more text</td></tr>
            <tr><td>value 1</td> <td>test message</td> <td>some more text</td></tr>
            <tr><td>value 1</td> <td>test message</td> <td>some more text</td></tr>
            <tr><td>value 1</td> <td>test message</td> <td>some more text</td></tr>
        </table>
        <form wicket:id="form">
            <button wicket:id="open-dialog">Show Dialog</button>
        </form>
    </body>
    </html>

    CSS - feedbackWebPage.css

    .ed-content {
        font-size: 12px;
        height: 100px;
        width: 240px;
        padding: 4px;
        position: fixed;
        background-color: #EDEDED;
        border-color: #BFBFBF;
        border-width: 1px;
        border-style: solid;
        border-radius: 4px;
    }
    
    .ed-header {
        background-color: #F5A729;
        border-color: #E78F08;
        border-style: solid;
        border-width: 1px;
        color: white;
        font-weight: bold;
        border-radius: 4px;
        margin: 0;
        padding: 4px;
        text-align: center;
    }
    
    .ed-message {
        padding-top: 6px;
    }

    POM.XML - dependencies

    <dependency>
        <groupId>org.apache.wicket</groupId>
        <artifactId>wicket-core</artifactId>
        <version>1.5.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.6.2</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.6.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-servlet-api</artifactId>
        <version>7.0.22</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.1</version>
    </dependency>
    <dependency>
        <groupId>com.googlecode.wicket-jquery-ui</groupId>
        <artifactId>jquery-ui-core</artifactId>
        <version>1.1</version>
    </dependency>