Validation in JAXB 2 vs JAXB 1

The release of JAXB 2 brought lot of advantages to the developer like putting annotations on the objects etc, at the same time it has given a liberty to the user about how does he/she wants to handle the validation using the JAXP validation APIs.

Validation in JAXB1
If JAXB detects error or inconsistency in the data received and it is unable to recover it throws an UnmarshalException.

eg:

JAXBContext jc = JAXBContext.newInstance( "com.thoughtclicks" );
Umarshaller u = jc.createUnmarshaller();
u.setValidating(true);


Validation in JAXB2
Developer has the choice of what and how to handle the incosistency in error validation.

eg:

JAXBContext jc = JAXBContext.newInstance( "com.thoughtclicks" );
Umarshaller u = jc.createUnmarshaller();
SchemaFactory factory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File("order.xsd"));
u.setSchema(schema);


Either you can use the default validation handler like

u.setEventHandler(new DefaultValidationEventHandler())


or you can have your own custom validation handler and set that to the umarshaller


public class CustomValidationEventHandler implements ValidationEventHandler{
public boolean handleEvent(ValidationEvent ve) {
if (ve.getSeverity()==ve.FATAL_ERROR ||
ve .getSeverity()==ve.ERROR){
ValidationEventLocator locator = ve.getLocator();
//log the message
System.out.println("Message is " + ve.getMessage());
//log the error reference
System.out.println("Column is " +
locator.getColumnNumber() +
" at line number " + locator.getLineNumber());
}
return true;
}

}


You are all set to handle the validations.

Good luck !

OpenSymphony Quartz Scheduler in Spring

Spring offers a very seamless integration with Quartz to create some scheduled tasks. Below i will explain the steps in which you can do that.

To get started what you need is a spring.jar downloaded along with a download of Quartz jar files.

Spring simply gives you extension of all the core classes provided by Quartz which includes:
1. org.springframework.scheduling.quartz.JobDetailBean - which extends QuartzJobBean
2. org.springframework.scheduling.quartz.SimpleTriggerBean - which extends SimpleTrigger
3. org.springframework.scheduling.quartz.SchedulerFactoryBean - which implements the main scheduling functionality.

So by using these three classes you can write scheduled jobs very quickly. All you need to do is defined three beans in your spring - config file. The definition is as follows.

Declare the job:


<bean name="sendmailsjob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.thoughtclicks.SendEmailsJob" />
<property name="jobDataAsMap">
<map>
<entry key="to" value="rahul.juneja@thoughtclicks.com" />
</map>
</property>
</bean>


Now add the job class as follows.

public class SendEmailsJob extends QuartzJobBean {
@Override
protected void executeInternal (JobExecutionContext ctx) throws JobExecutionException {
String touser = (String) ctx.getJobDetail().getJobDataMap().get("to");
sendmail(to);//this will send the mail to the user defined in the to address.
}
}


You have a choice of fetching the properties from the context i have done in the previous code or you can also add the properties in the bean for the same and provide getter and setters and Spring will do the injection for you and provide the populated properties.

now you need to define the trigger using the job you created above.


<bean id="emailTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="sendmailsjob" />
<property name="startDelay" value="0" />
<property name="repeatInterval" value="10000" />
</bean>


Now finally you need to define the scheduler for scheduling this very trigger, which can be done as follows.


<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="emailTrigger" />
</list>
</property>
</bean>


After the steps defined above once you start the application including the spring config the job you just created is started automatically and will run in every 10 seconds as defined in the trigger with property "repeat interval"

You can also use your existing methods to be called by the scheduler rather then creating the whole new scheduler bean and the only change you need for that is creating the job as follows.


<bean name="sendmailsjob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="existingbeanallreadydefined" />
<property name="targetMethod" value="methodsendMail" />
</bean>


If you need any further code or tips. you can drop me an email at rahul.juneja@thoughtclicks.com

Rest and JSON in JQuery - Twitter Gadget

I am sure you guys must have seem lot of gadget floating around the web for twitter, yahoo, google and what not.

Did you ever thought that writing a small gadget is such a small and minutes job with jquery and the apis exposed by these social networking sites like facebook and twitter. I just tried hands on one of the those and it was quick to get this twitter gadget ready to be shared.

Simple JSON script like the one below can do the whole trick for you.


$(document).ready(function(){
var tweeturl = "http://twitter.com/status/user_timeline/
rahuljuneja.json?count=5&callback=?";
$.getJSON(tweeturl, function(data){
$.each(data, function(i, item) {
$('

').addClass(i%2 ? 'even' : 'odd')
.html(item.text)
.prependTo('#tweet');
});
});
});

Interface handling in REST and JAXB

It is a very common scenario when you are writing a class implementing and interface and your parameters to the classes are interfaces.

eg:

 
public interface Person {}

@XmlRootElement
public class Employee implements Person {}

@Path("/persons")
public class MyEmployeeResources {
@PUT
@Consumes("application/xml")
public void putEmployee(Person person) {...}
}

In the above example you will get an error with Jersey or RESTEasy as they both don't know the implementation of Person are JAXB class, hence they don;t have the context of JAXB.

Really cool alternative to this was to use @XMLSeeAlso annotation. something like below

 
@XmlSeeAlso(Employee.class)
public interface Person {}

This way JAXB creates the JAXBContext of Person, because it knows that it can be unmarshal with Employee or Student class.

Similarly @XMLSeeAlso can be used with JAX-WS.

Tag Cloud Component in JSF

After spending couple of hours and playing around with some jsf component features tweaks i was able to develop a Tag Cloud Component.

Here are few things this you might clear some confusions which i faced when writing this component in jsf.

Firstly, you need to decide do you need a seperate class for renderer or you can render in the same component class if you are not planning to reuse the renderer for other things.

Second writing jsf component will be a little more simpler if you are using jsf-facelets.

Now if you are doing this is Jsf 1.1 then while writing the tag class you need to take care that any attributes defined should be declared as String no matter what is the input/Output type of the component. whereas same thing if you are doing in 1.2 then all attributes has to be defined as ValueExpression.

eg: if you are creating a tag for TagCloud Component in jsf 1.1 look at the following code.

 
public class TagCloudTag extends UIComponentTag {

public String labelsMap = null;

public String getlabelsMap() {
return labelsMap ;
}

public void setlabelsMap(String labelsMap) {
this.labelsMap = labelsMap ;
}

// Associate the renderer and component type.
public String getComponentType() {
return "com.thoughtclicks.component.TagCloudComponent";
}

public String getRendererType() {
return null;
}

protected void setProperties(UIComponent component) {
super.setProperties(component);
if (!(component instanceof TagCloudComponent)) {
throw new IllegalStateException(
"Component "
+ component.toString()
+ " not expected type. Perhaps you're missing a tag?");
}
TagCloudComponent tagCloud = (TagCloudComponent) component;
if (labelsMap!= null) {
if (isValueReference(labelsMap)) {
ValueBinding vb = getValueBinding(labelsMap);
tagCloud.setValueBinding("labelsMap", vb);
} else {
throw new IllegalStateException(
"The value for 'tagCloud' must be a ValueBinding.");
}
}
}

public void release() {
super.release();
labelsMap= null;
}

private ValueBinding getValueBinding(String valueRef) {
ApplicationFactory factory = (ApplicationFactory) FactoryFinder
.getFactory(FactoryFinder.APPLICATION_FACTORY);
Application application = factory.getApplication();
return application.createValueBinding(valueRef);
}


Similarly, if you are writing the same component in jsf 1.2 then you will need to change the attribute labelsMap to ValueExpression also don;t forget you need to extend "UIComponentELTag" instead of UIComponentTag and corresponding changes to set properties method.

For any other supporting code you can write me at : rahul.juneja@thoughtclicks.com.

US Govt. approach towards SOA

It is interesting to see that Obama administration is quickly adapting latest IT trends and also promoting them to be used by other users.

White house blog :
Allow citizens to build their own applications on top of government online services; for example, using a "Services Oriented Architecture" approach;


More information can be found at: Data Transparency via Data.gov

Some people might say SOA is loosing its flavor during this downturn but i think SOA jointly with cloud computing is going to be a winner out of this "R".

World of Cloud Computing

Large number of options available in Cloud computing including Amazon EC2, Stax, Google App Engine did encourage me to get into this wide and fast growing world of Cloud computing.

Since last some days i have just been exploring this amazing and recently growing world of cloud computing. I did try developing couple of small apps with Stax, Google App Engine and i was surprised the way these folks have opened a new world of options for small organizations or individual developers who wants to use the large infrastructure and don't want to invest huge amount of money in the beginning.

After this recent release of Google app engine supporting Java, its not leaving anybody unaware about this new arena, which can help anybody and everybody from a small software garage shop or large companies.

I was surprise to see what all can you do with huge infrastructure backing you and you pay only what you use with no strings attached.

Amazon Simple Queue Service (Amazon SQS) was one of the most interesting platform I encountered which is highly scalable, hosted queue for storing messages as they travel between your business networks. But one thing i was wondering about was the security. How secure are they ? They definitely comment being very secure but what's the guarantee that these messages are not intercepted by the hosting provider.

But definitely these options help new developers to develop some applications which they can expand in future.

Good luck to all this cloud computing and hope this lands up in strong cloud in future.