Monday, July 14, 2014

Easy Spring AOP

This article shows how to create aspects in Spring, using Spring AOP.

Quick notes:
  1. Spring AOP is not a fully blown AOP framework (read these few paragraphs). 
  2. It uses AspectJ annotations and pointcut expressions.
  3. Only join point is method execution.
  4. Since Aspects are actually Spring beans, you can inject stuff into it (I prefer using @Autowire for DI).
  5. Spring AOP is a proxy based implementation. This is the most common implementation outside of Spring. Spring will create a proxy for any bean that is being advised. This is called auto-proxying.

Personally always try to use 
  1. Spring's Classpath scanning (aka component scanning)

Ok. To create an aspect I need to:
  1. Create a Spring bean.
  2. Tell Spring that this bean is a Spring AOP aspect
  3. Define the pointcuts. I usually do this in the bean itself, but you can define the pointcuts in its own class.
  4. Define the advices. These will be methods in the bean.

Create a Spring bean
There are many ways to do it. I prefer "annotation-based configuration". So its just a simple annotation (and the xml config to enable annotation-based configuration. I include it here, but its beyond the scope of this document so go read up on it by yourself).

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <mvc:annotation-driven/>
    <context:component-scan base-package="net.gerardsetho.web"/>

</beans>


Here is my MyAnnotationClass. Note the @Component annotation
package net.gerardsetho.web;

import org.springframework.stereotype.Component;

@Component
public class MyAnnotationClass {
}


Tell Spring that this bean is a Spring AOP aspect
So Spring now thinks my class is a normal Spring singleton. We need to tell Spring that its also a Spring AOP aspect. There are 2 ways to do it. I prefer to use "@AspectJ aspects", which Spring recognises. This is done by adding a single line in the XML configuration:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation=".....">

    <mvc:annotation-driven/>
    <context:component-scan base-package="net.gerardsetho.web"/>


    <!--
    This tells Spring to look for AspectJ annotations in the source code, 
    and create aspects for them.
    It also tells Spring to create proxies for (other) beans which are 
    being advised.
    -->
    <aop:aspectj-autoproxy/>

</beans>


Define the pointcuts
I usually define the pointcuts in the Aspect class itself. I guess one could put them in another class, but I rarely needed to do so.

Defining pointcuts is done using the @Pointcut annotation (its an AspectJ annotation). Note that Spring AOP only understand method-invocation join points. So if you need to advise field-get or field-set join points, you need to use a full fledged AOP framework like Aspect J.

Moving on. I usually like to define a pointcut that matches every method in an advised class. 1 pointcut per class. I think it makes things clearer. Then I make another join point for the methods in the class. The code should make this clear.

@Component
@Aspect
public class MyAnnotationClass {


    /**
     * Pointcut that describes all join points (in Spring, 
     * the only join points are method invocations)
     * in the class / interface MyController.
     */
    @Pointcut( "target(net.gerardsetho.web.MyController)")
    private void MyControllerMethods() {}


    /**
     * any method called home,
     * with any number of arguments
     * which returns anything
     */
    @Pointcut( "execution(* home(..))")
    private void entrypoint() {}

}

Here are some examples of other types of pointcuts.


Define the advices
We can combine different pointcuts to define an advice. The below combines (logical AND) the above 2 pointcuts, and creates an advice to print to System.out. It uses @Before, but one can use any number of supported advice types.

    @Before( "MyControllerMethods() && entrypoint()" )
    public void logEntryPoints() {

        System.out.println( "logging entry point." );

    }

In addition to other types of advice, one can also access the parameters of the advised methods. Let me know in the comments if you're interested to know about that.



Tuesday, February 25, 2014

Easy Spring MVC, Maven and Intellij IDEA

Its odd that there isn't a Spring MVC Maven archetype. 

But creating a Spring MVC from one of the standard Maven archetypes is easy, and there are many tutorials online to do it. I've done it myself many times. 

I created a video that shows how to do it. I wanted to try to create a skeleton Spring MVC Maven project in Intellij IDEA in 10 minutes (spoiler: I couldn't). I wanted to do it without referring to any online articles or tutorial. So even though there aren't any Spring MVC archetypes, its really easy to do so yourself.

Here's the video:




Thursday, February 6, 2014

Correct way to use DB sequences in JPA

I have a sequence defined in an existing database (mine is PostgreSQL) for the primary key. I want to use JPA (implemented by Hibernate) to use this sequence when persisting (inserting) a new object.

The below is the correct way to do it.


First, basic JPA stuff. The column name.

Next, we need to have 2 annotations @GeneratedValue and @SequenceGenerator. With the former referring to the latter. It looks a little redundant to me, but hey... I'm just a programmer.

Third, we specify the the sequence name (as in the DB). We need to include the schema as well.

Finally, we specify the increment.

ps. I seem to need to restart the server (Glassfish 3) almost each time I make changes to JPA annotations (it was giving me "XxxXxx class is not recognized by Java persistance" etc etc). So if the above doesn't work for you, try restarting the server first.

Friday, January 24, 2014

Creating a Sencha client side app with IntelliJ IDEA and Maven

This assumes you already have a project open in IDEA. I use IDEA 13.

First create a new module. 


Type in a module name.


We will create a module from a Maven archetype (maven-archetype-webapp). In my case, the group id and artifact id aren't important.


IDEA creates the new module for us.


Second, this module will contain a Sencha GXT application, so we need to set up our dependencies. We edit our pom.xml to add in these dependencies. We are dependent on the Sencha jars, and the GWT jars (first 2 red arrows below). We also need the GWT Maven plugin, so we can compile the GWT app from IDEA (the 3rd arrow below).


Below is the text (for copy and paste purposes).
    <dependencies>
        <dependency>
            <groupId>com.sencha.gxt</groupId>
            <artifactId>gxt</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-user</artifactId>
            <version>2.5.1</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>uibinder</finalName>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>gwt-maven-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

I think its a little irritating that the archetype does not create a java folder for me. So I have to do that. And to tell IDEA that the folder contains all the Java source files and that it should compile all the source files. Doesn't IDEA already know this? Its the standard source location after all... Oh well... We create the folder.

And indicate to IDEA that its a source folder.

(select the module, then select the new folder java, and click the "Sources" button.)



Third, we now add a GWT module (which is basically a Xxxx.gwt.xml file, plus one or more entry point classes). IDEA will create the XML file, and 1 entry point class. If necessary, more entry points can be added later. It also creates an HTML and a CSS file which will load the (GWT-compiled) Javascript which will display the GWT module.


Choose a name for the GWT module.


Fourth, we need to "change" the GWT module to a GXT module. Some Sencha inherits and stylesheets do not work with the standard GWT ones. So we open the Xxxx.gwt.xml file and modify it for GXT (below: red box). Also, I like to add a rename-to attribute. If in the future I add RPC calls to the Sencha app, this attribute will be the URL that the AJAX calls to.

Fifth, most people use GWT development mode to do quick development. To do this in IDEA, we need to create a new configuration. We create a new GWT configuration (and give it any name). Make sure the correct project module is selected (if you have more than 1 like I do). And we also tell development mode to load all our GWT modules. 





We test the configuration: running the configuration will basically start a Jetty server that serves the GWT module (in development mode).
It works.



Finally we add a Sencha widget to make sure this works with Sencha.



Done.






























Friday, July 5, 2013

Using a Publish-Subscribe messaging pattern in Vaadin

The events system described by the Book of Vaadin is quite primitive. It's a standard Observer pattern (aka Listener pattern). 

Unfortunately, since the Listener requires access to the source object, this makes it highly coupled (the listener has to know about the source). 

What's worse is, in a practical sense, since Vaadin events do not "bubble" (not on the server side at least), its very difficult "get the handler to the required component" without violating all kinds of information hiding best practices.

What we really want is a publish-subscribe architecture that is similar to Parsley's in Flex.

GWT does provide a SimpleEventBus. And Vaadin does include this. And blogger Alex Tretyakov has here a great example of how to use it. As of this writing, its the best example out there.

Wednesday, July 3, 2013

Creating a Vaadin application using M2Eclipse (aka m2e) gives an error

I use M2Eclipse (and m2e-wtp) to create a vaadin-archetype-application. It works, but M2E keeps complaining about the below error.

"Plugin execution not covered by lifecycle configuration: com.vaadin:vaadin-maven-plugin:7.1.0:update-theme (execution: default, phase: generate-sources) "

Yes its a harmless error. But its irritating for an OCD like me. This is (probably) because m2e doesn't know about some of Vaadin's Maven goals:

  1. compile-theme
  2. update-theme
The way I solve let m2e know about it is:
  1. search the pom.xml for m2e's lifecycle config. Do a search for "org.eclipse.m2e".
  2. m2e will have tried to put some goals into vaadin-maven-plugin's plugin execution. e.g. <goal>resources</goal>
  3. put in the missing <goal>compile-theme</goal> and <goal>update-theme</goal>.
  4. update the Eclipse's Maven config. The easiest way is to quick fix ⌘1.

Tuesday, March 12, 2013

Dune HD "Error: file can't be played"

I recently got a "Error: file can't be played" when I tried to play a file in my Dune HD player (it was working less than 12 hours ago).

How I solved it was to re-flash my firmware. It doesn't seem to have any adverse effect besides wasting my time. Here's how I did it in my Dune HD.


  1. Go to "Setup -> Miscellaneous -> Firmware Upgrade"
  2. Select "Check Available Updates"
  3. It tells me "no new firmware version available" (If there is a new firmware, I'd suggest upgrading. If so, you can ignore the below steps.)
  4. Select "Show all versions".
  5. Select the current version (it stated there "current")
  6. Select "Upgrade"

Hths



Player: Dune HD Smart B1
Player purchased in: 2012
Player firmware: 121018_0846

NAS: Synology DS212