Archive for the ‘Programming’ Category

Geecon Prague 2015 – looking for silver bullet again

Geecon has apparently caught its momentum aspiring to be most recognizable conference brand in central Europe. I have recently attended the fourth installment this year – after TDD Geecon in Poznań, Main Geecon in Krakow and Microservices Geecon in Sopot the time has come for Geecon Prague 2015Let’s go with bunch of insights after this event.

The hype around microservices is still on the rise – the really big part of the talks was devoted to this topic. Other significant part of the lectures was about importance of testing on various levels of abstraction and system architecture needed to be able to make reliable tests achievable.

Since history repeats itself (I really recommend to read THIS article, even though it is sooo long..), there were some talks indicating that again – there is no silver bullet, which is what makes programmers sad, since […] is most fun thing to do – everyone knows it. This silver bullet thing was emerging in various talks. Ranging from quite obvious but not so often asked questions : modular-monolith and whether or not your microservices architecture is just: distributed ball of mud


(slides from presentation ‘Modular Monoliths’ by Simon Brown).

Christopher Batey – The Dangers of Building Microservices

A microservice is simple. You can recompile and restart it in seconds. If you stop liking the code of your microservice you can rewrite it from scratch. They are small so they can’t be a big ball of mud can they? The decomposition to a lot of independent services allows to test them easily. Ahh, the world of greenfield programming. No silver bullet. The microservice itself won’t be a big ball of mud – by itself. BUT the vast network of connections between them can be. What a lot of people forgot at first was that word : network. Microservices are easy to test in isolation. But once you send the packets over the wire bad things can happen, and they will happen sooner or later, you can be sure. That is why you need to use tools and write tests which can handle and emulate situations like :

  • slow responding services,
  • not responding services,
  • fast responding services but network working slow for a moment,
  • corrupt messages..

Saboteur, Wiremock, Hystrix.. you should try them!

Antonio Molina & Nick Zeeb – What I Learned Writing a Trillion $

Interesting story built around lessons learned during development of system dealing with massive money amounts going through Forex. Namely 1900000000000$ during one year in their case. Is it even possible to work with such (continuously deployed!) system without 80% heart stroke rate per year among developers? It is. It wouldn’t be without the knowledge they’ve learned till this day. And some of the lessons I noticed are:

  1. Test like crazy. They have 10 000 acceptance tests. And many times more unit tests. Micro performance tests. Meso performance tests. Macro performance tests. Failure tests. Data migration tests. Live tests on real market with small amounts of money. Of course it comes at a cost. 80% of development time.  And.. :

invest But they discovered that it pays out at the end. Otherwise… : why-loss 2. Sometimes less is more. LMAX discovered that in their case spreading across multiple repositories brought more pain then gain. Also fancy ‘branch per feature’ attitude was ditched. Oh, and there is one slightly bigger company which does similar thing now : google-single-repo There is also some team culture involved here : always try to develop as small working piece of code as you can. And the whole team also tries to focus on the smallest achievable piece of functionality at time.

3. Accept your inferiority at estimating performance of your algorithms working in the world of deep stack traces. You know the big ‘O’ notation? That is great, you can prove you were right in the performance test you will write. But some day it will prove you were so, so wrong, and it will allow to avoid big ‘O’ on your face on the release day.

      No silver bullets, but going to attend Geecon next year to try find one, for sure! 😉

Cannot resolve symbol XYZ in IntelliJ although maven builds sources properly

Today I stumbled upon a weird problem with IntelliJ IDE.

I had to update one of maven dependencies version, which introduced a new class I wanted to use.
It was possible to build the project without any problem by mvn install, but still the editor marked it red with message ‘cannot resolve symbol’.
Consequently it was for instance impossible to run single unit tests from IDE, because IntelliJ considered this code as invalid to compile.

I tried invalidating caches, reloading pom.xml etc. but to no avail.

Finally it turned out that for some reason IntelliJ is incapable to track changes in maven artifacts versions, if the version is given in a variable like :


The workaround goes as follows :

1. Replace ${yoke.version} with raw string version
2. Go to File -> Settings … -> (search) maven -> repositories and click ‘Update’ on your local maven repository.
3. Invalidate caches. (File -> Invalidate caches / restart … )
4. Now it should work
5. You can replace tag content with variable reference again

I wasted quite a lot of time for that, so maybe it will help someone with similar issue 😉

Exposing Activiti BPMN Engine events via websockets extending its REST application

The latest release of Activiti (5.15) introduced a new interesting mechanism – support for event handlers. You can now get notified just when something interesting happens inside process engine. (You can read more on events in Activiti HERE).

I instantly thought that would be even more interesting if external applications integrated with Activiti REST could also get easily notified about the process events. Using websockets as a medium for broadcasting these messages seemed quite natural.
In this article I will present step by step how I extended the default REST application to serve events via websockets. I also developed a client test consuming these events to prove the thing is working, it will also be described later on.


You can git clone or download zip package with sources of this project here:

To run it just go to activiti-websockets-server directory and execute

mvn jetty:run

This will build the server application and run it in maven embedded jetty server.

Then to run automated client test go to activiti-websockets-client directory and execute

mvn test

You will need Maven running on JDK 8 to run the test project.

activiti-websockets server project

Broad view on main concepts :

  • The project is based on original Activiti REST application. It is included in the project as maven dependency and extended where needed.
  • The websockets server has been developed using standard Java EE7 web-api libraries. They are compatible with modern webapp containers like Jetty 9 and Tomcat 8.

Let’s go into some more details:

1. How websocket server is hooked to the Activiti REST webapp?

The standard web.xml file has been altered to use a custom ServletContextListener :


This listener extends default ActivitiServletContextListener.

Look at its source code now:

public class CustomActivitiServletContextListener extends ActivitiServletContextListener {
private static final Logger log = LoggerFactory.getLogger(CustomActivitiServletContextListener.class);
 public void contextInitialized(ServletContextEvent event) {
 event.getServletContext().setAttribute("activiti-engine", ProcessEngines.getDefaultProcessEngine());
public void addProcessEventsEndpoint(ServletContextEvent ce) {"Deploying process-engine-events websockets server endpoint");
 ServletContext sc = ce.getServletContext();
final ServerContainer server_container
 = (ServerContainer) ce.getServletContext().getAttribute("javax.websocket.server.ServerContainer");
try {
 ServerEndpointConfig config
 = ServerEndpointConfig.Builder.create(ProcessEngineEventsWebsocket.class,
 config.getUserProperties().put("servlet.context", sc);
 } catch (DeploymentException e) {
 throw new RuntimeException(e);

Two most important lines:

ServerEndpointConfig config
 = ServerEndpointConfig.Builder.create(ProcessEngineEventsWebsocket.class,

New endpoint will be deployed to path “/process-engine-events“, it is implemented by websocket server class ProcessEngineEventsWebsocket.

event.getServletContext().setAttribute("activiti-engine", ProcessEngines.getDefaultProcessEngine());

Process engine reference is stored in ‘activiti-engine‘ servlet context attribute, it allows to be later acquired in ProcessEngineEventsWebsocket class.

2. Websocket server endpoint

public class ProcessEngineEventsWebsocket extends Endpoint {
private static final Logger log = LoggerFactory.getLogger(ProcessEngineEventsWebsocket.class);
private ServletContext servletContext;
 private ProcessEngine processEngine;
 public void onOpen(final Session session, EndpointConfig config) {"Websockets connection opened");
this.servletContext = (ServletContext) config.getUserProperties().get("servlet.context");
 processEngine = (ProcessEngine) servletContext.getAttribute("activiti-engine");
 processEngine.getRuntimeService().addEventListener(new ActivitiProcessEventsWebsocketBroadcaster(session));
processEngine = (ProcessEngine) servletContext.getAttribute("activiti-engine");

When a new websockets session is opened, processEngine is retrieved from the servlet context attribute stored in servlet context listener.

processEngine.getRuntimeService().addEventListener(new ActivitiProcessEventsWebsocketBroadcaster(session));

Registering ActivitiProcessEventsWebsocketBroadcaster as an event listener for all events published by the Activiti engine. Websockets session object is passed to the event handler to allow sending messages to the client.

3. ActivitiProcessEventsWebsocketBroadcaster – Activiti events handler

This class implements ActivitiEventListener interface. Every time new event occurs this method gets called:

 public void onEvent(ActivitiEvent event) {
 switch (event.getType()) {

I decided to publish two selected types of Activiti events. Every time they occur they are broadcasted to the client. Quite self-explanatory.

private void broadcastEvent(ActivitiActivityEvent e) {
 ProcessEventDTO dto = ProcessEventDTO.builder().activityId(e.getActivityId())
 .build();"Activiti event received: " + e.getType());
 RemoteEndpoint.Basic remoteEndpoint = session.getBasicRemote();
 try {
 } catch (IOException ex) {
 throw new RuntimeException(ex);

Here the event properties are wrapped in transport class object (ProcessEventDTO), then serialized to JSON using Jackson ObjectMapper, and send to the client as string. The client endpoint is retrieved from the session object injected in ProcessEngineEventsWebsocket during session opening.

And that’s basically all about publishing Activiti events via websockets.

Example process and websockets client as test case

To demonstrate it working I developed a simple BPMN process which gets auto deployed during start of the REST webapp.
It is done in DemoDataGenerator class substituting the original class from REST webapp. The file ‘event-demo-process.bpmn20.xml‘ is deployed in method initDemoProcessDefinitions(). You can find this process in graphic notation below:


– first-task and second-task just print some info to server log
– timer-catch waits 8 seconds, then process is resumed again

Let’s move to activiti-websockets-client project

I developed a client going automatically through this process in the form of unit test.

The main test method goes as follows:

 public void processShouldComplete() throws InterruptedException, Exception {
 final ProcessEventsWebSocket ws = con.getProcessEventsWebsocket();
String processInstanceId = createProcessInstance();
ws.addExpectedEventAndWait(15000, ProcessEventDTO.builder()

– A new process instance is created using Activiti REST services. You can read documentation of these services HERE. I used Jersey client for dealing with HTTP requests and again Jackson for deserialization of JSON objects representing server events.
– In class ProcessEventsWebSocket using eclipse jetty websocket client library and CountDownLatch (you can read more about it HERE) I implemented simple mechanisms to wait for an event with given field values set. For demo purposes every event incoming in onMessage() method is printed to standard output.
– In this particular test we wait for ACTIVITY_STARTED event of ‘user-task‘, then we can push process forward in completeUserTask() method, finally we check if process has finished. It is also achieved using Activiti REST API mentioned before.

The output of the test should be like:

Running pl.mwrobel.activiti.websockets.test.ActivitiWebsocketsIntegrationTest
 2014-04-28 12:54:52.081:INFO::main: Logging initialized @863ms
 MATCHED ****ProcessEventDTO(processId=287, activityId=null, activityName=user-task, activityType=ACTIVITY_STARTED, customActivityType=null)
 closed connection
 Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 9.358 sec

And that is all on Proof of Concept integration of Activiti with websockets server. Hope it helped someone 😉


My thread on Activiti forums about somewhat more complicated example involving signals and problems regarding transactions and events in Activiti:

So – in some cases this concept may still need some refining 😉

Resources :

Article on Java EE7 Websockets:
Detailed Activiti user guide:
Jackson JSON Processor

How to draw semicircle on Android Canvas?

I just resolved a problem which at first I thought is a matter of 5 min for finding appropriate Android API function, unfortunately it took me much longer..

Given start and end points of a vector, draw left/right hand semicircle knowing, that this vector is diameter of this semicircle.


Use addArc android function.

public void addArc (RectF oval, float startAngle, float sweepAngle), float, float)

As you can see we need an oval rect and startAngle, which are not obvious..
Hereunder you can find a handy method computing needed parameters.

     * @param xStart vector start point
     * @param yStart
     * @param xEnd vector end point
     * @param yEnd
     * @param ovalRectOUT RectF to store result
     * @param enum direction left/right
     * @return start angle
    public static float getSemicircle(float xStart, float yStart, float xEnd,
            float yEnd, RectF ovalRectOUT, Side direction) {

        float centerX = xStart + ((xEnd - xStart) / 2);
        float centerY = yStart + ((yEnd - yStart) / 2);

        double xLen = (xEnd - xStart);
        double yLen = (yEnd - yStart);
        float radius = (float) (Math.sqrt(xLen * xLen + yLen * yLen) / 2);
        RectF oval = new RectF((float) (centerX - radius),
                (float) (centerY - radius), (float) (centerX + radius),
                (float) (centerY + radius));


        double radStartAngle = 0;
        if (direction == Side.LEFT) {
            radStartAngle = Math.atan2(yStart - centerY, xStart - centerX);
        } else {
            radStartAngle = Math.atan2(yEnd - centerY, xEnd - centerX);
        float startAngle = (float) Math.toDegrees(radStartAngle);

        return startAngle;


After that drawing semicircles is deadsimple with eg.

path.addArc(oval, startAngle, 180);

Hope that helps! 😉

If you need to manipulate circle pieces a bit more specifically I really recommend you this article:

How to configure Eclipse to debug Alfresco java webscript code

How to configure Eclipse to debug Alfresco java webscript code

NOTE: It is assumed, that Eclipse environment has been configured to work with Alfresco SDK. If it’s not true the configuration process has been described here:

1. Select: Run menu -> Debug configurations…
2. Create new configuration for ‘Remote Java Application’
3. In ‘Project’ field select ‘home’ project (presumably your webscript project), which you want to debug (but it is also possible to debug code from Alfresco core outside selected project)
4. In ‘Connection properties’ set Tomcat server IP address and debug port you defined earlier.

NOTE: It’s advised against to use ‘localhost’ instead of IP address on Windows because of hosts file issues.

5. Click Apply, Debug
6. If everything went correct you shouldn’t get any message.
7. Switch to debug perspective
8. You should see something like this:

Proper screen from eclipse debug perspective

Proper screen from eclipse debug perspective

In case of debug session disconnection (eg. Tomcat restart) you may reconnect to it using Relaunch option:
Reconnecting to debugger

Reconnecting to debugger

9. Now you can normally set breakpoints and trace code execution of your webscript or other Alfresco SDK projects. A good test is setting a breakpoint in org.alfresco.web.bean.LoginBean at line
“FacesContext context = FacesContext.getCurrentInstance();” – breakpoint should be caught at Alfresco Explorer login attemp.

NOTE: You may get following error message: “Unable to install breakpoint in org.evolpe.webscripts.XMLwebs due to missing line number attributes. Modify compiler options to generate line number attributes.
Absent Line Number Information”

Missing line info window

Missing line info window

CAUSE&SOLUTION: To debug your own webscripts or other code it’s essential to enable code line number information in the compiler. If you use ant, set debug=”true’ parameter in javac task.

How to configure tomcat to debug instance of Alfresco on Windows and Linux will be described soon in my next articles.;)

I get “Unable to locate the Javac Compiler” when trying to build using IAM Maven Eclipse plugin.

When trying to build maven project using IAM under Eclipse I get an error like this:

"Unable to locate the Javac Compiler in:C:\\Program
Please ensure you are using JDK 1.4 or above and
not a JRE (the class is required).
In most cases you can change the location of your Java
installation by setting the JAVA_HOME environment variable"

,nevertheless I have proper installation of newest Java JDK and JAVA_HOME is properly set.
The problem never occured before.


I know two possible causes of that problem:

1. Eclipse uses its own JRE to start, and IAM does the same. You’ve recently installed a new maven plugin and it requires JDK.
You can force Eclipse to start using directly given Java VM by starting it that way from command line:

“X:\\path\to\\eclipse\\eclipse.exe -vm JAVA_JDK_PATH”

2. There also cases when IAM brokes up without apparent cause, and that happend to me.
The reason may be IAM itself.
Try standard tricks checklist from my another post here:
Problems using Eclipse IAM and Maven

How to upload a new file to Alfresco using web services?

There are some examples how to upload a file to alfresco using UploadContentServlet but they all show how to code it directly in Java. Documentation and forum lacks an example showing how to upload a large file using Alfresco web services. After a bit of struggle I figured it out.

Quick and dirty recipe:

  1. Perform ticket authorization
POST /alfresco/service/api/login
"username" : "admin",
"password" : "admin"

You’ll get response with ticket in it.

  1. Create a new document using CMIS services
POST /alfresco/service/cmis/i/176c5f4d-db63-49ec-9886-c19d6d9eefce/children

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns=""
<title>important document</title>
<summary>VERY important document</summary>
<content type="text/plain">
<cmis:propertyId propertyDefinitionId="cmis:objectTypeId"><cmis:value>cmis:document</cmis:value></cmis:propertyId>

/i/176c5f4d-db63-49ec-9886-c19d6d9eefce denotes folder to create document within.

It is also possible to refer to directories in more natural way – using names.

More info provided here: will get quite big chunk of xml with a lot info about newly uploaded document, among these informations you’ll find ID of the document.

3.  Overwrite the new document with your big file

PUT /alfresco/upload/workspace/SpacesStore/85c43689-4a38-4a0a-8e58-e24333ffec14/test.pdf?ticket=TICKET_fc7af4c45f138ad366dd5905aaf7a4ab8b9da268

Send file as body of request.

More info about UploadContentServlet :

And that’s all, your file is ready in Alfresco repository!

I get NoClassDefFound for ContextLoaderListener class using Spring and Eclipse IAM Maven plugin

My most common headache during my last Spring project was:

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

during start of Tomcat.

Every source pointed to problems with spring.jar, so I suspected having some version conflict between my Spring libraries (eg. I used also Spring-WS in an old version). But that wasn’t real cause and I’d wasted a lot of time. The real problem was faulty Eclipse IAM plugin.

Try out some tricks I’ve described in my another article : Problems using Eclipse IAM and Maven

They really may help you.

Problems using Eclipse IAM and Maven

During my last project I was involved, I used Eclipse IAM plugin for integration with Maven. It caused many problems, mainly Class not found exceptions and issues with Tomcat server.

Generally I perceived that Eclipse IAM tends to lose jars from pom.xml, what leads to unexpected, bizarre time wasting NoClassDefFoundError.

Unfortunately I hadn’t been sucessful in finding causes of my problems but I’d like to share with you my standard ‘IAM problems checklist’ 😉

If you have any problems try this (in specified order) :

  1. Use refresh, then fetch source jars option from maven menu.
  2. Try cleaning maven libraries, then do ‘1.’
  3. After doing ‘2.’, remove your app from Tomcat, clean server, then deploy again.
  4. Try removing whole server, then add it again.

Any step mentioned above is not a joke. I had really to ‘reset’ workspace a few times to make things work again.. First three steps helped me in 80% cases.

I hope my tips will save your time.

JNA causes JVM to crash althoug I allocate memory properly

During my work with JNA I experienced a following problem:

Memory intMem = new Memory(4);  // allocating space
intMem.setInt(0, 666); // setting allocated memory to an integer
Pointer intPointer = intMem.getPointer(0);
dlllib.method1(intMem);  // OK
dlllib.method1(intPointer);  /// JVM crash !!

I can’t find the reason for such behaviour, I’ve only found out that passing Memory object (which inherits from Pointer) to Pointer parametered methods works perfectly fine. It’s rather strange that getPointer results in invalid(?) pointer but it’s just the way it is.

For more info about JNA and calling native library functions from java I recommend you to read my another article: How to call/invoke external DLL library method/function from Java code?

Subscribe by mail