MDA Approach for Card Scheme conversion

The idea is to use MDA approach for conversion of one card schema to the other one. The traditional way is to write java code field by field. What I suggested is to use MDA (Model Driven Approach) for the conversion. The idea is to define the model in a kind of object model, use XML to make the model and create the framework to execute the mode.

During the implementation I understood that usage of standard EL (Expression Language) would be very handy and I successfully tried Juel.

In this way, the conversion rules are much more meaningful and understandable. It is also possible to change them dynamically without recompiling.

There is only one important negative point and that one is type safety. Not all expression in Juel are checked against syntax in type of loading. My next task on this subject is to find how can I guaranty type safety, at least at the same level as java code.

Posted in java | Tagged , , | Leave a comment

Default page in Tapestry

In the current release of Tapestry version 5.0, there is an odd behavior about default index page. Here is the problem. I have used Tynamo for enforcing security. The desired behavior is that all pages should be authenticated. If you access them, before logging you should be redirected to /login.tml page. Our main page is set as default /index.tml page.

you can configure tynamo on which pages to protect in AppModule.contributeSecurityConfiguration

          configuration.add(factory.createChain("/login").add(factory.anon()).build());
	  configuration.add(factory.createChain("/").add(factory.authc()).build());

this works fine, as you long as access the main page by directly accessing root at http://server.port/app/

But what happens if you try to access a non existent page, some thing like http://server.port/app/blahblah ? strange unchangeable behavior of tapestry, directs this url to default index page, after that it is checked by tynamo. So your protected page is revealed easily. Tynamo has also no way to protect wild pages with exception. Something like

	  configuration.add(factory.createChain("/**").add(factory.authc()).build());

will also protect /login.tml and prohibits logging in.

The best I came to, was to move the index page to some other page, say /processlist and protect by tynamo. I changed the Index.java to:

public class Index {
	Object onActivate() throws MalformedURLException {
		return ProcessList.class;
	}
}

Now if you access your arbitary page, it is redirected to the main page, but this time before security checking and every thing works fine.

Posted in java, Tapestry | Tagged , | Leave a comment

Activiti and Hibernate/tynamo integration

We are using Tapestry as MVC framework in the company and we needed to integrate a sample tapestry based with activiti security tables.

“Apache Shiro” and “Tynamo” are used. “Apache Shiro” is a Java security framework from Aapche. Tynamo  helps in using Shiro in Tapestry. In this post I am going to explain how Activiti security could be used in Tapestry web based applications.

 

Target:

Target is creating a web based application. The related page should be visible only after authentication. For authentication these conditions should be validated:

1. User should exist in “act_id_user” table

2. password should match to the password in the same table.

3. In “act_id_membership” table, user should be associated with “admin” group
 
Activiti realm:

In Shiro, different realms are foreseen. JDBC, LDAP, Active. So one way is to create a new “Activiti Realm” and configure Shiro to use it, and configure Tapestry to use Shiro.

Creating ActivitiRealm is simple. You have to extend AuthorizingRealm class and implement doGetAuthenticationInfo member and put the authentication logic in it. Something like this:

 

@Override
protected AuthenticationInfo doGetAuthenticationInfo(
   AuthenticationToken token) throws AuthenticationException {
      UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
      String username = usernamePasswordToken.getUsername();
      char[] pswrd = usernamePasswordToken.getPassword();
      String password = String.copyValueOf(pswrd);

      // check if the username and password are correct
      IdentityService identityService = processEngine.getIdentityService();
      if (!identityService.checkPassword(username, password)) {
          throw new IncorrectCredentialsException();
      }

      // check if the username ins member of "admin" role
      GroupQuery query = identityService.createGroupQuery();
      if (query.groupMember(username).groupName(ADMIN_ROLE).count() == 0) {
         throw new IncorrectCredentialsException();
      }
      return buildAuthenticationInfo(username, password);
}

 

Service Injection:

As you may have seen in the above code, processEngine is just used. It is injected by Tapestry Injection framework. It could be injected in Spring configuration file or in build method in AppModule. In this implementation Spring based configuration is used. This code snipplet in application-context.xml file will do the job:

   

 
Configure Shiro to use Activiti Realm
Now we have the realm and we have to make shiro use our new realm.
This method in AppModule.java will make shiro use the realm:

@Contribute(WebSecurityManager.class)
public static void addRealms(Configuration configuration, @Autobuild ActivitiRealm activitiRealm) {
configuration.add(activitiRealm);
}

 
Login page
Shiro is configured and can be used for checking security. Now we need a login page. It is possible to use default login page, but here I prefer to have my own login page.
The page is a normal login page, like in any other one. Just in validation, such a code uses Shiro for authentication:

public Object onActionFromJsecLoginForm()
{

   Subject currentUser = securityService.getSubject();

   if (currentUser == null) {
      throw new IllegalStateException("Subject can`t be null");
   }

   UsernamePasswordToken token = new UsernamePasswordToken(jsecLogin, jsecPassword);
   token.setRememberMe(jsecRememberMe);

   try {
      currentUser.login(token);
   } catch (UnknownAccountException e) {
      loginMessage = "Account not exists";
      return null;
   } catch (IncorrectCredentialsException e) {
      loginMessage = "Wrong password";
      return null;
   } catch (LockedAccountException e) {
      loginMessage = "Account locked"; 
      return null;
   } catch (AuthenticationException e) {
      loginMessage = "Authentication Error";
      return null;
   }

   SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(requestGlobals.getHTTPServletRequest());

  
   if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase("GET")) {
      try {
        response.sendRedirect(savedRequest.getRequestUrl());
        return null;
      } catch (IOException e) {
        logger.warn("Can't redirect to saved request.");
        return Index.class;
      }
  } else {
     return Index.class;
  }
}

 
Configure Tapestry to use Shiro for security
Ok, everything is there. Now we have to configure Tapestry to use Shiro for security and secure desired pages.
First we have to introduce our login page. Shiro will redirect user to this page, whenever he wants to access to a secured page and he is not logged in. This code in AppModule does this task:

@Contribute(SymbolProvider.class)
@ApplicationDefaults
public static void applicationDefaults(
    MappedConfiguration<String, String> configuration) {
    // Tynamo's tapestry-security (Shiro) module configuration
       configuration.add(SecuritySymbols.LOGIN_URL, "/login");
}

and the last thing is to let Shiro know which pages should be protected:

public static void contributeSecurityConfiguration(Configuration configuration,
SecurityFilterChainFactory factory) {
   // /authc/** rule covers /authc , /authc?q=name /authc#anchor urls as well
   configuration.add(factory.createChain("/login").add(factory.anon()).build());

   configuration.add(factory.createChain("/assets/**").add(factory.anon()).build());
   configuration.add(factory.createChain("/myPage").add(factory.authc()).build());
   configuration.add(factory.createChain("/").add(factory.authc()).build());
}

this configuration make the “/login” accessible without authentication and put protection on “/assets/”, “/myPage” and “/” pages.

Done, Done.

 

Posted in activiti | Tagged | Leave a comment

The basic usage of BPMN Boundary event, just sends a string named as ErrorCode. For some cases it might not be enough. We just had an interesting discussion in activiti forum about what should be proper definition according to the specification.

Discussion could be followed in issues    act-1411  and  act-462.

 

Here is the summary of my latest conclusion:

a clearer and more direct diagram is Figure 10.69 in section 10.4. It is clearly mentioned that “intermediate catch event” is inherited from “Catch Event” which is associated with “DataOutputAccociation”. On the other hand, “Intermediate Throw Event” is inherited from “ThrowEvent” which is associated with “DataInputAssociation”.

It could also be seen in xsd. in “Table 10.113 – IntermediateCatchEvent XML schema” is inherited from “tCatchEvent” which is explained in “table 10.104 – Catch Event XML Schema”. And there association with “DataOuput” and “DataOutputAssociation” is clear. With the same logic “dataInput” and “dataInputAssociation” is stated for “intermediate Throw Event”.

So the the catching part should be something like this:
<intermediateCatchEvent id=”myIntermediateCatchEvent” >
<XXXEventDefinition/>
<dataOutputAssociation>
<targetRef>dataOutputOfProcess</targetRef>
<transformation>${dataOutputOfServiceTask.prettyPrint}</transformation>
</dataOutputAssociation>
</intermediateCatchEvent>

and throwing part can be something like:
<intermediateCatchEvent id=”catchSignalEvent” name=”On Alert”>
<!– signal event definition –>
<XXXEventDefinition” />
<dataInputAssociation>
<sourceRef>PrefixVariable</sourceRef>
<targetRef>prefix</targetRef>
</dataInputAssociation>
<dataInputAssociation>
<sourceRef>SuffixVariable</sourceRef>
<targetRef>suffix</targetRef>
</dataInputAssociation>
</intermediateCatchEvent>

of course, with whistles and bells defined in activiti guide

Posted on by smirzai | Leave a comment

Using Activiti with Xform

Preface:

Thank you Joram to motivate me to write this post and explains what is mentioned in this post in more details.

We are using Activi in our company. Activiti provides an explorer application which is based on Vaadin. Vaadin is a Javascript based web framwork and extends Google GWT.

My first problem with this approach is that a new protocol for form definition is created from scratch. There are already mature form definition protocols with lots of open source and commercial implementations available. So why to reinvent the wheel ? Xform maybe the best standard available today. It is a little bit old and forgotten, but still works fine.

My second problem is the framework used. Vaadin is wonderful, but it is not easy to integrate it with other main stream servlet based frameworks.

First I tried to make current Vaadin based implementation to use Xform instead of home made protocol used in it. I spent several days on the subject and was persuaded that it is not easy if not impossible. One of the problems is discussed here in Vaadin forum.

To select a rendering engine, first I took ronal.van.kuik’s advice in this thread and selected BetterForms open source Xforms implementation. I was not able to configure it properly to work well in a short time. So I tested Orbeon, another open source implementation.This time it went well. I was able to create a proof of concept easily. Here I explain how it works.

Orbeon Integration

First of all Orbeon needs to be installed on the tomcat. Orbeon could be configured to process the Xforms for another application. First it should be deployed as a seperate web application, say /orbeon. It is a stand alone application with a nice user interface for management and even designing new forms. But what we need here is the form rendering functionality. For this, a jar file should be copied in the application and configured as a filter. This filter checks the HTTP traffic and renders any xforms content in it.

Details for configuration of Orbeon could be found here. Installation is very straight forward.  I used “seperate configuration” option, though “Integrated application” also does not seem to be much different.

Xforms file assignment

The next step is to define a standard for assigning the user task to a specific xforms file. Our application uses static tapestry forms. It is desired that application be backward compatible and can support traditional static forms. For this, I selected to add an “xform:” string to the start of the form name, if it is going to be rendered by Xforms engine. Else it will be processed as usual.   Here is how the definition looks like:

<userTask
id="utProvideMerchantMainInfo" name="Provide merchant main info"
activiti:formKey="xforms:merchant/ProvideMerchantMainInfo">
</userTask>

Rendering Xforms 

Now is the time to do the main part of the job and render the form. The form reading should be dynamic. As Orbeon filter is configured, it is enough to copy the content of xforms  file to  http output. To do this, i have created a Servlet. This servlet simply, gets the file name containing xform from a request parameter and copies the content of the file to http stream.

Here is the code for servlet:

String formName = request.getParameter(PARAM_XFORM_NAME);
String resourceName = "/xforms/" + formName + ".xhtml";
String line;
Writer writer = response.getWriter();
while ((line = reader.readLine()) != null) {
writer.write(line);
}

and here is its mapping in web.xml


<servlet>
<servlet-name>xformActiviti</servlet-name>
<servlet-class>net.atos.xa.mac.admin.xform.XformsRendererServlet</servlet-class>
</servlet>


<servlet-mapping>
<servlet-name>xformActiviti</servlet-name>
<url-pattern>/xforms/renderer</url-pattern>
</servlet-mapping>

now in the application, it is enough to set the file name parameter and forward the page to renderer servlet:

if (formPrefix == FormPrefix.XFORMS) {
formKey = FormPrefix.removePrefix(formKey);
Link link = new LinkImpl("/xa-mac-admin" + "/xforms/renderer", false,
false, response, null);
link.addParameter(XformsRendererServlet.PARAM_XFORM_NAME, formKey);
link.addParameter("taskId", taskId);
return link;

That was the main part, now the form is rendered by orbeon filter. Orbeon filter, also cares for events and ajax like interactions.

Submitting the xform

After the user sees the rendered xform, he fills into the fields and submits the form. In Xform standard, xforms:submission is responsible for this. Xform engine creates an xml file with from input data and sends the generated xml to the url mentioned in xforms:submission tag.

here is a sample value for this tag in our xform:

<xforms:submission action="http://localhost:8080/xa-mac-admin/xforms/submit" method="post"
id="submit" includenamespaceprefixes="" />

The xml is sent to the above url. Again we need a servlet to receive xml file, parse it and complete the task. The source for the code is a little bit long and trivial.

Initial values of  xform fields

The above procedure was the first step and usually the form in this step is clear. But it is probable that in the next steps, some of the previously input data should be shown. Again for this purpose, an xml document should be created and sent to Xform engine.

Posted in activiti | Tagged | 25 Comments

Class debug in eclipse

This could be very useful when debugging class files with no source:
http://stackoverflow.com/questions/1905446/how-to-debug-compiled-java-code-in-eclipse

Posted in java | Tagged | Leave a comment

How to build activiti user guide

Simple

just go to useruide directory and run:

ant build.userguide 

 

 

Posted in activiti | Tagged | Leave a comment

A turtle named Hibernate

Hibernate, is a fantastic tool, as long as it is not used in very high number of transactions. In our case for a transactional  application, with a relatively complex data model, it is disastrous. It is one single hibernate insert, which is translated to 5 related sql inserts. Oracle 11g is the test database.

Database tools report less than ms for the real database work.

about 16 ms, is spent on oracle JDBC drivers. And guess how much is spent by hibernate.

about 90 ms.  

I am working on it. Stay tuned.

Posted in java | Tagged | Leave a comment

Cygwin Slash and Backslash

When you are working in sygwin and tools like Subversion, then you might face the same problem as me. The problem is that output of svn st for example is using \ instead of / and you cannot easily cut and paste the results and use other linux based tools.

This sed command corrects it 

svn st | sed ‘s:\\:/:g’

Till now I was not able to make it easier using alias or function.

Posted in linux | Tagged | Leave a comment

stand alone JNDI providers

I am need to find some non container based JNDI providers. Here is a short list:

 

1. Sun filesystem provider (http://java.sun.com/products/jndi/serviceproviders.html)

2. Spring JNDI

3. Apache Harmony (RMI based)

4. Google Simple Jndi

5. ActiveMQ jndi provider

 

 

Posted in java | Tagged | 1 Comment