Spring OXM with XStream example

Here is a simple example to marshalling/unmarshalling xml content to/from java object using Spring XOM.

Here I am generating xml content from java object, writing the content to file system, reading that back to java object.

Spring configuration – applicationContext.xml

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;

xsi:schemaLocation=”http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt;

<bean id=”xstreamExample”>

<property name=”marshaller” ref=”xstreamMarshaller” />

</bean>

<bean id=”xstreamMarshaller”>

<property name=”aliases”>

<props>

<prop key=”bean”>com.example.ConfigurationBean</prop>

</props>

</property>

</bean>

</beans>

Simple java bean – ConfigurationBean.java

package com.example;

 

public class ConfigurationBean {

 

private String name;
private Integer age;
private String jobDescription;
private boolean executive;

 

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getJobDescription() {
return jobDescription;
}
public void setJobDescription(String jobDescription) {
this.jobDescription = jobDescription;
}
public boolean isExecutive() {
return executive;
}
public void setExecutive(boolean executive) {
this.executive = executive;
}
}

Spring bean with main main method (for testing): XStreamExample.java

package com.example;

 

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.xstream.XStreamMarshaller;

 

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 

/**
* Example to marshal/unmarshal xml to/from java object using Spring 3.0 OXM feature.
*
* @author Anil Sadineni
*/
public class XStreamExample {
private static final String F_NAME = "example.xml";
private List configurationBeans;

 

private XStreamMarshaller marshaller;

 

public void setMarshaller(XStreamMarshaller marshaller) {
this.marshaller = marshaller;
Map alias = new HashMap();
alias.put("configurations", List.class);
alias.put("configuration", ConfigurationBean.class);
try {
this.marshaller.setAliases(alias);
} catch (Exception e) {
e.printStackTrace();
}
}

 

public void loadConfigurationBeans() throws IOException {
FileInputStream is = null;
try {
is = new FileInputStream(F_NAME);
this.configurationBeans = (List) this.marshaller.unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}

 

public void saveConfigurationBeans() throws IOException {
FileOutputStream os = null;
try {
os = new FileOutputStream(F_NAME);
this.marshaller.marshal(configurationBeans, new StreamResult(os));
} finally {
if (os != null) {
os.close();
}
}
}

 

public static void main(String[] args) throws IOException {
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
XStreamExample ex = (XStreamExample) appContext.getBean("xstreamExample");
ex.execute();
}

private void execute() throws IOException {
configurationBeans = getConfigurationBeans();

saveConfigurationBeans();
loadConfigurationBeans();

for (ConfigurationBean configurationBean : configurationBeans) {
System.out.println(“name: ” + configurationBean.getName());
System.out.println(“desc : ” + configurationBean.getJobDescription());
System.out.println(“age: ” + configurationBean.getAge());
System.out.println(“Exec : ” + configurationBean.isExecutive());
}
}

private List getConfigurationBeans() {
List beans = new ArrayList();

for (int i = 1; i <= 5; i++) {
ConfigurationBean configurationBean = new ConfigurationBean();
configurationBean.setAge(26);
configurationBean.setExecutive(false);
configurationBean.setJobDescription(“Jab Desc – ” + i);
configurationBean.setName(“Anil S – ” + i);
beans.add(configurationBean);
}

return beans;
}
}

 

Output on console:
name: Anil S – 1
desc : Jab Desc – 1
age: 26
Exec : false
name: Anil S – 2
desc : Jab Desc – 2
age: 26
Exec : false
name: Anil S – 3
desc : Jab Desc – 3
age: 26
Exec : false
name: Anil S – 4
desc : Jab Desc – 4
age: 26
Exec : false
name: Anil S – 5
desc : Jab Desc – 5
age: 26
Exec : false

Generated XML content (example.xml) –

<configurations>

<configuration>

<name>Anil S – 1</name>

<age>26</age>

<jobDescription>Jab Desc – 1</jobDescription>

<executive>false</executive>

</configuration>

<configuration>

<name>Anil S – 2</name>

<age>26</age>

<jobDescription>Jab Desc – 2</jobDescription>

<executive>false</executive>

</configuration>

<configuration>

<name>Anil S – 3</name>

<age>26</age>

<jobDescription>Jab Desc – 3</jobDescription>

<executive>false</executive>

</configuration>

<configuration>

<name>Anil S – 4</name>

<age>26</age>

<jobDescription>Jab Desc – 4</jobDescription>

<executive>false</executive>

</configuration>

<configuration>

<name>Anil S – 5</name>

<age>26</age>

<jobDescription>Jab Desc – 5</jobDescription>

<executive>false</executive>

</configuration>

Advertisements

Simple demonstration of Ext.extend

I have used javascript before in many project but never looked at javascript from object oriented programming prospective. As I started learning extjs, i am finding some interesting OO fundamentals in javascript. Here is a simple demonstration of extjs’s extend feature.


// declares class 'a'
var a = function(){
// constructor
console.log('in a class constructor');
};

// defines memebers in class ‘a’
a.prototype = {
foo: function() {
console.log(‘in a class m1()’);
},
bar: function() {
console.log(‘in a class m2()’);
}
};

// declares class ‘b’
var b = function() {
console.log(‘in b class constructor’);
b.superclass.constructor.call(this);
};

// extends class ‘a’
Ext.extend(b, a, {
// overrides method ‘bar’
bar : function() {
console.log(‘in b class m2()’);
}
});

// on document ready..

Ext.onReady(function(){
// declares aVar of type ‘a’
var aVar = new a();

// calls methods using aVar
aVar.foo();
aVar.bar();

// declares bVar of type ‘b’
var bVar = new b();

// calls methods using bVar
bVar.foo();
bVar.bar();

});

Output in forebug console when page loads –

in a class constructor
in a class m1()
in a class m2()
in b class constructor
in a class constructor
in a class m1()
in b class m2()

ZK validator to check user id uniqueness on registration

I wrote a very simple validator to verify the uniqueness of user entered id by checking against database. It also validates if the user id is more than 5 characters long.

import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zul.Constraint;
import User;
import UserService;
/**
* ZK validator for user id uniqueness.
*
* @author Anil
*/
public class UserIdUniquenessValidator implements Constraint {
/** user service to pull user info from DB */
private UserService userService;
public void validate(Component comp, Object value) throws WrongValueException {
if (value == null || StringUtils.isEmpty((String) value)) {
throw new WrongValueException(comp, “Please enter User ID”);
}
if (((String)value).trim().length() < 4) {
throw new WrongValueException(comp, “User Id must be at least 5 characters”);
}
User user = userService.load((String) value);
if (user != null) {
throw new WrongValueException(comp, “User ID already exists”);
}
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
I declared this validator as spring bean in spring context file:
<bean id=”userIdUniquenessValidator” class=”com.gavs.skill.ui.validator.UserIdUniquenessValidator”>
<property name=”userService” ref=”userService”/>
</bean>
ZUL file:
<bean id=”userIdUniquenessValidator” class=”UserIdUniquenessValidator”>
<property name=”userService” ref=”userService”/>
</bean>
<?variable-resolver class=”org.zkoss.zkplus.spring.DelegatingVariableResolver”?>
<grid>
<columns>
<column label=””></column>
<column label=””></column>
</columns>
<rows>
<row>
<label value=”First Name” width=”150px” />
<textbox  id=”indFirstName” width=”150px” constraint=”no empty”  value=”@{user.firstName}” />
</row>
<row>
<label value=”Last Name” width=”150px” />
<textbox id=”indLastName” width=”150px” constraint=”no empty” value=”@{user.lastName}”/>
</row>
<row>
<label value=”Email” width=”150px” />
<textbox id=”indEmail” width=”150px” constraint=”/.+@.+\.[a-z]+/: Please enter an e-mail address” value=”@{user.emailId}”/>
</row>
<row>
<label value=”User Id” width=”150px” />
<textbox id=”indUserId” width=”150px” constraint=”${userIdUniquenessValidator}” value=”@{user.userId}”/>
</row>
<row>
<label value=”Password” width=”150px” />
<textbox id=”password” type=”password”  width=”150px” constraint=”no empty” value=”@{user.password}”/>
</row>
</rows>
</grid>
.….
Thats all. On blur of user id field, validator validates the user entered info  and display the error message if user id already exist in database.
Posted in ZK. Tags: , . 1 Comment »

Custom resolver to explose logged in user info for ZK (Spring Security)

To expose spring security’s authentication info with object name “authentication” in ZK CE, the following simple resolver is useful.

import org.springframework.security.context.SecurityContextHolder;
import org.zkoss.xel.VariableResolver;
/**
* Resolver to make “authentication” object available for zk EL.
*
* @author Anil
*
*/
public class SecurityResolver implements VariableResolver {
public Object resolveVariable(String name) {
if (“authentication”.equals(name)) {
return SecurityContextHolder.getContext().getAuthentication();
}
return null;
}
}

This is resolver will be used as below:

<?variable-resolver class=”com.gavs.zk.common.SecurityResolver”?>

<toolbar id=”toolbar” style=”margin-top: -15px;”>

<toolbarbutton image=”/images/icons/small/home.ico” label=”Home”   if=”${authentication.principal == ‘roleAnonymous’}” style=”font-size: 11px; font-weight: bold;”>

<attribute name=”onClick”>

<![CDATA[Executions.sendRedirect(“/index.zul”); ]]>

</attribute>

</toolbarbutton>

</toolbar>

Here  “Home” link gets displayed only if user has not yet logged into system.

Back with new blog

Back with new blog. 🙂

Spring Security custom tag in ZK community edition

I upgraded my app to ZK 5.x community edition from 3.x and realized that spring security tags support not provided by community edition. I have created a custom tag to enforce restrictions based on roles in zul page.  I thought of sharing it here:

1) Create a class with static function to verify the role from spring’s  SecurityContextHolder.

public class SpringSecurityUserAccessSupport {
private static final Logger LOG = LoggerFactory.getLogger(SpringSecurityUserAccessSupport.class);
/**
* Verifies whether logged in user is in passed in role.
*
* @param role
* @return
*/
public static boolean isUserInRole(String roleStr) {
String[] roles = StringUtils.split(roleStr, “,”);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
GrantedAuthority[] authorities = auth.getAuthorities();
Role role;
for (int i = 0; i < roles.length; i++) {
role = new Role(StringUtils.trimToEmpty(roles[i]));
if (ArrayUtils.contains(authorities, role)) {
return true;
}
}
return false;
}
}

2) create  a new .tld file and config.xml file under metainfo\tld directory

custom.tld:

<taglib>

<uri>http://www.domain.com/custom</uri&gt;

<function>

<name>isUserInRole</name>

<function-class>SpringSecurityUserAccessSupport</function-class>

<function-signature>boolean isUserInRole(java.lang.String)</function-signature>

</function>

</taglib>

config.xml:

<?xml version=”1.0″ encoding=”UTF-8″?>

<config>

<taglib>

<taglib-uri>http://www.domain.com/custom</taglib-uri&gt;

<taglib-location>metainfo/tld/custom.tld</taglib-location>

</taglib>

</config>

3) Use the tag inside .zul file

<?taglib uri=”http://www.domain.com/custom&#8221; prefix=”sec”?>

<hbox width=”100%” align=”center”>

<toolbar id=”toolbar” style=”margin-top: -15px;”>

<toolbarbutton image=”/images/icons/small/home.ico” label=”Add User” if=”${sec:isUserInRole(‘ROLE_INDIVIDUAL_USER’) }” style=”font-size: 11px; font-weight: bold;”>

<attribute name=”onClick”>

<![CDATA[Executions.sendRedirect(“/index.zul”); ]]>

</attribute>

</toolbarbutton>

</toolbar>

</hbox>

Here I am displaying “Add User” option on toolbar only when logged in user has role “ROLE_INDIVIDUAL_USER“.


Issue with maven and cobertura integration

I found an interesting problem while integrating cobertura with maven to generate the test coverage report for my new code.

I have done following modificaitons in pom.xml file:
a) Added plug-in for cobertura

<build>

<plugins>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

b) Reporting

<reporting>
<plugins>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
</plugin>
</plugins>
</reporting>

When I ran mvn cobertura:cobertura, I got the following error:

[INFO] Nothing to compile – all classes are up to date [INFO] [cobertura:instrument] [ERROR] java.lang.UnsupportedClassVersionError: net/sourceforge/cobertura/instru ment/Main (Unsupported major.minor version 49.0) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source)

By looking at this I came to a conclusion that this incompatible class version issue.
When i ran mvn –version command, it gave me following info. Evrything looks fine as expected.

Maven version: 2.0.9
Java version: 1.5.0_15 OS name: “windows xp” version: “5.1” arch: “x86” Family: “windows”

I should not see above exception as I am using right version of JDK (1.5.0_15). I checked JAVA_HOME and even JRE_HOME env variable and they pointed to right location.

When I executed java –version command, I see following results

java version “1.4.2_11” Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_11-b06) Java HotSpot(TM) Client VM (build 1.4.2_11-b06, mixed mode)

Hmmmm…

I still didn’t believe that’s the root cause of problem. I gave it a
try by uninstalling JRE 1.4.2 and installed JRE 1.5 and everything started working fine.

I believe(though I am not a maven guru) that MAVEN is not making use of environment variable (here JAVA_HOME) to execute the plug in. I have spent almost 3 hours of my time and i thought this might be helpful for people like me.