Passing variables to Activities using Parse Handlers

In an Activiti project I’m working on, we need to pass some variables in/out through the call activities. But there was a problem. We have too many processes and call activities in them. So managing those variables in all of them was a tedious task. Also missing one in or out tag will cause error in our execution.

The solution to this is adding in and out parameters on deploy. We’ve created some parse handlers extending from org.activiti.engine.parse.BpmnParseHandler and register it to the org.activiti.engine.ProcessEngineConfiguration. We are using org.activiti.spring.SpringProcessEngineConfiguration so I will go on with that but stand alone configuration will be similar.

You can learn how to define SpringProcessEngineConfiguration bean in your application using that guide.

First you need to define process configuration and process engine beans like this:

<bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
...
</bean>
  
<bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
	<property name="processEngineConfiguration" ref="processEngineConfiguration" />
</bean>

The dots will be filled soon.
If you are able to deploy and run your processes then we are ready to go. We need to implement our parser classes that will help us to register in and out parameters. Here I’ll implement a custom call activity parse handler for this, namely ParameterRegisteringCallActivityParseHandler.

The mechanism is simple:

package org.activiti.engine.impl.bpmn.parser.handler;
public class CallActivityParseHandler extends AbstractActivityBpmnParseHandler<CallActivity> {
  public Class< ? extends BaseElement> getHandledType() {
    return CallActivity.class;
  }
  
  protected void executeParse(BpmnParse bpmnParse, CallActivity callActivity) {    
    ActivityImpl activity = createActivityOnCurrentScope(bpmnParse, callActivity, BpmnXMLConstants.ELEMENT_CALL_ACTIVITY);
    activity.setScope(true);
    activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createCallActivityBehavior(callActivity));
  }

}

Our code will be like this:

public class ParameterRegisteringCallActivityParseHandler extends CallActivityParseHandler {
	@Override
	protected void executeParse(BpmnParse bpmnParse, CallActivity callActivity) {
		//super.executeParse(bpmnParse, callActivity);
		ActivityImpl activity = createActivityOnCurrentScope(bpmnParse, callActivity, BpmnXMLConstants.ELEMENT_CALL_ACTIVITY);
		activity.setScope(true);
		ProcessDefinitionEntity currentProcessDefinition = bpmnParse.getCurrentProcessDefinition();
		initDefaultInOutParameters(currentProcessDefinition, callActivity);
		activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createCallActivityBehavior(callActivity));
	}
}

I will come to initDefaultInOutParameters later but I want you to notice commenting out super call. The trick here, Activiti does not let us to add in or out parameter passing definitions after calling super. You can check out the conversation between me and Joram Barrez here. We’ve just stepped in while the call activity is being constructed.

So what is about initDefaultInOutParameters? Here is the details:

private void initDefaultInOutParameters(ProcessDefinition processDefinition, CallActivity callActivity) {
	final Set<IOParameter> defaultInParameters = getDefaultInParameters();
	final List<IOParameter> activityInParameters = callActivity.getInParameters();
	activityInParameters.addAll(defaultInParameters);

	final Set<IOParameter> defaultOutParameters = getDefaultOutParameters();
	final List<IOParameter> activityOutParameters = callActivity.getOutParameters();
	activityOutParameters.addAll(defaultOutParameters);
}

private Set<IOParameter> getDefaultInParameters() {
	final Set<IOParameter> ioParameters = new HashSet<IOParameter>();

	final IOParameter currentCallActivityIdParameter = getCurrentCallActivityIdParameter();
	ioParameters.add(currentCallActivityIdParameter);

	final IOParameter someCustomParameter = getCustomParameter();
	ioParameters.add(someCustomParameter);

	return ioParameters;
}

private Set<IOParameter> getDefaultOutParameters() {
	final Set<IOParameter> ioParameters = new HashSet<IOParameter>();

	final IOParameter someCustomParameter = getCustomParameter();
	ioParameters.add(someCustomParameter);

	return ioParameters;
}

As you can see I’ve defined 2 default in parameters and 1 out. One of the in parameters is same with the out one. That means that parameter will be passed in and out for each call activity in the process definition. If you have nested call activities, then it will be passed to and from them too. You can update the value of it and then set to the execution, this parameter will passed out up and up until root execution and you will have the updated value on your root execution.

Implementation of those methods, getCurrentCallActivityIdParameter, getCustomParameter are like this:

private IOParameter getCurrentCallActivityIdParameter() {
	final String sourceExpression = "${execution.currentActivityId}";
	final String target = "CALL_ACTIVITY_ID_VARIABLE_NAME";
	return getIoParameterForSourceExpression(sourceExpression, target);
}

private IOParameter getCustomParameter() {
	final String sourceExpression = "${SOME_VARIABLE_NAME_WHOSE_VALUE_WILL_BE_UPDATED}";
	final String target = "SOME_VARIABLE_NAME_WHOSE_VALUE_WILL_BE_UPDATED";
	return getIoParameterForSourceExpression(sourceExpression, target);
}

protected IOParameter getIoParameterForSourceExpression(final String sourceExpression, final String target) {
	final IOParameter ioParameter = new IOParameter();
	ioParameter.setSourceExpression(sourceExpression);
	ioParameter.setTarget(target);
	return ioParameter;
}

First method, getCurrentCallActivityIdParameter, adds to your call activity definition this:

<activiti:in sourceExpression="${execution.currentActivityId}" target="CALL_ACTIVITY_ID_VARIABLE_NAME"/>

So when you deploy your process definition, it is added to the call activity definition. When the execution reaches to your call activity, this call activity’s id is got and written to the call activity’s execution context. That can be useful for logging.

Second method, notice it is called for in and out, adds to your call activity definition this:

<activiti:in sourceExpression="${SOME_VARIABLE_NAME_WHOSE_VALUE_WILL_BE_UPDATED}" target="SOME_VARIABLE_NAME_WHOSE_VALUE_WILL_BE_UPDATED"/>
<activiti:out sourceExpression="${SOME_VARIABLE_NAME_WHOSE_VALUE_WILL_BE_UPDATED}" target="SOME_VARIABLE_NAME_WHOSE_VALUE_WILL_BE_UPDATED"/>

When the execution hits to your call activity, a new execution context is created. There are 2 execution context at this time, one parent and one child(call activity). Activiti will try to find the variable named SOME_VARIABLE_NAME_WHOSE_VALUE_WILL_BE_UPDATED and get its value. Beware, you should have a variable named SOME_VARIABLE_NAME_WHOSE_VALUE_WILL_BE_UPDATED even if its value is null, otherwise you will get NullPointerException. After getting its value, Activiti writes the value to child execution context with same name. After completing call activity, same is done but in reverse direction. You can update it in call activity or just leave as it is.

The final touch, org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl, which org.activiti.spring.SpringProcessEngineConfiguration is extending from has a property definition that lets us to register our parsers: customDefaultBpmnParseHandlers

So bean definition becomes this:

<bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
	<property name="customDefaultBpmnParseHandlers">
		<list>
			<ref bean="parameterRegisteringCallActivityParseHandler"/>
		</list>
	</property>
</bean>
  
<bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
	<property name="processEngineConfiguration" ref="processEngineConfiguration" />
</bean>

<bean id="parameterRegisteringCallActivityParseHandler" class="my.pkg.ParameterRegisteringCallActivityParseHandler"/>

Hope this helps if you face with something similar.

Unit Test: JUnit 4 and Mockito

Hi,

This post is about unit testing. Writing tests, as you already know, is very important. The more important thing, as I learnt lately, is writing testable code. Writing testable code requires more intelligent designs and hard work. Also you must expect your workers or colleagues or boss might be get upset when you try to write or make them to write testable code, because it will take time. But think that way; you write your business logic in 3 days and writing tests on them takes 10 days. Not this only, you change your business logic whenever you get stuck on writing test, and worst you drop writing test at all. Am I exaggerating? No, I don’t think so. You must spend your time on your business logic, it will be responsible for work not tests. So, maybe you are asking yourselves that why I’m writing tests. In fact if you are here, then you know the importance of it. You can (and should) read from Miško Hevery‘s blog. He is fantastic and he has valuable thoughts on testing. I’m stopping talking about philosophy of testing and coming to action, read Miško Hevery, seriously.

The code I will share is about testing your code using JUnit and Mockito. I’ll not talk about JUnit, I’ll talk about Mockito a bit and show them to you in action in a dummy project.

You wrote your code, you are sure it will work. Your classes are full of intelligent decisions and designs. But at some point they are all dependent of others. Others depends on others etc. The meaning of unit test is testing units of your project in isolation. Class A depends on B and C but in TestA.java you should concentrate on only A. So you must find a way to simulate B and C in a way that they work perfectly. Mockito comes here to solve your problems. (Misko Hevery has some posts on dependencies in classes, they might help you at this point.) Create mocks(simulations) of your dependencies, provide them some functionality and let them go. You must test your units one by one in unit tests. You can read about Mockito here, and JUnit here.

Here is the class:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class DummyFileReader {
 public void readNames(String path) {
 InputStream resourceAsStream = DummyFileReader.class.getResourceAsStream(path);
 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream));
 String name;
 try {
 while ((name = bufferedReader.readLine()) != null) {
 System.out.println(name);
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
}

And here is the test class:

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doThrow;
public class DummyFileReaderTest {
 @Mock
 DummyFileReader dummyFileReader;
@Rule
 public ExpectedException expectedException = ExpectedException.none();
@Before
 public void setup() {
 MockitoAnnotations.initMocks(this);
 doThrow(new RuntimeException("Intended Exception")).when(dummyFileReader).readNames(anyString());
 }
@Test
 public void testReadNames() throws Exception {
 expectedException.expect(RuntimeException.class);
 expectedException.expectMessage("Intended Exception");
dummyFileReader.readNames("names");
 }
}

I have a class that has only one method “readNames” which has no return value. Mockito has a problem about void methods. If you don’t mock the method then they do nothing. If you mock them you have 2 options, doNothing and doThrow. I want to show you that you can use ExpectedException annotation to test your void methods with cooperation of Mockito and JUnit. Now you can test your mocks which have doThrow functionality using ExpectedException. You could use @Test(expected = MyException.class) but you have more control(eg. message of exception) over your tests now.

One point; Mockito.doThrow can only throw unchecked exceptions.

You can find the source code here.

Creating SSL Keystore For Apache Tomcat Using Keytool and BouncyCastle

This post is explaining how to create your own ssl keystore file and using it in your Android applications. I have taken the example from http://stackoverflow.com/questions/4065379/how-to-create-a-bks-bouncycastle-format-java-keystore-that-contains-a-client-c.

Download bouncycastle JAR from http://repo2.maven.org/maven2/org/bouncycastle/bcprov-ext-jdk15on/1.47/bcprov-ext-jdk15on-1.47.jar
Configure BouncyCastle for PC using one of the below methods.
Adding the BC Provider Statically (Recommended)

Copy the bcprov-ext-jdk15on-1.47.jar to each
jdk1.6.0_33\jre\lib\ext (JDK bundled JRE)
jre1.6.0_33\lib\ext (JRE)
C:\ (location to be used in env variable)
Modify the java.security file under
jdk1.6.0_33\jre\lib\security
jre1.6.0_33\lib\security
and add the following entry
security.provider.10=org.bouncycastle.jce.provider.BouncyCastleProvider
Edit your path and add this entry:

c:\bcprov-ext-jdk15on-1.47.jar
Generate the Keystore using Bouncy Castle
Run the following command
keytool -genkey -alias changeit -keystore C:/changeit.keystore -storepass changeit -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider

Note: You should write your ip when it asks: What is your first and last name?
This generates the file C:\changeit.keystore

Run the following command to check if it is properly generated or not
keytool -list -keystore C:\changeit.keystore -storetype BKS

Configure BouncyCastle for TOMCAT

Open apache-tomcat-6.0.35\conf\server.xml and add the following entry
<Connector port=”8443″ keystorePass=”changeit” alias=”changeit” keystore=”c:/changeit.keystore” keystoreType=”BKS” SSLEnabled=”true” clientAuth=”false” protocol=”HTTP/1.1″ scheme=”https” secure=”true” sslProtocol=”TLS” sslImplementationName=”org.bouncycastle.jce.provider.BouncyCastleProvider”/>

Restart the server after these changes.

Go to https://localhost:8443/, you should see Tomcat homepage.

You should check Stackoverflow link above to get whole example. I should say that Vipul has made a great work.

Flex: Security error accessing url

[RPC Fault faultString=”Security error accessing url” faultCode=”Channel.Security.Error” faultDetail=”Destination: DefaultHTTP”]

As you already know flex applications have a strict security policy. You can look at this site for more information.

Flash player normally does not let your application to access to some resources (assets, web services etc) in another domain. Your domain is where you publish your flash/flex application. This sandbox also prohibits your web application from accessing local files/resources of the client. While there is no way to bypass the second one -imho-, you can enable your application to access resources in another domain.

You can do this using crossdomain.xml file. That file should be at the root of your application. You can configure which domains your application can or can’t access. Also you can configure this by actionscript.

Typical crossdomain.xml file looks like this:

<?xml version=”1.0″?>
<!DOCTYPE cross-domain-policy SYSTEM “http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd”&gt;
<cross-domain-policy>
<allow-access-from domain=”*” />
<allow-http-request-headers-from domain=”*” headers=”*”/>
</cross-domain-policy>

First entry lets your application to be reached from all domains. Sometimes you don’t want this for security reasons. You can replace * with *.yourdomain.com or http://www.yourdomain.com or else.

The second one, as the name implies, lets your application to accept request headers from any domain. While I’m using RESTful services of another domain, I need the second one. But as I said before, using * wildcard is not a good idea. Restrict these options as much as you can.

Also you can do this using Actionscript. You can call that method at initialization step of your application and you are good to go:

// (Loader) Application initialization
public function initApp():void
{
Security.allowDomain( “*” );

}

Have a good day…

Flex – Java Real Time Chart With BlazeDS

In my previous post I’ve explained how to create a line chart populated with real time data.

In this post I’ve moved real time data generating to Java project and push that data to client using BlazeDS. The rest is same as the previous flex project.

I’ll simply put sources here so you can take a look at it. You need to modify build.xml in java project according to your system. Also right click on your flex project in your Flash Builder  and select properties. Flex Compiler->Additional Compiler Arguments then modify path. You will be able to deploy the java project war file to tomcat and run your flex project from Flash Builder.

You will see the live data in line chart generated and pushed from the server.

There are 2 projects(RealTimeDataServer, RealTimeLineChart) one for server-side with BlazeDS and the other for client with Flex:

GitHub

Real Time Flex Line Chart

Hi,

That example may seems a bit silly but I saw that there is a lack of similar solutions. I’ve not used any third party library. You can find them on Internet.

In fact that project does not do anything other than populating data provider of a line chart in a fixed time interval basis. But in the next post I will integrate that one with BlazeDS and over channels you can send your real time data to your clients and populate line chart according to these data. Let the coding begin:

First we have 2 timers: 1 for populating data and the other for updating chart. We have a bindable data provider for chart. We change that array collection until update chart timer fires. So that we can optimize the speed of the update.

The code is like that:

 <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
 xmlns:s="library://ns.adobe.com/flex/spark"
 xmlns:mx="library://ns.adobe.com/flex/mx"
 minWidth="955" minHeight="600"
 creationComplete="application1_creationCompleteHandler(event)"
 initialize="application1_initializeHandler(event)">
 <fx:Script>
 <![CDATA[
 import mx.collections.ArrayCollection;
 import mx.events.FlexEvent;

 private static const ARRAY_SIZE:int = 500;
 private static const DATA_INTERVAL:int = 8;
 private static const UPDATE_INTERVAL:int = 80;

 private var dummyGeneratorTimer:Timer;
 private var dummyUpdateTimer:Timer;
 [Bindable]
 private var chartData:ArrayCollection = new ArrayCollection;
 private var chartIndex:int = 0;

 protected function application1_initializeHandler(event:FlexEvent):void
 {
 dummyGeneratorTimer = new Timer(DATA_INTERVAL); // 8 millisecond
 dummyGeneratorTimer.addEventListener(TimerEvent.TIMER, populateData);

 dummyUpdateTimer = new Timer(UPDATE_INTERVAL); // 80 millisecond
 dummyUpdateTimer.addEventListener(TimerEvent.TIMER, populateChart);
 var dummyArray:Array = new Array();
 for(var i:int=0; i<ARRAY_SIZE; i++)
 {
 dummyArray[i]=128;
 }
 chartData = new ArrayCollection(dummyArray);
 }

 protected function application1_creationCompleteHandler(event:FlexEvent):void
 {
 dummyGeneratorTimer.start();
 dummyUpdateTimer.start();
 }

 private function populateData(event:TimerEvent):void
 {
 var randomNumber:int = Math.random()*256;
 //Does not trigger chart update
 chartData.source[chartIndex] = randomNumber;
 chartIndex++;
 chartIndex%=ARRAY_SIZE;
 }

 private function populateChart(event:TimerEvent):void
 {
 //Trigger update
 chartData.setItemAt(chartData.getItemAt(0), 0);
 }
 ]]>
 </fx:Script>
 <fx:Declarations>
 <!-- Define custom Strokes. -->
 <mx:SolidColorStroke id="s3" color="0x33F400" weight="1"/>
 </fx:Declarations>

 <mx:CartesianChart id="linechart" width="100%" height="100%" cacheAsBitmap="true"
 cachePolicy="on" paddingLeft="5" paddingRight="5">
 <mx:verticalAxis>
 <mx:LinearAxis id="vAxis" alignLabelsToInterval="true" autoAdjust="false"
 baseAtZero="false" interval="16" maximum="256" minimum="0" padding="1"/>
 </mx:verticalAxis>
 <mx:verticalAxisRenderers>
 <mx:AxisRenderer axis="{vAxis}" canDropLabels="true" color="0xF8F8F6" fontSize="8"/>
 </mx:verticalAxisRenderers>
 <mx:horizontalAxis>
 <mx:LinearAxis id="hAxis" alignLabelsToInterval="true" autoAdjust="false"
 baseAtZero="false" interval="25"/>
 </mx:horizontalAxis>
 <mx:horizontalAxisRenderers>
 <mx:AxisRenderer axis="{hAxis}" canDropLabels="true" color="0xF8F8F6" fontSize="8"/>
 </mx:horizontalAxisRenderers>
 <mx:fill>
 <mx:SolidColor color="0x231F20"/>
 </mx:fill>
 <mx:backgroundElements>
 <mx:GridLines cacheAsBitmap="true" cachePolicy="on" gridDirection="horizontal">
 <mx:horizontalStroke>
 <s:SolidColorStroke alpha="0.2" color="0xD4D4D3" weight="0"/>
 </mx:horizontalStroke>
 </mx:GridLines>
 </mx:backgroundElements>
 <mx:series>
 <mx:LineSeries id="recordGraph" cacheAsBitmap="true" cachePolicy="on"
 dataProvider="{chartData}" form="segment" lineStroke="{s3}"
 sortOnXField="false"/>
 </mx:series>
 </mx:CartesianChart>
</s:Application>

In next post I will move generating random values to a Java project and connect these 2 projects via BlazeDs.

If you’ve better solutions please comment.

Creating android library project with eclipse

I’ve two versions of my project. One for phones and one for tablet pc. The problem is they share a lot of functionality. The one for phones is using tabhost and the other one not using it but services, activities and permissions are the same more or less.

So I decided to sum these  common points in a library project so I get rid of duplication of work.

First thing is creating a new  android application in eclipse. Name it TestLibProject. Make it Library Project by Right Click on this project and Properties->Android then check the Is Library option. You can find this information from http://developer.android.com/guide/developing/projects/projects-eclipse.html

Anyway as the link says create another project that will be using this library project. Name it TestClientProject. Right click this project and  Properties->Android then in library panel click ‘Add’. You will see your lib project named  TestLibProject. Select and add it.

You will notice that under your   TestClientProject->Library Projects you have  testlibproject.jar exists. That jar contains the classes of your lib project.

Let’s create a dummy service that prints the time to console. It’s really dummy sorry🙂

The Library Project( TestLibProject  ) :

DummyService.java

public class DummyService extends Service
{

 @Override
 public void onCreate()
 {
 super.onCreate();
 DummyThread dummyThread = new DummyThread();
 dummyThread.start();
 }

 @Override
 public IBinder onBind(Intent arg0)
 {
 return null;
 }

 private class DummyThread extends Thread
 {
 public DummyThread()
 {
 this.setName("DummyThread");
 }

 @Override
 public void run()
 {
 while (true)
 {
 Log.e(getName(), new Date().toLocaleString());
 try
 {
 sleep(1000);
 }
 catch (InterruptedException e)
 {
 e.printStackTrace();
 }
 }
 }
 }
}

AndroidManifest.xml

It is really interesting here. You don’t need to declare anything here. But you will need to declare your services, activities or anything you will use in your client project. But it is advised to declare these in here too.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.lib.package" >

    <service android:name=".DummyService" >
    </service>

</manifest>

The Client Project( TestClientProject ) :

TestClientProjectActivity.java:

BEWARE: You may need to restart eclipse to make your client project to recognize DummyService class.

public class  TestClientProjectActivity extends Activity
{
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 Intent intent = new Intent(this,  DummyService.class);
 startService(intent);
 }
}

AndroidManifest.xml:
As I said before we need to declare our service here.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="your.client.package"
 android:versionCode="1"
 android:versionName="1.0" >

 <uses-sdk android:minSdkVersion="8" />

 <application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name" >
 <activity
 android:name=".TestClientProjectActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <service android:name="your.lib.package.DummyService" >
 </service>
 </application>

</manifest>

When you run your client project you will see logs like that:

01-27 03:20:43.855 E/DummyThread ( 281): Jan 27, 2012 3:20:43 AM
01-27 03:20:44.913 E/ DummyThread ( 281): Jan 27, 2012 3:20:44 AM
01-27 03:20:45.973 E/ DummyThread ( 281): Jan 27, 2012 3:20:45 AM
01-27 03:20:46.984 E/ DummyThread ( 281): Jan 27, 2012 3:20:46 AM
01-27 03:20:47.993 E/ DummyThread ( 281): Jan 27, 2012 3:20:47 AM
01-27 03:20:49.013 E/ DummyThread ( 281): Jan 27, 2012 3:20:49 AM
01-27 03:20:50.072 E/ DummyThread ( 281): Jan 27, 2012 3:20:50 AM
01-27 03:20:51.093 E/ DummyThread ( 281): Jan 27, 2012 3:20:51 AM
01-27 03:20:52.103 E/ DummyThread ( 281): Jan 27, 2012 3:20:52 AM
01-27 03:20:53.108 E/ DummyThread ( 281): Jan 27, 2012 3:20:53 AM

Our library project works!

Happy coding…