Featured FREE Whitepapers

What's New Here?


Android WebView CSS Support

Creating HTML applications can be a great way to cut down development time between two platforms. The trend today is to develop a web app for iOS (with varing amount of native code) and simply use the HTML, CSS, and Javascript on other platforms like Android. The process can work well, and it can save you considerable time while still having a nice, polished app on multiple platforms. There are a few pitfalls with the approach, though. One of the main troubles is developing for iOS first. You see, iOS has a great in-app brower. It has support for all of the latest HTML5 components, it fully supports CSS3, and it has great Javascript performance. The problem is, no other platform is near that level yet. This can create some issues when you are porting your HTML,CSS, and Javascript to other platforms, like Android. When following the pattern above, you should really develop for the lower platform first and then port to iOS. This way, you will have less development time lost to solving compabability issues. Some of these issues could be: Javascript DOM differences, CSS3 syntactical differences, and Javascript performance differences. Also, keep in mind that the usage of third party libraries, that may work great on iOS, may not work on other platforms. It may not even have an equivalent verison available. One thing to watch out for would be: -webkit-linear-gradient… versus -webkit-gradient… I’m sure that there are several other major differences between what is supported between Android and iOS. Once I find more, I’ll let you know. Reference: Android WebView CSS Support from our JCG partner Isaac Taylor at the Programming Mobile blog....

Java: Mergesort using Fork/Join Framework

The objective of this entry is to show a simple example of a Fork/Join RecursiveAction, not to delve too much into the possible optimizations to merge sort or the relative advantages of using Fork/Join Pool over the existing Java 6 based implementations like ExecutorService. The following is a typical implementation of a Top Down Merge sort algorithm using Java: import java.lang.reflect.Array;public class MergeSort { public static <T extends Comparable<? super T>> void sort(T[] a) { @SuppressWarnings('unchecked') T[] helper = (T[])Array.newInstance(a[0].getClass() , a.length); mergesort(a, helper, 0, a.length-1); } private static <T extends Comparable<? super T>> void mergesort(T[] a, T[] helper, int lo, int hi){ if (lo>=hi) return; int mid = lo + (hi-lo)/2; mergesort(a, helper, lo, mid); mergesort(a, helper, mid+1, hi); merge(a, helper, lo, mid, hi); }private static <T extends Comparable<? super T>> void merge(T[] a, T[] helper, int lo, int mid, int hi){ for (int i=lo;i<=hi;i++){ helper[i]=a[i]; } int i=lo,j=mid+1; for(int k=lo;k<=hi;k++){ if (i>mid){ a[k]=helper[j++]; }else if (j>hi){ a[k]=helper[i++]; }else if(isLess(helper[i], helper[j])){ a[k]=helper[i++]; }else{ a[k]=helper[j++]; } } }private static <T extends Comparable<? super T>> boolean isLess(T a, T b) { return a.compareTo(b) < 0; } } To quickly describe the algorithm – The following steps are performed recursively:The input data is divided into 2 halves Each half is sorted The sorted data is then mergedMerge sort is a canonical example for an implementation using Java Fork/Join pool, and the following is a blind implementation of Merge sort using the Fork/Join framework: The recursive task in Merge sort can be succinctly expressed as an implementation of RecursiveAction - private static class MergeSortTask<T extends Comparable<? super T>> extends RecursiveAction{ private static final long serialVersionUID = -749935388568367268L; private final T[] a; private final T[] helper; private final int lo; private final int hi; public MergeSortTask(T[] a, T[] helper, int lo, int hi){ this.a = a; this.helper = helper; this.lo = lo; this.hi = hi; } @Override protected void compute() { if (lo>=hi) return; int mid = lo + (hi-lo)/2; MergeSortTask<T> left = new MergeSortTask<>(a, helper, lo, mid); MergeSortTask<T> right = new MergeSortTask<>(a, helper, mid+1, hi); invokeAll(left, right); merge(this.a, this.helper, this.lo, mid, this.hi); } private void merge(T[] a, T[] helper, int lo, int mid, int hi){ for (int i=lo;i<=hi;i++){ helper[i]=a[i]; } int i=lo,j=mid+1; for(int k=lo;k<=hi;k++){ if (i>mid){ a[k]=helper[j++]; }else if (j>hi){ a[k]=helper[i++]; }else if(isLess(helper[i], helper[j])){ a[k]=helper[i++]; }else{ a[k]=helper[j++]; } } } private boolean isLess(T a, T b) { return a.compareTo(b) < 0; } } MergeSortTask above implements a compute method, which takes in a array of values, split it up into two parts, creates a MergeSortTask out of each of the parts and forks off two more tasks(hence it is called RecursiveAction!). The specific API used here to spawn of the task is invokeAll which returns only when the submitted subtasks are marked as completed. So once the left and right subtasks return the result is merged in a merge routine. Given this the only work left is to use a ForkJoinPool to submit this task. ForkJoinPool is analogous to the ExecutorService used for distributing tasks in a threadpool, the difference to quote the ForkJoinPool’s API docs: A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute subtasks created by other active tasks (eventually blocking waiting for work if none exist) This is how the task of submitting the task to the Fork/Join Pool looks like: public static <T extends Comparable<? super T>> void sort(T[] a) { @SuppressWarnings('unchecked') T[] helper = (T[])Array.newInstance(a[0].getClass() , a.length); ForkJoinPool forkJoinPool = new ForkJoinPool(10); forkJoinPool.invoke(new MergeSortTask<T>(a, helper, 0, a.length-1)); } A complete sample is also available here: https://github.com/bijukunjummen/algos/blob/master/src/main/java/org/bk/algo/sort/algo04/merge/MergeSortForkJoin.java Reference: Mergesort using Fork/Join Framework from our JCG partner Biju Kunjummen at the all and sundry blog....

DAO layer – Generics to the rescue

Generics can be a powerful tool to create reusable code with the power of compile time verification (type safety..). Unfortunately I feel the main stream developers still afraid of it. However, in analogy to Hagrid’s spiders I would say that Generics are seriously misunderstood creatures… :-) I hope the following example will demonstrate how useful they can be. The Problem - DAO (Data Access Objects) classes have common methods such as save, update, delete, loadAll.. which are required in every DAO class. Writing a base class with these common methods and making every DAO object extend it, is simply not enough since each DAO class represents a different domain class and therefore the type used in the common methods’ signature is different (although implementation is similar), for example: class OrderDAO { //save method receive an Order public void save(Order order){....} //getAll method return Orders List public List<Order> getAll(){...} }class UserDAO{ //save method receive an User public void save(User user){....} //getAll method return Users List public List<User> getAll(){...} }How Generics can help us create a base class with a common implementation and yet, keep method signature type-safety? First, we need to define an interface with the common methods: /** * Base interface for CRUD operations and common queries */ public interface IDaoBase<T> { public List<T> loadAll(); public void save(T domain); public void update(T domain); public void delete(T domain); public T get(Serializable id); /** * Get list by criteria * @param detachedCriteria the domain query criteria, include condition and the orders. * @return * */ public List<T> getListByCriteria(DetachedCriteria detachedCriteria); public List<T> getListByCriteria(DetachedCriteria detachedCriteria, int offset, int size); } Please note that we utilize generics so each method signature has a type T, which in the implemented DAO classes, will be a concrete type, per domain. The second step is to create an abstract class which implements the common functionality: public abstract class DaoBase<T> extends HibernateDaoSupport implements IDaoBase<T> { private Class<T> entityClass; @Autowired public void setSession(SessionFactory sessionFactory){ this.setSessionFactory(sessionFactory); } public DaoBase() { entityClass = (Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; }public List<T> loadAll(){ return getHibernateTemplate().loadAll(entityClass); }public void delete(T domain) { getHibernateTemplate().delete(domain); }public void save(T domain) { getHibernateTemplate().saveOrUpdate(domain); }public void update(T domain) { getHibernateTemplate().merge(domain); } public T get(Serializable id) { T o = (T) getHibernateTemplate().get(entityClass, id); return o; }public List<T> getListByCriteria(DetachedCriteria detachedCriteria, int offset, int size) { return getHibernateTemplate().findByCriteria(detachedCriteria, offset, size); } public List<T> getListByCriteria(DetachedCriteria detachedCriteria) { return getHibernateTemplate().findByCriteria(detachedCriteria); } } And that’s it ! Take a minute or two to inspect how the base object implements a generic functionality with a type-safety manner. All we have to do when implementing a new DAO is: 1. Interface to extend the IDaoBase with a concrete type public interface DaoUser extends IDaoBase<User> {//<=Notice the User typing //Add any additional custom methods.. public User getbyUsername(String username); public User getbyEmail(String email); }2. Implementation to extend the DaoBase with a concrete type //This class has all the common methods, which are type safe for the User class @Repository("daoUser") public class DaoUserImpl extends DaoBase<User> implements DaoUser { //<=Notice the User typingpublic User getbyUsername(String username) { // concrete implmentation ... }So now you see how powerful it is to use generics. Hope it is now a bit less scary and more understood… Reference: DAO layer – Generics to the rescue from our JCG partner Gal Levinsky at the Gal Levinsky’s blog blog....

Client Reviews: From Waterfall to Agile

We are currently transforming a large organization with 200+ people to adopt new agile behaviors. The transformation started off with identifying 3 pilot projects to be the first adopters of agile skills and techniques.The 3 projects started their agile journey with creating a story map to organize and visualize their business requirements. The story mapping technique enabled the project teams to decompose their projects into features that can be managed independently. As a start, they used their current business requirements document and transformed it into a story map. The story map was then used as visual tool to drive discussions with business on feature creation and prioritization.After decomposing the project into features, the teams created their Kanban boards with policies to manage the flow of work through the system. The teams’ set up regular cadence for standup meetings to provide updates on tickets, raise and resolve risks, issues, and blockers.The new approach received positive feedback from business as a result of engaging them in more frequent discussions. Business is now working closely with project teams to get acquainted with the new tools and processes. Currently they have setup regular meetings with business to address business and IT perspectives on features and how they will be grouped into MMFs. The new processes and Kanban have provided project teams and business a collaborative and transparent approach to manage their projects.Below are pictures from project Kanban boards and the team’s feedback on the new process and Kanban.   Pilot Project 1“The story board has been instrumental in identifying gaps between the requirements and potential solution.” “Although our project is still very early in the Kanban process we have found definite value in the visual and collaborative aspects of the model.” “Having standups helps to ensure everyone on the team is familiar with the state of the project, what issues are currently open and also creates an opportunity for everyone to brainstorm and provide input when required.” “Main challenges that I have seen are firstly trying to learn and pilot the model in a medium/high complexity project (learning curve) as well as adjusting everyone’s views to how the project would be approached compared to a standard waterfall model.” “Trying to retrofit a project that started as waterfall is challenging e.g. high level requirements doc (updated, revised) in progress when Kanban training started; developing project plan with business partner who had not yet been exposed to Kanban, and moving forward adapting to Kanban technique.” “Learning and application happening at the same time (don’t feel there is sufficient time allowed in the project timeline to ‘practice’ techniques/adjust our processes before putting it in front of the client; making mistakes as part of our learning can affect our credibility, especially in a culture that traditionally is not failure/mistake-tolerant.”Pilot Project 2“One could easily understand the work flow and identify the bottleneck to re-distribute the work load.” “It makes work more interesting and more transparent.” “It also helps me to find where is my position in this project and the relation between my tasks and others, and who will be affected if the task cannot be delivered on time.” “The most challenging part is defining meaningful tasks (fine-grained) or feature sets and reduce the coupling (dependency) between tasks, which is the key part to make the whole workflow goes smoothly.” “Switching to Kanban in mid project hasn’t been easy. some overhead was encountered getting everyone up to speed but project timelines weren’t changed”Pilot Project 3“The daily standups promote communication between my peers.” “Helpful to identify road blocks and the opportunity to resolve more quickly.” “Using Kanban, we can trace the project activities, and find the bottleneck (blocker) in the different phases.” “Business stakeholders wanting to drive Kanban activities before they are fully understood. Often the business PM is not clear and causes confusion.” “Clarify the role and responsibilities of the Kanban Champion in relation to the Project, how they interact with business – this is not clear and is causing confusion.” “I feel that we have a challenge to get blocker removed quickly and efficiently, and define the delivery timeline/milestone for each MMF.”Reference: Client Reviews: From Waterfall to Agile from our JCG partner Alexis Hui at the Lean Transformation blog....

Testing Spring & Hibernate Without XML

I’m very keen on the improvements in Spring 3 that eventually let you move away from XML into plain Java configuration with proper support from IDE and compiler. It doesn’t change the fact that Spring is a huge suite and it sometimes finding the thing you need can take a while. XML-free unit tests around Hibernate are one such thing. I knew it was possible, but it took me more than 5 minutes to find all the pieces, so here I am writing it down. I am going to initialize all my beans in a @Configuration class like this: @Configuration @EnableTransactionManagement public class TestRepositoryConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) .setName("Nuts").build(); }@Bean public LocalSessionFactoryBean sessionFactoryBean() { LocalSessionFactoryBean result = new LocalSessionFactoryBean(); result.setDataSource(dataSource()); result.setPackagesToScan(new String[] { "pl.squirrel.testnoxml.entity" });Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); result.setHibernateProperties(properties); return result; }@Bean public SessionFactory sessionFactory() { return sessionFactoryBean().getObject(); }@Bean public HibernateTransactionManager transactionManager() { HibernateTransactionManager man = new HibernateTransactionManager(); man.setSessionFactory(sessionFactory()); return man; }@Bean public OrderRepository orderRepo() { return new OrderRepository(); } }… and my test can look like this: @RunWith(SpringJUnit4ClassRunner.class) @TransactionConfiguration(defaultRollback = true) @ContextConfiguration(classes = { TestRepositoryConfig.class }) @Transactional public class OrderRepositoryTest { @Autowired private OrderRepository repo;@Autowired private SessionFactory sessionFactory;@Test public void testPersistOrderWithItems() { Session s = sessionFactory.getCurrentSession();Product chestnut = new Product("Chestnut", "2.50"); s.save(chestnut); Product hazelnut = new Product("Hazelnut", "5.59"); s.save(hazelnut);Order order = new Order(); order.addLine(chestnut, 20); order.addLine(hazelnut, 150);repo.saveOrder(order); s.flush();Order persistent = (Order) s.createCriteria(Order.class).uniqueResult(); Assert.assertNotSame(0, persistent.getId()); Assert.assertEquals(new OrderLine(chestnut, 20), persistent .getOrderLines().get(0)); Assert.assertEquals(new OrderLine(hazelnut, 150), persistent .getOrderLines().get(1)); } }There are a few details worth noting here, though:I marked the test @Transactional, so that I can access Session directly. In this scenario, @EnableTransactionManagement on @Configuration seems to have no effect as the test is wrapped in transaction anyway. If the test is not marked as @Transactional (sensible when it only uses @Transactional components), the transaction seems to always be committed regardless of @TransactionConfiguration settings. If the test is marked as @Transactional, @TransactionConfiguration seems to be applied by default. Even if it’s omitted the transaction will be rolled back at the end of the test, and if you want it committed you need @TransactionConfiguration(defaultRollback=false). This probably goes without saying, but the @Configuration for tests is probably different from production. Here it uses embedded H2 database, for real application I would use a test database on the same engine as production.That’s it, just those two Java classes. No XML or twisted depedencies. Take a look at my github repository for complete code. Reference: Testing Spring & Hibernate Without XML from our JCG partner Konrad Garus at the Squirrel’s blog....

Spring Profile pattern example

Recently we were introduced with the concept of Spring Profiles. This concept is an easy configuration differentiators for different deployment environments. The straight forward use case (which was presented) was to annotate the relevant classes so Spring would load the appropriate class according to the active profile. However, this approach might not always serve the common use case… often, the configuration keys would be the same and only the values will change per environment. In this post, I would like to present a pattern to support loading configuration data per environment, without the need to create/maintain multiple classes for each profile (i.e. for each environment). Throughout the post I would take the DB connection configuration as a sample, assuming we have different DB definitions (e.g. username or connection URL) for each deployment environment. The main idea is to use one class for loading the configuration (i.e.. one class for DB connection definition) and inject into it the appropriate instance which holds the correct profile configuration data. For convenience and clarity, the process was divided into 3 phases: Phase 1: infra preparation Step 1.1 – create a properties file which contains all configuration data Step 1.2 – create an annotation for each profile step 1.3 – make sure the profile is loaded during context loading Phase 2: implementing the profile pattern Step 2.1 – create a properties interface Step 2.2 – create a class for each profile Step 2.3 – create an abstract file which holds the entire data Phase 3: using the pattern Step 3.1 – example for using the pattern Spring Profile pattern – phase 1: infra preparation This phase will establish the initial infra for using Spring Profile and the configuration files. Step 1.1 – create a properties file which contains all configuration data Assuming you have a maven style project, create a file in src/main/resources/properties for each environment, e.g: my_company_dev.properties my_company_test.properties my_company_production.properties example for my_company_dev.properties content: jdbc.url=jdbc:mysql://localhost:3306/my_project_db db.username=dev1 db.password=dev1 hibernate.show_sql=true example for my_company_production.properties content: jdbc.url=jdbc:mysql:// db.username=prod1 db.password=fdasjkladsof8aualwnlulw344uwj9l34 hibernate.show_sql=false Step 1.2 – create an annotation for each profile In src.main.java.com.mycompany.annotation create annotation for each Profile, e.g : @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Profile("DEV") public @interface Dev { }@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Profile("PRODUCTION") public @interface Production { }Create an enum for each profile: public interface MyEnums {public enum Profile{ DEV, TEST, PRODUCTION }Step 1.3 – make sure the profile is loaded during context loadingDefine a system variable to indicate on which environment the code is running. In Tomcat, go to ${tomcat.di}/conf/catalina.properties and insert a line: profile=DEV (according to your environment) Define a class to set the active profile public class ConfigurableApplicationContextInitializer implements ApplicationContextInitializer<configurableapplicationcontext> {@Override public void initialize(ConfigurableApplicationContext applicationContext) { String profile = System.getProperty("profile"); if (profile==null || profile.equalsIgnoreCase(Profile.DEV.name())){ applicationContext.getEnvironment().setActiveProfiles(Profile.DEV.name()); }else if(profile.equalsIgnoreCase(Profile.PRODUCTION.name())){ applicationContext.getEnvironment().setActiveProfiles(Profile.PRODUCTION.name()); }else if(profile.equalsIgnoreCase(Profile.TEST.name())){ applicationContext.getEnvironment().setActiveProfiles(Profile.TEST.name()); } } }Make sure the class is loaded during context loading in the project web.xml, insert the following: <context-param> <param-name>contextInitializerClasses</param-name> <param-value>com.matomy.conf.ConfigurableApplicationContextInitializer</param-value> </context-param>Phase 2: implementing the profile pattern  This phase utilizes the infra we built before and implements the profile pattern. Step 2.1 – create a properties interface Create an interface for the configuration data you have. In our case, the interface will provide access to the four configuration data items. so it would look something like: public interface SystemStrings {String getJdbcUrl(); String getDBUsername(); String getDBPassword(); Boolean getHibernateShowSQL(); //.....Step 2.2 – create a class for each profile Example for a development profile: @Dev //Notice the dev annotation @Component("systemStrings") public class SystemStringsDevImpl extends AbstractSystemStrings implements SystemStrings{ public SystemStringsDevImpl() throws IOException { //indication on the relevant properties file super("/properties/my_company_dev.properties"); } }Example for a production profile: @Prouction //Notice the production annotation @Component("systemStrings") public class SystemStringsProductionImpl extends AbstractSystemStrings implements SystemStrings{ public SystemStringsProductionImpl() throws IOException { //indication on the relevant properties file super("/properties/my_company_production.properties"); } }The two classes above are where the binding between the properties file and the related environment occur. You’ve probably noticed that the classes extend an abstract class. This technique is useful so we won’t need to define each getter for each Profile, this would not be manageable in the long run, and really, there is no point of doing it. The sweet and honey lies in the next step, where the abstract class is defined. Step 2.3 – create an abstract file which holds the entire data public abstract class AbstractSystemStrings implements SystemStrings{//Variables as in configuration properties file private String jdbcUrl; private String dBUsername; private String dBPassword; private boolean hibernateShowSQL;public AbstractSystemStrings(String activePropertiesFile) throws IOException { //option to override project configuration from externalFile loadConfigurationFromExternalFile();//optional.. //load relevant properties loadProjectConfigurationPerEnvironment(activePropertiesFile); }private void loadProjectConfigurationPerEnvironment(String activePropertiesFile) throws IOException { Resource[] resources = new ClassPathResource[ ] { new ClassPathResource( activePropertiesFile ) }; Properties props = null; props = PropertiesLoaderUtils.loadProperties(resources[0]); jdbcUrl = props.getProperty("jdbc.url"); dBUsername = props.getProperty("db.username"); dBPassword = props.getProperty("db.password"); hibernateShowSQL = new Boolean(props.getProperty("hibernate.show_sql")); }//here should come the interface getters....Phase 3: using the pattern As you can recall, in previous steps we defined an interface for configuration data. Now we will use the interface in a class which needs different data per environment. Please note that this example is the key differentiator from the example given in the Spring blog, since now we don’t need to create a class for each profile, since in this case we use the same method across profiles and only the data changes. Step 3.1 – example for using the pattern @Configuration @EnableTransactionManagement //DB connection configuration class //(don't tell me you're still using xml... ;-) public class PersistenceConfig {@Autowired private SystemStrings systemStrings; //Spring will wire by active profile@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryNg(){ LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setDataSource( dataSource() ); factoryBean.setPersistenceUnitName("my_pu"); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(){ { // JPA properties this.setDatabase( Database.MYSQL); this.setDatabasePlatform("org.hibernate.dialect.MySQLDialect"); this.setShowSql(systemStrings.getShowSqlMngHibernate());//is set per environemnt.. } }; factoryBean.setJpaVendorAdapter( vendorAdapter ); factoryBean.setJpaProperties( additionalProperties() );return factoryBean; } //... @Bean public ComboPooledDataSource dataSource(){ ComboPooledDataSource poolDataSource = new ComboPooledDataSource(); try { poolDataSource.setDriverClass( systemStrings.getDriverClassNameMngHibernate() ); } catch (PropertyVetoException e) { e.printStackTrace(); } //is set per environemnt.. poolDataSource.setJdbcUrl(systemStrings.getJdbcUrl()); poolDataSource.setUser( systemStrings.getDBUsername() ); poolDataSource.setPassword( systemStrings.getDBPassword() ); //.. more properties... return poolDataSource; } }I would appreciate comments and improvements. Enjoy! Reference: Spring Profile pattern from our JCG partner Gal Levinsky at the Gal Levinsky’s blog blog....

Hello World with Spring 3 MVC

I owe my introduction to Spring to this article by Martin Fowler, way back in 2005. Since then I have tinkered with many a IoC frameworks including Guice, PicoContainer, NanoContainer etc. While I have enjoyed working with IoC in general, I must say Spring has been and continues to be my choice of IoC container for all enterprise grade application development for well over 5 years now. The latest version of Spring i.e. Spring 3 has been out for a while now. The latest minor version 3.1.1 was released less than a week back, at the time of writing this article. So, as I generally do with latest releases of a few software like Spring, Hibernate, Maven etc I redid – perhaps for the 1000th time – a hello world example with Spring. However, this time I thought I will share this, with the hope that novices in Spring will find the article useful. Keeping in mind the intended audience I felt that an article on Spring MVC will be more useful. Before I go any further, I must mention that there is no dearth of articles on this subject on net. A few of them are highly recommendable e.g. this one. In my article – unlike the other ones that I have read – I intend to use Eclipse only as an editor and Maven for most of build and dependency management related activities. I am sure others would have written similarly as well. If you know of any good article please let me know and I will mention them here as well. Without further ado, lets start by creating a vanilla web application using Maven. File: C:\partha\codeRepo\MavenCommands.bat ECHO OFF REM ============================= REM Set the env. variables. REM ============================= SET PATH=%PATH%;C:\ProgramFiles\apache-maven-3.0.3\bin; SET JAVA_HOME=C:\ProgramFiles\Java\jdk1.7.0 REM ============================= REM Create a vanilla web applicaiton. REM ============================= call mvn archetype:create ^ -DarchetypeArtifactId=maven-archetype-webapp ^ -DarchetypeGroupId=org.apache.maven.archetypes ^ -DgroupId=org.academy ^ -DartifactId=springwebapp001 pauseThis would create a web application springwebapp001. You could deploy that in any servlet container and should be able to hit http://yourmachinename:portnumber/springwebapp001/. It should show you whatever is available at /springwebapp001/src/main/webapp/index.jsp. Now we will Spring dependencies which will allow us to hijack the http hits to the website. I find this article very informative at this step. It gives you a laundry list of all Spring dependencies. There are a few things worth pointing out though. If you were looking for only Spring MVC, it is not immediately apparent that you could just include dependency for Spring MVC and not the entire list. What is also missed is that you need JSTL as well. Lastly, I think it could have been also mentioned that Spring comes preloaded with commons logging which in my opinion is well and truly on it’s way out – relinquishing it’s seat to Logback or Log4j. So, net net, my version of dependency section in pom looks like this. File: \springwebapp001\pom.xml [...] <properties> <project.build.sourceencoding>UTF-8</project.build.sourceencoding> <slf4j.version>1.6.1</slf4j.version> <logback.version>1.0.6</logback.version> <org.springframework.version>3.1.2.RELEASE</org.springframework.version> <javax.jstl.version>1.2</javax.jstl.version> </properties> [...] <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>${org.springframework.version}</version> <exclusions> <exclusion> <groupid>commons-logging</groupid> <artifactid>commons-logging</artifactid> </exclusion> </exclusions> </dependency> [...] <dependency> <groupid>javax.servlet</groupid> <artifactid>jstl</artifactid> <version>${javax.jstl.version}</version> </dependency> [...] <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>${slf4j.version}</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>jcl-over-slf4j</artifactid> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-log4j12</artifactid> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency>We have got all dependencies in place now and we should be able to do a mvn -e clean install without any hiccups. Once we have done that, now is the time to get Spring into the game. We need to hijack all hits for *.html and hand it to Spring. File: /src/main/webapp/WEB-INF/web.xml [...] <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> [...]This means that our application would look for a spring-servlet.xml, where we need to tell Spring what it needs to do with the hits that it intercepts. File: /src/main/webapp/WEB-INF/spring-servlet.xml <beans xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="org.academy.spring3.controllers"> <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"> <property name="prefix" value="/WEB-INF/views/"> <property name="suffix" value=".jsp"> </property></property></property></bean> </context:component-scan></beans>Here we have told Spring to look for controllers in org.academy.spring3.controllers package. Lets add one then. File: /src/main/java/org/academy/spring3/controllers/HelloWorld.java @Controller public class HelloWorld { private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class); @RequestMapping("/helloworld") public ModelAndView hello(){ logger.debug("In the controller."); return new ModelAndView("HelloWorld", "message", "Hello world from Spring3."); } }In this controller we have told Spring to intercept any call to helloworld.html and hand over control to hello(). In this method, we have created a model. The model contains an object called “message” which has a string “Hello world from Spring3.”. This model is handed over to a view called “HelloWorld”. If you look back at spring-servlet.xml you will see “HelloWorld” translates to /src/main/webapp/WEB-INF/views/HelloWorld.jsp. Let’s add some code to that. File: /src/main/webapp/WEB-INF/views/HelloWorld.jsp <html> <head> <title>Spring 3.0 MVC</title> </head> <body> ${message} </body> </html>This code is going to complain a bit on compilation because we have not provided configuration to logback. The following file should do the trick. File: /src/main/resources/log4j.properties # Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 # configure A1 to spit out data in console log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%nFinally, we just need a convenient way to call the helloworld.html. Let’s modify index.jsp. File: /src/main/webapp/index.jsp <html> <html> <body> <h2>Spring 3</h2> <a href="http://www.blogger.com/helloworld.html"> Hello world.</a> </body> </html>That’s it. Compile and deploy in any servlet container. You have a Spring 3 MVC bare bones example up and running. Give it a go. Continue to Handling Forms with Spring 3 MVC. Reference: Hello World with Spring 3 MVC from our JCG partner Partho at the Tech for Enterprise blog....

Handling Forms with Spring 3 MVC

This article is a part of a series of articles written about Spring 3. The previous article of this series is available here. In this article we take another baby step towards Spring MVC. [Aside: A pdf by the originator of the term MVC.] Building from the previous article, let’s add code necessary to add “Contacts” to the application. First thing, we will need to add some UI component to initiate the process. For simplicity’s sake let it be a simple link. File: /springwebapp001/src/main/webapp/index.jsp [...] <a href="contacts/addNew.html"> Add new contact.</a> [...]As you would notice, we have pointed this link to “contacts/addNew.html”. This means that we need something – a controller and / or a method that is looking for this request. Let us create a controller that will field all requests starting with “contacts”. File: src/main/java/org/academy/ui/spring3/controllers/ContactCtlr.java package org.academy.ui.spring3.controllers; import org.academy.ui.spring3.forms.ContactFrm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value = "/contacts") public class ContactCtlr { private final static Logger logger = LoggerFactory .getLogger(ContactCtlr.class); [...] }Spring also has to know that it has to scan for a particular package for controllers. File: /springwebapp001/src/main/webapp/WEB-INF/spring-servlet.xml [...] <context:component-scan base-package="org.academy.ui.spring3.controllers" /> [...]Having set this we will need a method in the ContactCtlr to field GET requests for /addNew.html. [Aside: What is the difference between GET and POST request? Read here.] File: src/main/java/org/academy/ui/spring3/controllers/ContactCtlr.java [...] private final String addNewView = "Contacts/AddNew"; @RequestMapping(value = "/addNew", method = RequestMethod.GET) public String addNewContact() { logger.debug("Display form to add a new contact."); return addNewView; } [...]Here we have simply directed the control to “Contacts/AddNew” which boils down to /springwebapp001/src/main/webapp/WEB-INF/views/Contacts/AddNew.jsp. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Add New Contact</title> </head> <body> <form:form method="post" commandName="contact" action="addNew.html"> <table> <tr> <td colspan="2">Add a new contact.</td> </tr> <tr> <td><form:label path="firstname">First Name</form:label></td> <td><form:input path="firstname" /></td> </tr> <tr> <td><form:label path="lastname">Last Name</form:label></td> <td><form:input path="lastname" /></td> </tr> <tr> <td><form:label path="email">Email</form:label></td> <td><form:input path="email" /></td> </tr> <tr> <td><form:label path="telephone">Telephone</form:label></td> <td><form:input path="telephone" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Add Contact" /></td> </tr> </table> </form:form> </body> </html>This form will need to be backed by a java pojo which will hold all the form elements mentioned in the jsp. File: /springwebapp001/src/main/java/org/academy/ui/spring3/forms/ContactFrm.java package org.academy.ui.spring3.forms; public class ContactFrm { private String firstname; private String lastname; private String email; private String telephone; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } }From the AddNew.jsp you can see the form expects someone to handle a call to “addNew.html”. As before, lets get back to the controller and add a method that handles a POST request to “addNew.html”. Please note that this is a POST request as opposed to the GET request which we have handled before. File: /springwebapp001/src/main/java/org/academy/ui/spring3/controllers/ContactCtlr.java [...] @RequestMapping(value = "/addNew", method = RequestMethod.POST) public ModelAndView addNewContact( @ModelAttribute("contact") ContactFrm contactFrm, BindingResult result) { logger.debug("Adding a new contact. {}", contactFrm.getFirstname()); // Some code to work on the data received from the user. return new ModelAndView(addNewView, "contact", new ContactFrm()); } [...]Lo and behold, if you compile and run this app in any servlet container i.e. Tomcat, you will get a link, that will lead to a Form, that will allow you to put in data, that will transport that data to a java controller at server end, and come back to the form for more. Those of the audience who have designed and developed web applications before MVC frameworks came into being will have moist eyes for sure. Even if you have worked with the early frameworks for MVC, Struts to name the most successful one, will rue the hours spend in getting the three components (M,V and C) together, that now we can get done in under 10 minutes. Software development has definitely come a long way. In the next section we will add unit testing and logging to this application. Happy coding. Related linksStruts – The only other MVC framework that I can recommend Difference between GET and POST The origin of the term MVC Continue to Handling Form Validation with Spring 3 MVC Reference: Handling Forms with Spring 3 MVC from our JCG partner Partho at the Tech for Enterprise blog....

Handling Form Validation with Spring 3 MVC

This article is a part of a series on Spring 3. The earlier articles of this series were Hello World with Spring 3 MVC and Handling Forms with Spring 3 MVC. Now lets dig a bit deeper into Spring. In this article we will learn to validate data that you have got from the forms. Let’s look at the task of validation a little more closely. Scenario 1: We might need to validate e.g. that the email provided does indeed look like an email (x@x.x format to be simplistic). This could be done by just running some scripts on the email field itself. That ought to be simple. We could write some javascript to be run on the browser itself. And also write the same validation on server side [Why? Read here]. This is true for all isolated validations e.g. check that the data is not null, check that the data is certain length etc etc. Scenario 2: Wish life was that simple. Since we were discussing email validations, lets say one of the validations requires us to check that the email is of certain domains (say partner organizations) so that the system can email certain privileged information also. Let’s say we need to check that the email is of format x@partner1.com, x@partner2.com or x@partner3.com. Trivial as it may be, this is an example of the type where the validation could not be run only on the data from the form itself. Whatever is the code for validation, it needs to know which domains are valid. And this data was not present in the data provided by end user in the form. If you flex your imagination a bit you could easily create use case where a business rules engine might be required (e.g. if the rules are too fluid) and / or you can throw in elements of internationalization (e.g. adult age is not 18 in all countries) or other complexities. These are non isolated validations and require accessing further information that is synchronously available. These validations could be coded in both server side and client side, although it is fair to say that it will lean more on server side. Scenario 3: Again, wish life was that simple. Wile we are on the subject of validating emails, we might also need perhaps to check that the email is valid i.e. it is not a thisemail@doesnot.exist(I am not really sure that that email does not exist – or can not exist in future – but you get the idea I hope). We will need to send an email to that email id and perhaps ask the user to click and confirm. We need to interact asynchronously with some other system over SMTP. Again, lean on your imagination a bit and the whole pandora’s box will burst open. Soon you are integrating over REST, SOAP, JMS, File Servers, and handling issues of security and authentication over distributed systems. I would bet most of the systems would go for server side validation in this area and client side validation – though technically possible – would not be used too often. Scenario 4: And we have not yet breached the subject of same domain objects being populated not only from web based forms but also from feed files, JMS messages etc thereby needing the same validation logic being applied on multiple channels. What started off as a puny little form with a handful of innocent looking textboxes at the beginning of this discussion, has morphed into a monster. Fortunately, JSR 303 or Bean Validation [Read more here] is there to rescue. It solves Scenario 1 and 4 mentioned above out of the box. And it supports you to solve Scenario 2 and 3. I will recommend you to read the section marked “How does this standard benefit users? What problems will it solve?” at this link. This specification for java was requested in 2006 and by late 2009 it was released. In other words, the implementations available have already had a chance to mature over year. Spring 3, being a first class open source citizen, allows you to use this standard solution rather than reinvent the wheel. And should you absolutely need to reinvent the wheel (all professional apps need to write that myAppSpecificKickAssValidator()) Spring allows for that as well. Let’s look at both scenarios one by one. Add JSR 303 support to any Maven based project The JSR 303 is an open api. You can find it at this link. Anyone can implement that. There are implementations by hibernate, and apache bval to name a few. Let’s go with the Hibernate implementation. You can see their jars at Maven Central at this link. The latest stable version at the time of writing this article is 4.3.0.Final. You just need to add this dependency in your pom. The api is also bundled with this implementation, hence you don’t need to add that either. File: pom.xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> [...] <hibernate.validation.version>4.3.0.Final</hibernate.validation.version> [...] </properties> <!-- Hibernate validations --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate.validation.version}</version> </dependency>Just by adding this dependency you could go into your entity / form class and declare constraints. JSR 303 has a few standard constraints [listed here] which covers standard checks like NotNull. Hibernate adds a few more non standard custom constraints [listed here]. They are non standard, but quite handy e.g. a check for valid Email. Let’s introduce both these checks on our ContactFrm.java. If you don’t know where that came from, you most probably have not read the previous article of this series i.e. Handling Forms with Spring 3 MVC. File: /org/academy/ui/spring3/forms/ContactFrm.java package org.academy.ui.spring3.forms; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Email; public class ContactFrm { @NotNull private String firstname; private String lastname; @Email private String email; private String telephone; // Getter and setters omitted for brevity. [...] }Unit test Until this point, our ContactFrm bean did not have any functionality in it and hence I did not bother to unit test it (although the TDD enthusiasts will shake their head at it). However, now just by adding a couple of annotations we have added functionality to the bean and that is unit testable (TDD enthusiasts can rejoice starting now). Let’s add a unit test. File: /src/test/java/org/academy/ui/spring3/forms/ContactFrmTest.java package org.academy.ui.spring3.forms; import static org.junit.Assert.*; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ContactFrmTest { private final static Logger logger = LoggerFactory .getLogger(ContactFrmTest.class); private static Validator validator; @BeforeClass public static void init() { validator = Validation.buildDefaultValidatorFactory().getValidator(); } @Test public void test() { Set<ConstraintViolation<ContactFrm>> errors; ContactFrm contactFrm = new ContactFrm(); errors = validator.validate(contactFrm); printErrors(errors); // We are expecting 1 error here. // Just the NotNull. assertEquals(1, errors.size()); errors.clear(); contactFrm.setFirstname("partha"); errors = validator.validate(contactFrm); printErrors(errors); // We are not expecting any errors here. assertEquals(0, errors.size()); errors.clear(); contactFrm.setEmail("this can not be a valid email"); errors = validator.validate(contactFrm); printErrors(errors); // We are expecting 1 errors here. assertEquals(1, errors.size()); errors.clear(); contactFrm.setEmail("this@mightbevalid.email"); errors = validator.validate(contactFrm); printErrors(errors); // We are not expecting any errors here. assertEquals(0, errors.size()); errors.clear(); } // Utility function to print out errors from validation. private void printErrors(Set<ConstraintViolation<ContactFrm>> errors) { if (errors.size() > 0) { for (ConstraintViolation<ContactFrm> error : errors) { logger.debug(error.getMessage()); } } else { logger.debug("There were no errors to print."); } } }You will notice I did not need to use any Hibernate, Spring or JSR specific code to unit test. It is just a simple JUnit. In my mind, the fact that I could add validations on a POJO by just adding a couple of annotations and then I could unit test that with the standard unit testing framework without any tweaks, is a huge step deal. And we are just getting started. Unit test – using Spring capabilities. Of course it is reassuring that we could do complete validation and unit testing without relying on Spring. However we would miss the point of this exercise entirely if we don’t explore how easy it is to bring this all together using Spring, in our website. We will start by adding all the required Spring dependencies to our project and stripping them off the commons logging as explained in the previous article. File: /pom.xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> [...] <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency>Now, add the @RunWith and @ContextConfiguration magic in the unit test, as as explained in the previous article. File: /src/test/java/org/academy/ui/spring3/forms/ContactFrmTest.java @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class ContactFrmTest { private final static Logger logger = LoggerFactory .getLogger(ContactFrmTest.class); @Autowired private Validator validator; // This is no more required as Spring does it for us. // @BeforeClass // public static void init() { // validator = Validation.buildDefaultValidatorFactory().getValidator(); // }[The rest of the code omitted as it remains same.] Now, all that remains is for us to tell Spring what it should Autowire in the validator. This we do using configuration rather than code. File: /src/test/resources/org/academy/ui/spring3/forms/ContactFrmTest-context.xml <?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /> </beans>There you are all set. You could now use “mvn -e clean install” to run this entire code and unit test it. If you were feeling too demanding you could use “mvn -e site” to create a nice HTML website which will report on the code coverage. Read more:Home page of JSR 303  Home page of Hibernate Validator Interview with lead developer of Hibernate Validation – Emmanuel Bernard Spring’s official documentation on validationReference: Handling Form Validation with Spring 3 MVC from our JCG partner Partho at the Tech for Enterprise blog...

JAXB and Root Elements

@XmlRootElement is an annotation that people are used to using with JAXB (JSR-222). It’s purpose is to uniquely associate a root element with a class. Since JAXB classes map to complex types, it is possible for a class to correspond to multiple root elements. In this case @XmlRootElement can not be used and people start getting a bit confused. In this post I’ll demonstrate how @XmlElementDecl can be used to map this use case. XML Schema The XML schema below contains three root elements: customer, billing-address, and shipping-address. The customer element has an anonymous complex type, while billing-address and shipping-address are of the same named type (address-type). <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/customer" xmlns="http://www.example.org/customer" elementFormDefault="qualified"><xs:element name="customer"> <xs:complexType> <xs:sequence> <xs:element ref="billing-address"/> <xs:element ref="shipping-address"/> </xs:sequence> </xs:complexType> </xs:element><xs:complexType name="address-type"> <xs:sequence> <xs:element name="street" type="xs:string"/> </xs:sequence> </xs:complexType><xs:element name="billing-address" type="address-type"/><xs:element name="shipping-address" type="address-type"/></xs:schema>Generated Model Below is a JAXB model that was generated from the XML schema. The same concepts apply when adding JAXB annotations to an existing Java model. Customer JAXB domain classes correspond to complex types. Since the customer element had an anonymous complex type the Customer class has an @XmlRootElement annotation. This is because only one XML element can be associated with an anonymous type. package org.example.customer;import javax.xml.bind.annotation.*;@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"billingAddress","shippingAddress"}) @XmlRootElement(name = "customer") public class Customer {@XmlElement(name = "billing-address", required = true) protected AddressType billingAddress;@XmlElement(name = "shipping-address", required = true) protected AddressType shippingAddress;public AddressType getBillingAddress() { return billingAddress; }public void setBillingAddress(AddressType value) { this.billingAddress = value; }public AddressType getShippingAddress() { return shippingAddress; }public void setShippingAddress(AddressType value) { this.shippingAddress = value; }}AddressType Again because JAXB model classes correspond to complex types, a class is generated for the address-type complex type. Since multiple root level elements could exist for this named complex type, it is not annotated with @XmlRootElement. package org.example.customer;import javax.xml.bind.annotation.*;@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "address-type", propOrder = {"street"}) public class AddressType {@XmlElement(required = true) protected String street;public String getStreet() { return street; }public void setStreet(String value) { this.street = value; }}ObjectFactory The @XmlElementDecl annotation is used to represent root elements that correspond to named complex types. It is placed on a factory method in a class annotated with @XmlRegistry (when generated from an XML schema this class is always called ObjectFactory). The factory method returns the domain object wrapped in an instance of JAXBElement. The JAXBElement has a QName that represents the elements name and namespace URI. package org.example.customer;import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.*; import javax.xml.namespace.QName;@XmlRegistry public class ObjectFactory {private final static QName _BillingAddress_QNAME = new QName("http://www.example.org/customer", "billing-address"); private final static QName _ShippingAddress_QNAME = new QName("http://www.example.org/customer", "shipping-address");public ObjectFactory() { }public Customer createCustomer() { return new Customer(); }public AddressType createAddressType() { return new AddressType(); }@XmlElementDecl(namespace = "http://www.example.org/customer", name = "billing-address") public JAXBElement<AddressType> createBillingAddress(AddressType value) { return new JAXBElement<AddressType>(_BillingAddress_QNAME, AddressType.class, null, value); }@XmlElementDecl(namespace = "http://www.example.org/customer", name = "shipping-address") public JAXBElement<AddressType> createShippingAddress(AddressType value) { return new JAXBElement<AddressType>(_ShippingAddress_QNAME, AddressType.class, null, value); }}package-info The package-info class is used to specify the namespace mapping (see JAXB & Namespaces). @XmlSchema(namespace = "http://www.example.org/customer", elementFormDefault = XmlNsForm.QUALIFIED) package org.example.customer;import javax.xml.bind.annotation.*;Unmarshal Operation Now we look at the impact of the type of root element when unmarshalling XML. customer.xml Below is a sample XML document with customer as the root element. Remember the customer element had an anonymous complex type. <?xml version="1.0" encoding="UTF-8"?> <customer xmlns="http://www.example.org/customer"> <billing-address> <street>1 Any Street</street> </billing-address> <shipping-address> <street>2 Another Road</street> </shipping-address> </customer>shipping.xml Here is a sample XML document with shipping-address as the root element. The shipping-address element had a named complex type. <?xml version="1.0" encoding="UTF-8"?> <shipping-address xmlns="http://www.example.org/customer"> <street>2 Another Road</street> </shipping-address>Unmarshal Demo    When unmarshalling XML that corresponds to a class annotated with @XmlRootElement you get an instance of the domain object. But when unmarshalling XML that corresponds to a class annotated with @XmlElementDecl you get the domain object wrapped in an instance of JAXBElement. In this example you may need to use the QName from the JAXBElement to determine if you unmarshalled a billing or shipping address. package org.example.customer;import java.io.File; import javax.xml.bind.*;public class UnmarshalDemo {public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance("org.example.customer"); Unmarshaller unmarshaller = jc.createUnmarshaller();// Unmarshal Customer File customerXML = new File("src/org/example/customer/customer.xml"); Customer customer = (Customer) unmarshaller.unmarshal(customerXML);// Unmarshal Shipping Address File shippingXML = new File("src/org/example/customer/shipping.xml"); JAXBElement<AddressType> je = (JAXBElement<AddressType>) unmarshaller.unmarshal(shippingXML); AddressType shipping = je.getValue(); }}Unmarshal Demo – JAXBIntrospector   If you don’t want to deal with remembering whether the result of the unmarshal operation will be a domain object or JAXBElement, then you can use the JAXBIntrospector.getValue(Object) method to always get the domain object. package org.example.customer;import java.io.File; import javax.xml.bind.*;public class JAXBIntrospectorDemo {public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance("org.example.customer"); Unmarshaller unmarshaller = jc.createUnmarshaller();// Unmarshal Customer File customerXML = new File("src/org/example/customer/customer.xml"); Customer customer = (Customer) JAXBIntrospector.getValue(unmarshaller .unmarshal(customerXML));// Unmarshal Shipping Address File shippingXML = new File("src/org/example/customer/shipping.xml"); AddressType shipping = (AddressType) JAXBIntrospector .getValue(unmarshaller.unmarshal(shippingXML)); }}Marshal Operation    You can directly marshal an object annotated with @XmlRootElement to XML. Classes corresponding to @XmlElementDecl annotations must first be wrapped in an instance of JAXBElement. The factory method you you annotated with @XmlElementDecl is the easiest way to do this. The factory method is in the ObjectFactory class if you generated your model from an XML schema. package org.example.customer;import javax.xml.bind.*;public class MarshalDemo {public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance("org.example.customer"); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// Create Domain Objects AddressType billingAddress = new AddressType(); billingAddress.setStreet("1 Any Street"); Customer customer = new Customer(); customer.setBillingAddress(billingAddress);// Marshal Customer marshaller.marshal(customer, System.out);// Marshal Billing Address ObjectFactory objectFactory = new ObjectFactory(); JAXBElement<AddressType> je = objectFactory.createBillingAddress(billingAddress); marshaller.marshal(je, System.out); }}Output Below is the output from running the demo code. <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customer xmlns="http://www.example.org/customer"> <billing-address> <street>1 Any Street</street> </billing-address> </customer> <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <billing-address xmlns="http://www.example.org/customer"> <street>1 Any Street</street> </billing-address>Reference: JAXB and Root Elements from our JCG partner Blaise Doughan at the Java XML & JSON Binding blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: