Friday, April 25, 2008

Castor Xml mapping: mapping.loadMapping() gives IOException for filepath

This is very know problem i think and many of you know it but then also i am writing it here.

For convert a Value Object class directly in pre-defined XML format we use castor mapping.We give xml mapping file (as we have seen in earlier tutorial) to Mapping class object as below which will write xml string in strWriter object from Object obj.
Mapping mapping = new Mapping();
mapping.loadMapping(mappingXmlFilename);
strWriter = new StringWriter();
Marshaller marshaller = new Marshaller(strWriter);
marshaller.setMapping(mapping);
marshaller.marshal(obj);
But when i given directly the filename to loadMapping method, it gives IOException as below:
IOException : \shared\p1\p2\shared\p1\p2\lai-sup-mapping.xml
i have given absolute filepath '\\shared\p1\p2\lai-sup-mapping.xml' and then also it is generating it using relative one.So throwing IOException for file.

Then i have changed the thing and instead of giving filepath, i have made a org.xml.sax.InputSource object from the xml file and passed that xml source to loadMapping() as below:

Mapping mapping = new Mapping();
InputSourcemappingSource =
newInputSource(new FileInputStream(mappingXmlFilename));

mapping.loadMapping(mappingSource);
strWriter = new StringWriter();
Marshaller marshaller = new Marshaller(strWriter);
marshaller.setMapping(mapping);
marshaller.marshal(obj);
And its working fine.Now its generating correct XML file from the given Value object.

Thursday, April 24, 2008

Servicemix Queue filled - Queue size increased

I have been using servicemix since more then 1 year.As we have seen in urlier articles that servicemix uses ActiveMQ for Message queuing. The messages sent are filled in the Queue of destined component which will be fetched later on.

When we started using Servicemix, we faced a strange problem.After running for sometimes,our application stops processing messages.When we looked in the JMS Queue, we found that after certain period the messages in the queue are not removing.So new messages can't be processed.The Queue is full and we must restart the application to get rid of this.

Then we dig into the source code of servicemix and found how queue is given size.We increased the size as per our need and the problem was solved.

Basically when message processed by the component, it will be removed from its queue.But for some reason, if message not processed or not removed from the queue then further messages will be stored in the queue and processing stops.The application seems to be running but messages are not processed.

The class org.apache.servicemix.jbi.util.BoundedLinkedQueue contains the property capacity_
Constructor of this class contains the magic which initializes the capacity of queue size.

By default it is 1024.you can change it as per your need. I mean how much messages you think will be processed after every restart.

code:
public BoundedLinkedQueue() {
this(1024);
}
public BoundedLinkedQueue(int capacity) {
if (capacity <= 0)
throw new IllegalArgumentException();
capacity_ = capacity;
putSidePutPermits_ = capacity;
head_ = new LinkedNode(null);
last_ = head_;
}
I just simply changes the 1024 to bigger number like 1024*10 etc...

Try this.may be it can solve your problem also.

And others who know about servicemix and want to share their problems and tweaks are welcome.Put your comments here i will post it.

Java Web application cookie lost!

I got one new change to do in our java web application.I have not been in it since 2 or 4 months and forgot some of its settings.

First of all my jboss refuses to run from eclipse!i was very worried about it, but later i re-configured it as a "dynamic web application" project in eclipse.

So when jboss runs finally, i logged in it and a big blast! it redirected me to error page. I checked the logs but i can't find anything.I was thinking that even i have not chnaged the things in code,configuration etc. then also it stucks here?

But suddenly, a spark happned and i remembered that we set domain for cookies in most web applications.And that thing sucks in local environment.
cookie setting code:
Cookie c1 = new Cookie(name, value);
c1.setDomain(domainName);
So i just commented out c1.setDomain(domainName); and my application is ok.

Monday, April 21, 2008

Java Mail API with Encoded Attachment FileNames

This is very strange problem i faces as per me. May be because different email clients have different encodings or something else, but we will get encoded filename header from some email clients like lotus, blackberry phone etc.

Message header for attachment:

Content-Transfer-Encoding: base64
Content-Type: image/jpeg
Content-Disposition:attachment;
filename="=?Windows-1252?B?SU1HMDAwMTYuanBn?="

Then i was stucked with the thing that how to decode the filename.I have the filename only in subject line.But i can not trust that because say if 3 attachments are there, then there will be 3 filenames in subject in order.But we should not depend on the subject of the email.

javax.mail.internet.MimeUtility util class which helps to decode the encoded strings in message header values as below

Method:
javax.mail.internet.MimeUtility.decodeText(strValueToBeDecoded);
But most of the encodings with java 1.3.1 are not supported. At least 1.4.1 must be used.

Friday, April 11, 2008

Eclipse Shortcuts

I was free as my code with CR is done. i was thinking wht to write and it just sparked in my mind that this can be a good thing though many of us has explored this.But then also it can help some newbies.
Maximize/minimize the selected window - Ctrl +M
Generate getters/setter - Alt+Shift+s + r
Override/implement methods - Alt+Shift+s + v
Show type implementation - Ctrl+T on selected type in java file
quick class member browser - Ctrl+o
search usage of selected member - Ctrl+Alt+H
comment/uncomment selected lines - ctrl+/
Open declaration - F3
This is what most used ones. You also can submit if i missed important ones in commnets.

Using Apache ServiceMix - ESB with spring


Apache ServiceMix is an open source ESB (Enterprise Service Bus) that combines the functionality of a Service Oriented Architecture (SOA) and an Event Driven Architecture (EDA) to create an agile, enterprise ESB.

Apache ServiceMix is an open source distributed ESB built from the ground up on the Java Business Integration (JBI) specification JSR 208 and released under the Apache license. The goal of JBI is to allow components and services to be integrated in a vendor independent way, allowing users and vendors to plug and play.

Features:

ServiceMix is lightweight and easily embeddable, has integrated Spring support and can be run at the edge of the network (inside a client or server), as a standalone ESB provider or as a service within another ESB. You can use ServiceMix in Java SE or a Java EE application server.

ServiceMix uses ActiveMQ to provide remoting, clustering, reliability and distributed failover.

ServiceMix is completely integrated into Apache Geronimo, which allows you to deploy JBI components and services directly into Geronimo. ServiceMix is being JBI certified as part of the Geronimo project.

Other J2EE application servers ServiceMix has been integrated with include JBoss, JOnAS with more to follow.

ServiceMix includes a complete JBI container supporting all parts of the JBI specification including:
* Normalized Message Service and Router
* JBI Management MBeans
* Ant Tasks for management and installation of components
* full support for the JBI deployment units with hot-deployment of JBI components
ServiceMix also provides a simple to use Client API for working with JBI components and services.

How to use?

JBI components can be created extending servicemix's implementation classes.This is required because only then can you will be able to use the plug-&-play component,which is our purpose to use servicemix ESB.

You can develop Binding components which can receive data through HTTP and Files.Servicemix has already provided specific classes so you can deal with http request,input folder.
HTTP - org.apache.servicemix.components.http.HttpConnector.
File - org.apache.servicemix.components.file.FilePoller
So your class will use the HTTP request/file to fetch data and will make an javax.jbi.messaging.NormalizedMessage class object.

This NormalizedMessage object will be then given to javax.jbi.messaging.MessageExchange implementation (InOnly or InOut) and MessageExchange will be then routed to the next component configured as service endpoint in application context xml file.

application context xml code:
<sm:activationSpec componentName="myfilePoller" service="foo:myfilePoller" destinationService="foo:myDrool">
<sm:component>
<bean class="test.my.file.MyFilePoller">
<property name="workManager" ref="workManager" />
<property name="file" value="C:/inbox" />
<property name="period" value="120000" />
<property name="deleteFile" value="true" />
</bean>
</sm:component>
</sm:activationSpec>

<sm:activationSpec componentName="myDrool" service="foo:myDrool">
<sm:component>
<bean class="org.apache.servicemix.components.drools.DroolsComponent">
<property name="ruleBaseResource" value="classpath:myRule1.xml" />
</bean>
</sm:component>
</sm:activationSpec>
Here MyFilePoller is the class which will poll files from 'C:/inbox' folder. And make messaging as we discussed above.'myDrool' is its destination component which is an drools component.

Drools is like dynamic routing.We just need to make rules in xml file and that xml will be loaded automtically if its configured in applicationContext file as above. Its jar must be in 'lib' dir of the server.

Below is the drools xml which declares the rule base on which the NormalizedMessage will be routed to appropriate destination component.

NormalizedMessage can contain data and properties.We can read its property in XML rule base.And based on particular property, we can route the message.

Check the xml below.

myRule1.xml:
<rule-set name="cheese rules"
xmlns="http://drools.org/rules"
xmlns:java="http://drools.org/semantics/java">
<application-data identifier="jbi">org.apache.servicemix.components.drools.JbiHelper</application-data>
<application-data identifier="context">javax.jbi.component.ComponentContext</application-data>
<application-data identifier="deliveryChannel">javax.jbi.messaging.DeliveryChannel</application-data>
<rule name="Rule for componentOne">
<parameter identifier="exchange">
<class>javax.jbi.messaging.MessageExchange</class>
</parameter>
<java:condition>"TRUE".equalsIgnoreCase(exchange.getMessage("in").getProperty("isForComponentOne").toString()) == true</java:condition>
<java:consequence>
jbi.forwardToService("http://servicemix.apache.org/demo/", "componentOne");
</java:consequence>
</rule>
<rule name="Rule for anotherComponent">
<parameter identifier="exchange">
<class>javax.jbi.messaging.MessageExchange</class>
</parameter>
<java:condition>"TRUE".equalsIgnoreCase(exchange.getMessage("in").getProperty("isForComponentOne").toString()) == false</java:condition>
<java:consequence>
jbi.forwardToService("http://servicemix.apache.org/demo/", "anotherComponent");
</java:consequence>
</rule>
</rule-set>
This will route the message to 'componentOne' if the property tested in condition is true and toward 'anotherComponent' otherwise.Both components also will be specified in applicationcontext xml file.

This is how routing does work.Now we will talk about how each component get notified of message transfered.

Every intemediate component in servicemix will create new message and Exchange,pass it to next component after finishing its processing and send notification to the previous component.

code:
getDeliveryChannel().send(newExchange);
done(exchange);
At last, we now talk about the service endpoint, which has opposite task compared to binding components.

BindingComponents takes in and creates messages, Service endpoints throw out the messages and finishes the process.

we have 3 to 4 different outbidding components here and its having some classes already provided.
File - org.apache.servicemix.components.file.FileWriter
FTP - org.apache.servicemix.components.net.FTPSender
HTTP - org.apache.servicemix.components.util.OutBinding ( i have used this becasue in http, we will jsut send data to some URL or so and then processing is finished.)
Mail/SMTP - org.apache.servicemix.components.email.MimeMailSender
This is how we can use servicemix. You can add different components as per your needs at any place in the whole flow and define the path in xml applicationContext and Rule base files.

The changes or additions afterward will require some small changes only. You need to define new properties in NormalizedMessage and based on that property you can create new RuleBase files. And using drools, create new routing path for new feature.

Its very easy to use though feels very tricky and complex in the beggining.

we Will discuss more. :)

Developement Processes: Some Important some boring

This is no new thing i am writing about.All developers know this and gone through this when ever they got some new thing to develop. It hurts in heart when someone says something which you must do as a process and feels boring.

As per SDLC, some basic steps needed for developers are,

Reading specs and use cases

This is most annoying thing i ever found. Yes because what the analysis team does all knows. Copy-paste some basic paragraphs from the templates,making funny and ugly diagram in word which is never usable to developers,using fast vivid colors which will just make you cry or feels you are reading some horror story and finally the language which is too complex and contains thing which are not of use! What they mention you can't get and what you want them to know they can't deal with it!

Deciding approach & Making design diagrams

This is somewhat very important thing if the team is well. Otherwise all are just suggesting diff. approaches and no decisions at the end!Design diagrams must be prepared before the development but sometimes the project managers or the CEOs are in so hurry that they want get it done fast and deployed even without any Technical documents/design diagrams!
Sometimes the coder submits the diagrams and docs for review but the leaders/seniors are so busy (or may be ignoring it thinking 'its not related to my project') and not reviewed it.And after the code is done, they will find holes and design problems in that.Now say who's fault is this?
This is cool when its a small thing and approach is simple, but when you are expecting a whole big feature/module/functionality in short period ,with testing yes keep this in mind "with testing" done,then its a hell for developer. After the coding done, developer asked for diagrams. Now say, isn't its boring? Yes that what i am saying. It sucks!

Coding

Its best part if the thing is designed and design is reviewed properly.As per my experience this is the least time taking step for a good team.

Code Review

CR must be done. But if its done in quite short time after the code done. it means, CR should be fast process of all because developer can complete task fast if its in period while he is inside the thing.Once he had given for CR and you get back to him after some 1 month or so then he even doesn't remember what he had done!
And at some places, quite boring procedures for CR. you submit code filenames for CR, distribute it to some person,write comments on it and etc... This is time wasting and it stinks! It must be a simple process like pressing a button because developers' time is not for this funny things.

Deployment

This may be complex thing but it should not waste coders time. But at some places, system people stuck and call for coders.Some are intelligent to get into but some are even not understanding on total help and documentation provided by a coder.Only the instructions needed to be given by a coder.Its not his job to deploy the whole titanic into the sea!

Testing

Now is the worst thing that a developer may be need to do sometimes.Yes i have done this even more than hundreds times because of some funny and frustrating test cycles! Sometimes they even don't know how to test & What should they do!You can say its better you do it all instead giving them the idea.This is mostly happens because nowadays testing people are nontechnical! They just know clicking the button and etc.They don't know how to deal with application internals and view log and all.May be companies wants some nontechnical arts graduate as a tester in less money instead of a good testing software engineer!
And sometimes they raise wrong bugs which have been tested with wrong scenarios,even on your instructions that this is not right one to test!And when you draft a mail which makes them shy or some senior person bang on them, they feels you like an enemy!

Bug fixing


This is most 'long long long' process for coders.The diff. natured(technical/nontechnical,thinking themselves as coders) testers rais long list of bugs out which rare cases are function issues.Most are like for UI things.And when a coder is given a bug which not of his area then definitely it will consume more time and if we calculate total time for such non-related-area bugs of all coders then it will make a big difference in the process completion date.May be it can delay release if the testing cycles are more in numbers but less detailed and proper.

This is not like i am bored of coding. I love coding but everything which is having its charms,have some bad things also associated with it.Say if testers are also coders then? may be you can get more bugs? yes but you can test fats and at the end your final release would be a great thing.Same thing applies for all team in SDLC ;). i mean analysis,project management,testing all.

I am telling what i think. It depends on particular's likings ;)

Just do Code.

Friday, April 4, 2008

Relo - Relationship based Exploration (UML Like Diagrams)

Relo helps developers explore and understand large codebases. Developers often face code that is hard to understand with over half their time being spent on understanding code. Relo allows developers to easily create relevant and intuitive diagrams, along with features to help automatically build diagrams based on the users past navigation.

While Relo diagrams are similar to UML, they also allow developers to zoom in to view details and edit the code using embedded text editors. These diagrams represent only a small manageable part of the code and do not include irrelevant details, thus allowing a developer to focus on important code relationships.

Java - Javascript interaction

Many of us using javascript in daily coding.I am a java developer and using ajax with applet also.And i need to call applet methods from javascript.

Actually i knew this while i was facing a strange problem (ofcourse it was strange for me becasue i was not aware of this!). The applet used is compiled in JRE 1.4.0.And whenever anyone having JRE version newer than 1.4.0 tried accessing that applet, the call from javascript to applet method gives error "Object doesn't support this property". So i was very much tired of compiling applet with different versions of Jre but no luck.

So once i found the <param> tags for <Object> element which is now used for applet in HTML code.And then i used these tags for java and javascript interaction.

we will look at what parameters we should use the applet and object tags to 'switch on' the java-js communications.

According to the java 5 documentation, if you use the APPLET tag, you do not need any special parameters to allow a javascript to call the applet's method. On the other hand if you use the OBJECT tag you need to use the scriptable parameter. Things use to be slightly different in the older versions.

For an applet to call javascript methods, all you need to do is add the mayscript parameter

so the tags are
<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
width= "290" height= "290" style="border-width:0;" id="rup" name="rup"
codebase="http://java.sun.com/products/plugin/autodl/
jinstall-1_4_1-windows-i586.cab#version=1,4,1">

<param name="archive" value="jsapplet.jar">
<param name="code" value="com.raditha.articles.JSHelloWorld">
<param name="mayscript" value="yes">
<param name="scriptable" value="true">
<param name="name" value="jssapplet">
</object>
The object tag can actually cause the most recent version of the java plug in to be downloaded if the user does not have it installed or if the version present is older than the minimum requirement (in this case 1.4.1). If you want to be able to do the same for Netscape Navigator the object tag has to change slightly:
<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
width= "290" height= "290" style="border-width:0;" id="rup" name="rup"
codebase="http://java.sun.com/products/plugin/autodl/
jinstall-1_4_1-windows-i586.cab#version=1,4,1">

<param name="archive" value="jsapplet.jar">
<param name="code" value="com.raditha.articles.JSHelloWorld">
<param name="mayscript" value="yes">
<param name="scriptable" value="true">
<param name="name" value="jsapplet">
</object>
Calling applet method from javascript is simple. You just need to do document.getElementById("appletid").methodName();
But calling javascript from Applet is somewhat tricky.

In order to call javascripts we need to get hold of a JSObject. But first things first, we need to import the netscape.javascript.JSObject into our class.
public void init()
{
jsObj= JSObject.getWindow(this);
}

All that remains to do is to add the JButton to our applet. Then we add an ActionListener to the JButton, and it's actionPerformed method calls the javascript.
public void actionPerformed(ActionEvent e) {
if(jsObj != null )
try {
jsObj.call("updatePage", new String[] {txt.getText()});
}
catch (Exception ex) {
ex.printStackTrace();
}
}
thats it! it will call the method from jsObj.

hope this helps someone like me for first time.Enjoy!

Java Spring Framework : Multiple PropertyPlaceholderConfigurer configurtion

This is very small thing which can be very annoying while coding in spring framework. Of cource no one can directly understand the problem until he faced that.

At first, I had only one property file from which i am reading some values into spring applicationContext Xml configuration file.So when i needed to add second one for my new feature, i think it is just to add new propertyPlaceholderConfigurer bean with second prop file.

my first prop file 'default-prop.properties' is :
default-prop.custName=testing customer
default-prop.address=building1
and the bean definition in the applicationContext xml file for this is:

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:default-prop.properties</value>
</property>
</bean>

so while adding second one, i have just added second bean for it like:
<bean id="propertyConfigurerNew"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:second-prop.properties</value>
</property>
</bean>
and in xml, prop has been read as,
<property name="customerName" value="${default-prop.custName}" />
But when i done this, i got error
"Could not resolve placeholder 'default-prop.custName' "
So i have to do some workaround and digg into spring references. And i found that we can define seperate placeHolderPrefix and suffix for each property configurer bean.

I have changed the bean definition as,
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:default-prop.properties</value>
</property>
<property name="placeholderPrefix" value="${" />
<property name="placeholderSuffix" value="}" />
</bean>

<bean id="propertyConfigurerNew"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:second-prop.properties</value>
</property>
<property name="placeholderPrefix" value="#[" />
<property name="placeholderSuffix" value="]" />
</bean>
it means, for first prop bean, we will use ${default-prop.custName} and for second bean we will use #[second-prop.secondName]

And voila! it solved my problem...

You can also use
<property name="ignoreUnresolvablePlaceholders" value="true" />
for each PropertyPlaceholderConfigurer bean defined. But, i have used the prefix-suffix one solution.
And my problem is resolved.

Give your comments on this problem and solution.