Sunday, November 11, 2012

Contact Application on Spring by Example

I've just updated Spring by Example to have a multi-module Contact Application. It's meant to be an example of an architecture pattern to follow for larger applications.

The DAO module has the DB schema, JPA entities, and uses Spring Data JPA repositories. It also has a Spring Profile for HSQL DB and PostgreSQL. The tests and webapp default to using the in memory database and PostgreSQL is meant to be used in the production deployment of the webapp.

The WS Beans module are JAXB beans generated from XSDs. They are generated to have a fluent API (ex: new Person.withId(1).withFirstName("John")) and are meant to provide an easy way to create different models for external APIs that can be easily serialized to JSON & XML.

The Services module uses the WS Beans (JAXB Beans) for it's main model and for any APIs. It is meant to be the layer where all business logic is located. It converts to and from the JPA entities & WS Beans using Dozer. It configures Spring's transactional support and Spring Security.

REST Services exposes the Services layer and provides clients & controllers for all REST APIs. All APIs can be exposed over JSON & XML. It has the standard JSON media type and a custom one that also includes class information for more complex data models.

The contact webapp has a standard JSP UI, Sencha ExtJS, and also a Sencha Touch UI.

There is a shared test module to keep inter-module dependencies less complex. The DAO, Services, and REST Services layer each have an abstract test base that creates a shared test context. The DAO and Services both create an in memory DB, and use Spring's transactional test framework to rollback transactions after each test runs. The REST Services module creates an in memory DB and an embedded Jetty instance. The embedded Jetty has it's own Spring context, separate from the test one. The embedded Jetty context loads as much as possible of the production Spring configuration, and the test context just loads the REST clients. You may also want to look at Spring Test MVC for testing controller, but the Contact Application approach runs very quickly and is really a full integration test.

Friday, August 24, 2012

Spring Data JPA Examples on Spring by Example

I've just updated Spring by Example to have two Spring Data JPA examples. One has basic repository use and shows how to make some custom queries, and the other one shows how to use Spring Data JPA auditing. All of the main webapps using JPA were updated to use Spring Data JPA and all JPA examples were updated to use Hibernate 4.1. I ran into issues updating the Hibernate template examples, so they will stay on Hibernate 3.6.

There were other miscellaneous updates. The AJAX tiles work in the web flow examples wasn't working so I removed it for now.

I'll be continuing to work on REST and UI examples, using ExtJS and Sencha Touch.

Saturday, August 18, 2012

SpringOne & Spring By Example Update

I've just updated Spring by Example to Spring 3.1 and Java 6. The new Spring by Example Repository is on GitHub.

Here are some general comments about the latest release. The Maven group and artifact IDs have been changed back to standard Maven naming and also all project dependencies (no OSGi ones in standard examples). The project is now one large multi-module project structure to make it easier to maintain and upgrade releases. Originally the goal was to have standalone projects so it was easier for someone to get started, but I don't have time to maintain the project this way anymore.

The GWT examples have been removed from the documentation and are not in git. If I have time in the future I may add them back, but I'll be focusing on some standard JS UI examples. The Spring dm Server (OSGi) examples have not been updated, but are still available in the documentation. They still located in Subversion since I won't actively try to maintain them anymore. Spring by Example JDBC has been removed and all projects (except for OSGi ones) have been changed to use the Spring JDBC Custom Namespace. Between the this namespace and Spring Data JPA, nothing is really necessary in this module. I'll be starting on a Spring Data JPA example next week.

Friday, January 20, 2012

Spring JAXB with CDATA Elements


I wanted to configure the Jaxb2Marshaller to support CDATA elements. This example works with Spring 3.1 and Java 6, using the Java 6 restricted XML parser classes to configure the CDATA elements.



<bean id="marshaller" class="org.springbyexample.marshaller.CdataJaxb2Marshaller">
     <property name="cdataElements">
         <list>
             <value>^value</value>
         </list>
     </property>
...


import java.io.IOException;
import java.io.OutputStream;

import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.XmlMappingException;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.oxm.mime.MimeContainer;


public class CdataJaxb2Marshaller extends Jaxb2Marshaller {
    
    private String[] cdataElements;
    
    public String[] getCdataElements() {
        return cdataElements;
    }

    public void setCdataElements(String[] cdataElements) {
        this.cdataElements = cdataElements;
    }
    
    @Override
    public void marshal(Object graph, Result result, MimeContainer mimeContainer) throws XmlMappingException {
        if (ArrayUtils.isNotEmpty(cdataElements)) {
            try {
                Marshaller marshaller = createMarshaller();
    
                com.sun.org.apache.xml.internal.serialize.XMLSerializer serializer =
                        createXMLSerializer(cdataElements, ((StreamResult)result).getOutputStream());
                marshaller.marshal(graph, serializer.asContentHandler());
            } catch (IOException e) {
                throw new MarshallingFailureException(e.getMessage(), e);
            } catch (JAXBException ex) {
                throw convertJaxbException(ex);
            }
        } else {
            super.marshal(graph, result);
        }
    }

    @SuppressWarnings("restriction")
    private com.sun.org.apache.xml.internal.serialize.XMLSerializer createXMLSerializer(String[] cDataElements, OutputStream cOut) {
        // This code is from a sample online: http://jaxb.java.net/faq/JaxbCDATASample.java
        // configure an OutputFormat to handle CDATA
        com.sun.org.apache.xml.internal.serialize.OutputFormat of = new com.sun.org.apache.xml.internal.serialize.OutputFormat();

        // specify which of your elements you want to be handled as CDATA.
        // The use of the '^' between the namespaceURI and the localname
        // seems to be an implementation detail of the xerces code.
        // When processing xml that doesn't use namespaces, simply omit the
        // namespace prefix as shown in the third CDataElement below.
        of.setCDataElements(cDataElements); //

        // set any other options you'd like
        of.setPreserveSpace(true);
        of.setIndenting(true);
        of.setPreserveSpace(false);

        // create the serializer
        com.sun.org.apache.xml.internal.serialize.XMLSerializer serializer = new com.sun.org.apache.xml.internal.serialize.XMLSerializer(of);
        serializer.setOutputByteStream(cOut);

        return serializer;
    }

}

Friday, December 25, 2009

Spring 3.0 & Maven

I wanted to go over the process of upgrading the build from Spring 2.5 to Spring 3.0 (3.0 release announcement) using Maven for the build process. For almost all applications from basic dependency injection to webapps, and even enterprise applications with Spring Web Services and Spring Integration all upgraded without any issues.

I did change all the builds to use the SpringSource Enterprise Bundle Repository. It has all the Spring projects and also repackaged versions of many other open source ones. SpringSource did this to make all the artifacts OSGi enabled and also corrected any errors in dependencies where possible. It isn't necessary to use this repository and all Spring projects are also deployed to the main Maven repository tool.

I primarily switched so the projects could be more easily imported into an OSGi environment if someone needed to the SpringSource Enterprise Bundle Repository (EBR) and to avoid any dependency resolution issues since some artifacts will need to be resolved from the EBR.

Keith Donald, from SpringSource, did a blog discussing using Maven with Spring 3.0. It's called Obtaining Spring 3 Artifacts with Maven and is definitely worth reading to understand things in more detail.

Thursday, December 24, 2009

Spring & Spring by Example


I've been working a lot on getting Spring by Example updated for Spring 3.0. A Simple Grails Webapp was also added to this release.

Almost everything is upgraded except for the AspectJ LTW example, GWT ones, and OSGi. The AspectJ one, I've had an odd problem that I've updated everything to use the Spring Repository, but when I change it to from Spring 2.5.6 to 3.0, the weaving stops working. No errors and no success resolving the issues, but I will keep working on it. I had trouble with the GWT webapps too, but I think it's mainly build related. I'll probably start over with a new project using GWT 2.0 and build the examples back up. For the Spring dm Server (OSGi) ones, I just haven't had time. I don't think there will be a problem upgrading them.

Everything is versioned on the site, so all past site releases and examples are available (Spring by Example 2.5.x, which is version 1.0.3). Just follow the subversion instructions at the end of the examples to checkout the correct version of the project the example describes. If you're ever not sure what version of something the example uses, check the 'Project Information' section at the end of the example and/or the Maven POM.

I have a Spring Roo example in progress that is the basis for a simple person and address example. Ideally I'd like to even use Roo to replace many of the webapp examples and/or have as much of them generated as possible. I'd also like to spend time redoing the web services add-ons for Roo and get them into a releasable state, but I just haven't had the time. I'm hoping it will fit in with a future project soon, so maybe it will get done.

I also plan on getting SpEL, REST, and some other examples together for the website. I've also done a lot of Flex work over the last year, so I'd really like to do some more advanced Flex examples and especially a basic messaging example and security example.

Monday, December 14, 2009

Spring Roo, SpringOne 2009, Spring by Example

I haven't been active on my blog or Spring by Example for a long time. I was just really busy. In that time I've been working with Flex, Spring BlazeDS Integration, Spring MVC, Spring Web Flow, Spring Roo, and other things.

Spring Roo was very useful. I made my own add-ons that generated web services based on a JPA bean and even the matching ActionScript class. I'm going to try working on a better version based on the new Spring Roo add-on format when I have time. What I did so far is checked into subversion. It was developed against Spring Roo 1.0.0.RC1 before there was standardized add-on format. I was very rushed when I did this, so it's functional but very basic and needs to be redone.

SpringOne 2009 in New Orleans was good. A lot of interesting presentations and nice getting to see different people again. The cloud presentation in the keynote was very interesting. Some of the improvements in Spring MVC that are in Spring 3.0 are quite nice. There is JSR-303 (Bean Validation) support, Type Conversion and Validation (blog by Keith Donald), REST support, and an MVC namespace for reduced configuration. Some of the SpEL (Spring EL) integration with other projects like Spring Integration and Spring Security look really useful. SpringOne is a really good conference and I'm glad I went.

I've been working for over a week on upgrading Spring by Example's projects to Spring 3.0.0.RC3. Most have upgraded without any issues, although I'm having trouble upgrading the GWT ones. I'm going to probably leave them and the dm Server (OSGi) examples as they are for now and finalize the other examples, double check everything is working, and update the documentation so I'll be ready for a release for the Spring 3.0 final release. The webapps (other than GWT & dm Server ones) have not only been upgraded to Spring 3.0, but have also been upgraded to JPA and following Spring MVC best practices as much as possible if they weren't already. All of them were changed to use the Spring MVC namespace which reduced their configuration slighlty. Also the applications with security had their login/logout pages changed to be served through Tiles and support i18n. When I have time I'd like to change the webapps to use jspx and use RESTful URLs.

I'm hoping to get a release of Spring by Example out in the next few days. Then continue working on everything else and possibly have another release before the end of the year. I'd also like to get a SpEL and Spring MVC REST examples added to the site.