Catching Expected And Unexpected Faults In BPEL

In BPELs in WebSphere Integration Developer we can catch exceptions – faults from a BPEL, like during an invoke for example.

image

What happens when we want to catch an exception that is not necessarily a fault and could stem from the underlying  system or the application behind the invoke(in the diagram it is InvokeSomeOperation)?

As you can see in the above excerpt of a BPEL, we have a known Fault called MyApplicationFault in the catch and then in the Catch All we deal with any unknown faults that are not MyApplicationFault and just exceptions that are not BPEL faults at all.

So if we have a NumberFormatException for example it will pass the MyApplicationFault catch and go the Catch All.

Now if we want to transform any exception that comes through in a BPEL exception that will be like a fault we can use an anonymous class in a snippet:

 

new BpelException(){

 

public String getFaultName() {

return “MyFaultName”;

}

 

public String getMessage() {

return caughtException.getMessage();

}

};

 

This way we can handle the exception elsewhere in the BPEL Process using:

com.ibm.bpe.api.BpelException bpelexception =

getCurrentFaultAsException();

logger.debug(“Fault Name” +

bpelexception.getFaultName());

bpelexception.printStackTrace( System.out);

Throwable rootCause = bpelexception.getRootCause();

 

So the Catch All can accept normal java exceptions as well as BPEL faults Smile

Advertisements

Securing a BPEL in WebSphere Integration Developer 7 difference over WebSphere Integration 6

 

Hi, another day in the windy city Smile Today we look at how to add a role-based security to secure a BPEL.

In WebSphere Integration Developer(WID) 6 there was no direct way to add a role to a BPEL at assembly level.

In WID 7 we can assign a role to the whole BPEL this could not be done in WID 6. It makes security much easier.

All you have to do is open your assembly diagram as in our example project below:

image

 

 

Click anywhere on the assembly diagram. Then click Properties on the BPEL and then click All Qualifiers.

Expand ExtractionProcess. As you can see above the is Security Identity. Here you can place a security role:

image

 

There you have it the entire Process is secured. On deployment make sure that role is allocated to a user that should have access to the BPEL application:

image

That’s all there is to it! Enjoy Smile

Jasper Reports – Fields And Fonts On Different Operating Systems

Jasper Reports – Fields And Fonts

I have been using Jasper Reports for a while and an interesting senario came to light. This is to do with fields been truncated on linux systems when the report is generated.

For example if we generate a csv file and in the report we have a field as follows:

<textField isBlankWhenNull=”true”>
<reportElement x=”76″ y=”0″ width=”63″ height=”11″/>
<textElement>
<font size=”6″/>
</textElement>
<textFieldExpression class=”java.lang.String“>

<![CDATA[“‘” + $F{user_id}]]></textFieldExpression>
</textField>

The above generated a report in which the field user_id (which is 18 characters wide) displayed all 18 characters on Windows Vista but on linux it truncated the last two and we only had 16 characters displaying.

On researching the issue I found that this problem had in deed manifested itself in a few places on the internet.

I found out that the different ways each operating systems handles the fonts caused this problem.

Increasing the width solved this partially:

<textField isBlankWhenNull=”true”>
<reportElement x=”76″ y=”0″ width=”70″ height=”11″/>
<textElement>
<font size=”6″/>
</textElement>
<textFieldExpression class=”java.lang.String“>

<![CDATA[“‘” + $F{user_id}]]></textFieldExpression>
</textField>

However another problem came to light and this was that on different versions of SUSE the generated report appeared differently.

On one version it printed correctly yet on another it still truncated the field.

When running a uname -arv on the machine that worked we have:

admin: uname -arv
Linux xserver1 2.6.5-7.257-nh1 #4 SMP Tue Jun 6 15:45:06 SAST 2006 i686 i686 i386 GNU/Linux

When running uname -arv on the machine that didn’t work we have:

admin: uname -arv
Linux xserver2 2.6.5-7.244-xeon #3 SMP Tue Nov 28 14:18:50 SAST 2006 i686 i686 i386 GNU/Linux

Seems the differences in the build version of the kernel make a difference which is an interesting observation .

The problem was resolved by extending the width once again:

<textField isBlankWhenNull=”true”>
<reportElement x=”76″ y=”0″ width=”87″ height=”11″/>
<textElement>
<font size=”6″/>
</textElement>
<textFieldExpression class=”java.lang.String“>

<![CDATA[“‘” + $F{user_id}]]></textFieldExpression>
</textField>

 

This time it worked on all three machines.

Picking Dates in Struts 2 and JQGrid

I have spent sometime analysing the power of Struts 2 and JQGrid. In a time when so many frameworks are out there, so many projects, some of which perform code generation, the question is can Struts 2 still have a place in the new world, the new era that has seen the rise of web technologies with mouth watering graphics and tantalizing visual effects?

I am happy to say that yes it can. Within the JQGrid Struts 2 is a framework that has the capability to make it through and past 2010 into the second decade of this new century that has dawned upon us.

Today I write about dates and date picking in the Struts 2 JQGrid plugin. The reason being there seems to be, to my knowledge, no clear explanation on this. In my next post I will give a full tutorial on the use of JQGrid and more comprehensive coverage on this wonderful plugin.

We want to be able to have a date picker in the Add Record screen. In the picture below confirmBy is a date field and when we click on it:

Also when we edit a record, on the Edit Record screen, we click on the date field we have:

The settings for this are as follows. First in the sjg:GridColumn we have:

Where the datePick function will be:

There we are. We have added date picking functionality in the Add Record screen and the Edit Record screen.

 

Digesting Struts 2 and Dojo

Digesting Struts 2 and Dojo

I was playing around with Struts 2 and Ajax mainly Dojo. Now how would one wire a struts action to return Dojo – JavaScript object? We will examine this below and setup a sample app that will use Struts and Dojo. We offer this as an alternative to JSON. The advantage of this over JSON is that an exist Struts 2 application could still generate JavaScript Objects without interfering with the Java classes. So where as when JSON is used your program must return a JSON object here your program can return normal data to pages and from these JavaScript objects can be constructed and used.

We will load a user’s information on selection of the user and dynamically append the user’s details.

 

Once the user is selected we will have his information dynamically appended to the screen as below:

 

The way this application will function is that struts will on success return a result to a JSP that will then dynamically have the XML created. The dojo.io.bind will then read in this XML and generate a JavaScript object with which we can use to update the page. We will start by creating the project for the application in Eclipse (Similar process for Netbeans)

 

The classes look like:

LoadUser.java

package struts2dojoexample.action;

 

import java.io.IOException;

 

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.struts2.ServletActionContext;

import org.apache.struts2.interceptor.ServletRequestAware;

import org.apache.struts2.interceptor.ServletResponseAware;

 

import struts2dojoexample.pojo.User;

 

import com.opensymphony.xwork2.ActionSupport;

 

public class LoadUserAction extends ActionSupport implements ServletRequestAware,

ServletResponseAware {

 

private String user;

private String username;

private String password;

private HttpServletRequest request;

private HttpServletResponse response;

 

public String execute() {

User user1 = new User();

user1.setUsername(“Gabriel”);

user1.setSurname(“Campbell”);

user1.setEmailAddress(“gjcbell@hotmail.com”);

user1.setStreetAddress(“On Earth”);

 

// Put the DTO in request so we can use it to render XML in the JSP.

getServletRequest().setAttribute(“user”, user1);

return SUCCESS;

}

 

public void setUsername(String username) {

this.username = username;

}

 

public String getUsername() {

return username;

}

 

public void setPassword(String password) {

this.password = password;

}

 

public String getPassword() {

return password;

}

 

public void setUser(String user) {

this.user = user;

}

 

public String getUser() {

return user;

}

 

 

public void setServletRequest(HttpServletRequest request){

this.request = request;

}

 

public HttpServletRequest getServletRequest(){

return request;

}

 

public void setServletResponse(HttpServletResponse response){

this.response = response;

}

 

public HttpServletResponse getServletResponse(){

return response;

}

 

}

 

 

As you can see in Struts 2 you can implement ServletRequestAware and ServletResponseAware

When these are implemented we now have access to our session.

User.java

package struts2dojoexample.pojo;

 

import java.lang.reflect.Field;

 

public class User {

 

private String username;

private String password;

private String surname;

private String emailAddress;

private String streetAddress;

 

public void setUsername(String username) {

this.username = username;

}

 

public String getUsername() {

return username;

}

 

public void setPassword(String password) {

this.password = password;

}

 

public String getPassword() {

return password;

}

 

public void setSurname(String surname) {

this.surname = surname;

}

 

public String getSurname() {

return surname;

}

 

public void setEmailAddress(String emailAddress) {

this.emailAddress = emailAddress;

}

 

public String getEmailAddress() {

return emailAddress;

}

 

public void setStreetAddress(String streetAddress) {

this.streetAddress = streetAddress;

}

 

public String getStreetAddress() {

return streetAddress;

}

 

public String getAsXML(){

StringBuffer sb = new StringBuffer(512);

sb.append(“<user username=\”” + username + “\” “);

sb.append(“surname=\”” + surname + “\” “);

sb.append(“emailAddress=\”” + emailAddress + “\” “);

sb.append(“streetAddress=\”” + streetAddress + “\”>\n”);

sb.append(“</user>\n”);

return sb.toString();

}

/**

* Overriden toString method.

*

* @return A reflexivelybuilt string representation of this bean.

*/

public String toString() {

 

String str = null;

StringBuffer sb = new StringBuffer(1000);

sb.append(“[“ + super.toString() + “]={“);

boolean firstPropertyDisplayed = false;

try {

Field[] fields = this.getClass().getDeclaredFields();

for (int i = 0; i < fields.length; i++) {

if (firstPropertyDisplayed) {

sb.append(“, “);

} else {

firstPropertyDisplayed = true;

}

sb.append(fields[i].getName() + “=” + fields[i].get(this));

}

sb.append(“}”);

str = sb.toString().trim();

} catch (IllegalAccessException iae) {

iae.printStackTrace();

}

return str;

 

} // End toString().

}

 

Next we have the web.xml:

 

 

 

 

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

 

<web-app version=“2.4” xmlns=http://java.sun.com/xml/ns/j2ee&#8221; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&#8221;>

 

<display-name>Struts2Dojo</display-name>

<filter>

<filter-name>struts2</filter-name>

<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

<init-param>

<param-name>actionPackages</param-name>

<param-value>struts2dojoexample</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>struts2</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<!– Session timeout config. –>

<session-config>

<session-timeout>30</session-timeout>

</session-config>

 

<!– Welcome file config. –>

<welcome-file-list>

<welcome-file>/LoadUser.jsp</welcome-file>

</welcome-file-list>

</web-app>

 

The struts.xml

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

<!DOCTYPE struts PUBLIC

“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”

http://struts.apache.org/dtds/struts-2.0.dtd&#8221;>

 

<struts>

 

<constant name=“struts.devMode” value=“true” />

 

<package name=“default” namespace=“/” extends=“struts-default”>

<action name=“LoadUserAction” class=“struts2dojoexample.action.LoadUserAction”>

<result name=“success”>/User.jsp</result>

</action>

</package>

</struts>

 

The javascript files are list below:

 

We have the ControlEvents.js this is where we control the events the user creates like the select list drop down menu.

Dojo.js is the dojo toolkit downloadable from http://www.dojotoolkit.org/

User.js is the script file container the user object in JavaScript. In the ControlEvents.js we use the JSDigester that is provided by the JavaWebparts tags. This enables us to generated JavaScript objects.

ControlEvents.js looks like this:

 

var user = null;

var aconsole = null;

// This function is called when the User dropdown selection changes.

function loadUser() {

// If an operation is in progress, usually involving the server, don’t do it.

//if (processing) { return false; }

// Get name of selected collection.

var username =document.getElementById(“userslist”).value;

// Ignore the first item, our “dummy” collection.

if (username == “none”) {

return false;

}

// Make AJAX call.

dojo.io.bind({

url: “LoadUserAction.action”,

content: {user: username},

error: function(type, errObj) { alert(“Error”); },

load: function(type, data, evt) {

// Now that we have received back the XML describing the collection,

// we’ll use JSDigester to parse it.

var jsDigester = new JSDigester();

jsDigester.addObjectCreate(“user”, “User”);

jsDigester.addSetProperties(“user”);

user = jsDigester.parse(data);

aconsole=document.getElementById(“console”);

if (aconsole != null ) {

removeAllChildren ( aconsole );

}

var div = document.createElement(“p”);

var txt=document.createTextNode(“Name: “ +user.username );

div.appendChild ( txt );

txt=document.createTextNode(“Surname: “ +user.surname );

var div1 = document.createElement(“p”);

div1.appendChild ( txt );

txt=document.createTextNode(“Email Address: “ +user.emailAddress );

var div2 = document.createElement(“p”);

div2.appendChild ( txt );

txt=document.createTextNode(“Street Address: “ +user.streetAddress );

var div3 = document.createElement(“p”);

div3.appendChild ( txt );

aconsole.appendChild(div);

aconsole.appendChild(div1);

aconsole.appendChild(div2);

aconsole.appendChild(div3);

},

mimetype: “text/plain”,

transport: “XMLHTTPTransport”

});

}

 

function removeAllChildren( node ){

var childCount = node.childNodes.length;

for ( var count = 1; count <= childCount; count++) {

node.removeChild ( node.childNodes[0] );

}

}

 

User.js :

// User object.

function User() {

this.username = null;

this.surname = null;

this.emailAddress = null;

this.streetAddress = null;

}

User.prototype.setUsername = function(inName) {

this.username = inName;

}

User.prototype.getUsername = function() {

return this.username;

}

User.prototype.setSurname = function(inSurname) {

this.surname = inSurname;

}

User.prototype.getSurname = function() {

return this.surname;

}

User.prototype.setEmailAddress = function(inEmailAddress) {

this.emailAddress = inEmailAddress;

}

User.prototype.getEmailAddress = function() {

return this.emailAddress;

}

User.prototype.setStreetAddress = function(inStreetAddress) {

this.streetAddress = inStreetAddress;

}

User.prototype.getStreetAddress = function() {

return this.streetAddress;

}

User.prototype.toString = function() {

return “User=[username=” + this.username +

“,surname=” + this.surname +

“,emailAddress=” + this.emailAddress + “,streetAddress=” + this.streetAddress + “]”;

}

 

The libraries:

 

 

There some additional libraries for expansion of this application like the MySQL driver for Database connectivity to MySQL.

There you are it runs. So we managed to dynamically update a page and translate our Java in to JavaScript. This example could be extended and enhanced to embrace the vast functionality of the Dojo Toolkit.

Cheers,

Gabriel

 

 

 

 

 

Dating, Where clauses and Hibernate

I recently ran into an interesting problem involving hibernate and dates across different database systems mainly Microsoft SQL 2008 and IBM Informix.

It appears that in HQL queries you can use Informix’s today for obtaining the current date and time:

query = session.createQuery();

String whereClause = "from myTable where myDateColumn > today -10";

This query finds the today 10 days from the current time.

When we run the query as below:

List<MyTable> myTableResults = query.list();

THis executes successfully in IBM Informix but in MSSQL we get the following error:

column today not found

So what do we do now? it appears that NOW() does not work.

Looking through various information and issues on the internet and hibernate tutorial and forums I found that hibernate can support certain functions of a specific database. This ties in with the hibernate dialect and JDBC driver.

I found that GETDATE() works within the where clause. So updating the above to:

String whereClause = "from myTable where myDateColumn > GETDATE() -10";

This worked well. So this raises more questions. How can we in general see which functions the RDMS provides that hibernate will support in its HQL queries – the where clause?

It should be noted that in the select part of the query we have more freedom. As dates can be retrieved.

Also it should be noticed that MS SQL has a newer driver sqljdbc4.jar and sqljdbc.jar. The difference in these two is quite big when we consider dates. For example SQL 2005 had fewer date types then SQl 2008. So this leads to problems when using the older driver(sqljdbc.jar) on SQL 2008.

 

Another important insight is in the Dialect class there exists the method Dialect.getCurrentTimestampSQLFunctionName() which can give us the database-specific SQL function for retrieving the current timestamp.

Also we cannot use Java’s

new Date() in the where clause part of the query as this does not always work. The format the date will be in might not translate well into a string. We could try parameters in queries using AbstractQueryImpl.setParameter(String name, Object val).

However a problem could arise when using Java’s new Date() in as a paramter in a query as opposed to using a database function, this problem would be that time from Java would be based on the application as opposed to the database server itself. So if the two are at different locations and setup differently we could have problems.

Hence we can make our application cater for different types of RDMS systems based on the type and hence use various functions to aid development.

Hence when dealing with date types one has to be cautious specially if developing on an open source RDMS and then using a commerial RDMS. This saves on licencing but when deploy issues like dates can give problems!

Nice and Naughty Transactions in Hibernate and Spring

I came across a very interesting fact about Spring transaction management.

 

Spring provides us with two ways of handling transaction

1) Using proxies,

2) Using DI through the getTemplate() method.

 

Now what happens when we consider 1) we mean:

Declaring in an XML file the transactionManager and transactionTemplate bean:

 

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" singleton="true">

            <property name="sessionFactory">

                  <ref bean="sessionFactory" />

            </property>

      </bean>

      <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" singleton="false">

            <property name="transactionManager">

                  <ref bean="transactionManager" />

            </property>

      </bean>

 

Then we use proxies and provide:

 

<bean id="myTableManagerTx" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" singleton="true" lazy-init="true">

            <property name="transactionManager">

                  <ref bean="transactionManager"/>

            </property>

            <property name="target">

                  <ref bean="myTableManagerImpl"/>

            </property>

            <property name="transactionAttributes">

                  <props>

 

     

 

            <prop key=" *">PROPAGATION_NOT_SUPPORTED,readOnly</prop>

 

                  </props>

            </property>

            <property name="preInterceptors">

                  <list>

                        <ref bean="callMonitor"/>

                  </list>

            </property>

      </bean>

 

With the use of interceptors we can now use doInHibernate() and have transaction support without any extra coding:

 

protected Object updateObject(final Context ctx, final Object o) {

            return getHibernateTemplate().execute(new HibernateCallback() {

 

                  public Object doInHibernate(Session session) throws HibernateException, SQLException {

                        return update(ctx, session, o);

                  }

            });

      }

 

However we can use alternative 2)

 

            try {

                  TransactionTemplate transactionTemplate = SpringFactory.getTransactionTemplate( TransactionDefinition.ISOLATION_READ_COMMITTED, TransactionDefinition.PROPAGATION_REQUIRED, false );

                  return ( List )transactionTemplate.execute( new TransactionCallback() {

 

                        public Object doInTransaction( TransactionStatus transactionStatus ) {

                              return getMyTableDAO().find( ctx, myId );

                        }

                  } );

            } catch( Exception e ) {

                  log.error( e.getMessage(), e );                

            }

 

Here we are programmatically creating a transaction based on Spring’s DI.

 

What happens if we use both together? That is 1) and 2) in an application we could have errors like:

 

Session cannot be closed!

 

This is because we are using proxies for transactions and also programmatically controlling transactions. If our TransactionDefinition fields : PROPAGATION_REQUIRED, PROPAGATION_NEVER, PROPAGATION_NOT_SUPPORTED, PROPAGATION_REQUIRES_NEW etc are not adjusted and used correctly we could have problems and errors with sessions being closed prematurely and incorrectly controlled. Also the HibernateTemplate controls the sessions for us. As stated in the Spring documentation:

The central method is execute, supporting Hibernate access code implementing the HibernateCallback interface. It provides Hibernate Session handling such that neither the HibernateCallback implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions. For typical single step actions, there are various convenience methods (find, load, saveOrUpdate, delete).

 This can lead to sessions not being closed properly and resources not been freed and hence lead to memory leaks(Which I have experienced!).

 

Final word of advice is: carefully watch your transactions!