Turn your Java apps Gnome-Shell friendly

August 30, 2011 - 5 Responses

The Problem

When you try to add a java application as favorite into the Gnome Shell‘s lateral dock and run it you’ll end up having duplicated icons, one for the launcher and one for the running app. This happens b/c the shell uses an application based system for grouping tasks, so the idea is, if you add an application as a favorite launcher and you start it you’ll end having that launcher icon highlighted. Internally the shell matches the running process with the Exec clause of the .desktop file .
This works well except for applications running inside a VM or being interpreted b/c those will share the same running process. On that situation the shell inspects the WM_CLASS X Window property [1] and matches it with the full name of the desktop file. E.g. if your applications has the WM_CLASS set as “mySwingApp”, for this to successfully matched in the dock with its launcher, that launcher must be called mySwingApp.desktop located according XDG.

Note: for inspecting that value on any window you just need to run xprop WM_CLASS and click into the target window

Why is this happening?

Even if you are creating a swing application from scratch there is no easy way to tweak that X Window property using plain and portable APIs. Taking a look into openjdk sources, this is how them manages it

String mainClassName = null;

StackTraceElement trace[] = (new Throwable()).getStackTrace();
int bottom = trace.length - 1;
if (bottom >= 0) {
    mainClassName = trace[bottom].getClassName();
}
if (mainClassName == null || mainClassName.equals("")) {
    mainClassName = "AWT";
}
awtAppClassName = getCorrectXIDString(mainClassName);

As you may note what is used for this value is the name of the class running the Swing main loop.

Da solution

Digging around the web I founded a java agent and a pretty similar explanation on what’s going on.
So what I did was to fork that agent and improve it a little bit. What I did was to move it into a maven structure and remove its packaging as a fat-jar (I’m radically against fat-jars as you can see in my comments here).

The forked project is located in my github here:
https://github.com/diega/window-matching-agent
and please take a look to the README there

A practical example

My first motivation on doing this was based on IntelliJ IDEA so I’ll paste here my environment.

  • Download the agent-1.0.jar and put it wherever you want (I put it into IntelliJ’s bin/ folder)
  • Edit the file bin/idea.vmoptions adding this line

    -javaagent:agent-1.0.jar=intellij-ultimate

  • Create the file ~/.local/share/applications/intellij-ultimate.desktop with the following content

    [Desktop Entry]
    Version=10.5.1
    Name=IntelliJ IDEA Ultimate Edition
    Comment=The Most Intelligent Java IDE
    Categories=Applications;Development;
    Encoding=UTF-8
    Exec=env IDEA_CLASSPATH\=../lib/asm.jar /home/diego/bin/ideaIU-10.5/bin/idea.sh
    GenericName=IntelliJ
    Icon=/home/diego/bin/ideaIU-10.5/bin/idea128.png
    MimeType=text/x-java
    Terminal=false
    Type=Application
    URL=http://www.jetbrains.com/idea
    

Latest notes

If you download the agent-1.0.jar into another location (or with another name) you must adjust the -javaagent: parameter.
Of course, change the path in the Exec entry to point to your own executable.

Hope this helps somebody, it took me a while to figure out the-right-things-to-do™ :)


[1]: Application Based GNOME 3

Drools persistence on top of HashMap

February 7, 2011 - One Response

Introduction

This post shows a reference implementation of drools persistence on top of a non transactional HashMap. This should serve as inspiration for more complex scenarios (like the Berkley DB one). This work was also developed under Intalio’s sponsorship.

As the new abstraction is heavily inspired on JPA there are some mechanisms which should be emulated in order to get the same behavior on both implementations.

Involved classes

Starting from the abstraction described in my previous post this is the new hierarchy for persisting drools runtime into a HashMap.

Drools abstract storage persistence diagram

Drools abstract storage persistence diagram

I’ll try to explain the most relevant objects in the diagram relating them to JPA components.

MapBasedPersistenceContext
behaves like the EntityManager, it stores all objects which are not yet commited. Finding objects is also resolved through this interface, for support this behavior it has to have access to the KnowledgeSessionStorage.
KnowledgeSessionStorage
represents the real persistent storage. This is the extension point for support any other non-JPA implementation. It provides saveOrUpdate and find methods and is the responsible to assign id’s to the entities.
ManualTransactionManager
as we cannot rely on JTA to manage our session Drools hooks explicit calls whenever things should be serialized. This component must access the NonTransactionalPersistenceSession to get the entities waiting for being persisted into the KnowledgeSessionStorage.

JBPM5

The same concepts have been applied into JBPM5 codebase and we have there proper extensions for managing process semantics.

You’ll find there:

  • MapBasedProcessPersistenceContext
  • ProcessStorage
  • ManualProcessTransactionManager
  • etc

Usage

You must setup the environment you gonna pass to the JPAKnowledgeService (still keeping the name for backward compatibility) setting the TRANSACTION_MANAGER and PERSISTENCE_CONTEXT_MANAGER keys. For this I have just created simple factories but you can build them the way you want.

I suggest using KnowledgeSessionStorageEnvironmentBuilder or ProcessStorageEnvironmentBuilder. There doesn’t exist a default implementation of this storage, the one on top of HashMap is only used for testing porposes, so you have to pass to the builder your own implementation of the desired storage.

Testing further implementations

To test this two implementations (and any new one which wants to respect the drools persistence semantic) together, I have created a simple set of abstract tests(*).
For Drools Expert:
https://github.com/droolsjbpm/droolsjbpm/[...]/MapPersistenceTest.java
For JBPM5
https://github.com/krisv/jbpm/[...]/MapPersistenceTest.java
In a future will be great to abstract the current tests on JPA to be able to run abstract of the lower persistence layer.

What’s next

Clean up this interfaces a bit more and start working on a DB Berkley implementation

(*) tests names are not declarative enough, I’m holding a commit for this until coming repository split is done

Drools Abstract Persistence Layer

January 28, 2011 - 2 Responses

Introduction

On the past two months, and under Intalio’s sponsorship, I’ve been working adding a new persistence layer into Drools. The main goal of this is to support Berlkey DB as persistent backend. Added abstractions are on that direction.
The approach for this task was to work on top of the current drools-persistence-jpa module. Is assumed this module is tested enough (through junit or merely day-to-day usage) and this is the one who defines the semantics which drools persistent applications should attach.

Little background on managing persistence

When you use the engine in a regular way, you obtain the ksession through the kbase and it doesn’t know anything about how to persist its state. To provide the ksession with persistence capabilities Drools makes use of the command pattern. That way, instead of creating it directly from the kbase you go through a factory which will return a decorator which will handle how and where the state is persisted. Being a decorator, at this point, will be totally transparent to the user whether or not the state is persisted.

Abstracting persistence

As the name dictates, drools-persistence-jpa module is heavily oriented to JPA usage. Then, what we have made here was to clean up the use of JPA interfaces and move them into this module.

The most used interface by JPA is the EntityManager, this one was abstracted by the PersistenceContext interface which now has specific methods for persisting SessionInfo’s and WorkItemInfo’s.
Internally Drools uses different scopes for dealing with persistenceContext’s, one for the whole application and one for each command. This behaviour has also been abstracted into PersistenceContextManager.

Persistence layer before refactor

Persistence layer before refactor


Persistence layer after refactor

Persistence layer after refactor

Backward compatibility

Other important aspect of this refactor is that maintains backward compatiblity. That means that, for the moment, you shouldn’t notice any difference if you already have your JPA application running. Current way to configure the ksession is still the same but we’ll add some new in the future, which, I wish, will end up being more polish and abstract.

JBPM5

This persistence refactor also applies for jbpm5 which now have a ProcessPersistenceContext and a ProcessPersistenceContextManager.

What’s next

In a comming post I’ll show a reference implementation on the top of a regular HashMap.

Simple Drools Rule Flow to BPMN2 migration tool

December 28, 2010 - One Response

For ease the transition from Drools Flow files to the new BPMN2 standard drools gives you a nice but hidden feature, a XmlBPMNProcessDumper.
This tiny piece takes a RuleFlowProcess instance and spits nice well formed BPMN2 files.
So, for making your life just a little better, I’ve created a project on github exposing this internal piece with a nice interface. Take a look at the class RuleFlow2BPMN2Migrator in

https://github.com/diega/rf-bpmn2-migrator

Enjoy.

Disclaimer: calling a 7-line class a tool isn’t fair enough, but you know…

Are you ready for Drools 5.2 + jbpm5?

December 16, 2010 - Leave a Response

Great things are happening into the core of Drools and it will impact into the whole community.
This post is not about the great features we gonna have soon but about how to make the transition painless.
From the developer point of view things are getting better and better.

    Git migration
    Maven 3 compliance
    Repository cleanup (no more .classpath and .project files)
    Guvnor building coming less and less painful
    Huge internal refactors and optimizations

The major of this tasks were leaded by ge0ffrey who has made our lives a lot better :)

As regular user of the framework when you finally decide to move from 5.1.1 to 5.2 you will find a big difference. Drools Flow is gone… but it has reborn as JBPM5!.
So the concepts remains the same but you’ll need to adjust your dependencies and make a reorganization of your imports. This is the first step on breaking backward compatibility preparing us for the big crash arriving on 6.0 :)
Basically u gonna need to add

<depdency>
  <groupId>org.jbpm</groupId>
  <artifactId>jbpm-[flow | persistence-jpa | bpm2 | ...]</artifactId>
  <version>${jbpm.version}</version>
</dependency>

Doing so you should change a lot of your org.drools packages into org.jbpm.

w00t

New Guvnor Feature – Rule Templates

May 28, 2010 - Leave a Response

Here is a screencast showing guvnor rule template features

As you can see here,  the Template Editor is an extension of the famous Rule Editor which now has a Template Data tab. On this tab you’ll find a grid having the template placeholders (a.k.a. “template keys”) as columns. So in your knowledge base you’ll finally add the rules generated by the drools-template module, using the data into the grid and the parametrized rule that you’ve created in the editor.

Drools Flow :: Work Items

April 19, 2010 - Leave a Response

Introduction

Working on improve our knowledge about the Drools platform and to give something back to the community. This time we’ll discuss a language extension called Work Items. The official documentation says: “[Drools Flow] offers constructs that are closely related to the problem the user is trying to solve”. In other words, creating your own WorkItems lets you extend the business modeling language to a domain oriented way.
Creating a language for your process gives you an enormous flexibility in what you can express. The funny thing is that with this great power doesn’t come a great responsibility, meaning there is no more responsibility than needed to write any bored and unflexible process language.

Read the rest of this entry »

Jetty + DataSource + JTA

April 18, 2010 - 2 Responses

Working on my next post about Drools Flow Work Items I wanted to have a one click example. This example involves a web application so I started with Jetty which fits perfect for a mvn jetty:run example. In the standalone example we run our own JNDI directory provided by Bitronix. Jetty has JNDI directory embedded so we have to register the datasource and the transaction manager. Doing this task for a totally jetty noob could be a little difficult and time consuming. So, hoping nobody has to spend too much time on this, I’ll try to summarize the steps I did to make this.
Read the rest of this entry »

Sobre la Programación Orientada a IDE©

September 27, 2009 - 3 Responses

Hace algún tiempo que vengo luchando contra este concepto[*]. La idea viene de la falacia que todo hay que hacerlo desde dentro de la IDE. Así, la IDE es la que termina guiando nuestro desarrollo y volviéndolo uno con la decisiones unilaterales que han tomado sus desarrolladores.
No estoy para nada en contra de las IDE, solo de las IDE que te obligan a hacer las cosas de la manera que se les antoja. Ésta es una herramienta y no quiero que me obligue a nada, yo quiero usarla como se me antoje y mi profesionalismo me indique para expresar mi arte.

Yendo al contexto Java, que es donde me siento cómodo seguro por el momento, me he encontrado con incontables casos donde a la pregunta de “cómo es su ciclo de deploy” la respuesta comienza con “exportamos el proyecto desde eclipse”…
Por qué esto está mal (sin orden particular)?
• Se depende de un humano para armar ‘entregables’ (no hay integración continua)
• Atenta contra la posibilidad de incluir a un nuevo integrante al equipo que haga uso de otra herramienta
• Tenemos que manejar las dependencias desde el eclipse
Otros efectos colaterales:
• Tendencia a ensuciar los controladores de versiones con cosas propias de las IDE
• Tendencia a nunca entender lo que una IDE hace tan mágicamente (aunque esto es algo inherente a la estupidez en cualquier contexto)
Soluciones a esto:
• Uso de Maven

Por qué Maven?
Maven no es nada de otro planeta ni hace magias oscuras. Hace muy pocas cosas y las hace bien. Mediante el uso de Maven se obtienen algunos puntos muy positivos: controlar dependencias, manejar ciclos de deploy (incluyendo el empaquetado) y unificar (de manera IDE agnóstica) convenciones a la hora de trabajar. Ésto último tiene un punto a destacar alucinante, que venga alguien totalmente ajeno a nuestro desarrollo y no se sienta [tan] perdido frente a cientos de archivos de código; va a saber dónde estan los fuentes, dónde buscar tests, dónde mirar a grandes rasgos qué bibliotecas se usan y va a poder generar un entregable corriendo un solo comando.

Qué es lo peor que podés hacer?
Intentar ajustar maven a tu proyecto y no al revés. Maven es una herramienta para organizar, que si bien deja que modifiques sus convenciones al hacerlo estarías perdiendo muchas de las cosas que destaqué en la pregunta anterior. Cuando te convenzas que estas son las cosas que querés que tu proyecto cumpla, pagá el precio por haber comenzado por la senda del mal y purga tu alma moviendo archivos y repensando los paquetes que tiene tu sistema.

Qué es algo feo feo de ver?
A alguien usando JBoss Developer Studio para mostrar las maravillas de Seam (básicamente hot deploy) cuando realmente conciliar estas maravillas con las ‘buenas prácticas’ antes mencionadas es imposible (y lo peor es que la mayoría de la gente valora más un entorno de desarrollo a-La PHP en lugar de un proyecto ordenado).

Quiénes son los más horrorizados con no comer/ver la tele/dormir con la IDE?
Los desarrolladores .Net . Ellos han comprado una serie de preceptos guiados por Visual Studio y sus wizards, que se les hace arcaico y elitista tratar de usar herramientas de línea de comando, el resto simplemente “la complican de gusto”.

Qué es lo que tendría que hacer un desarrollador nuevo cuando entra a un equipo?
• git clone [o el scm que quieran]
• mvn eclipse:eclipse [o la ide que quieran]
• [abrir la ide y buscar las cosas como tu intuición te indica]
• mvn package
• [deploy]
• [probar la aplicación]

Qué alternativas similares hay?
Para Java ninguna[**] y no me parece mal. Creo que se puede confiar bastante en los desarrolladores de maven como para que guien este camino.
Hablar de ciclos de desarrollo en otros lenguajes no puedo, solo comentar que en C se adolece del mismo problema que generó Ant en su momento, Autoconf/Autotools son infinitamente poderosos, infinitamente complejos y no existe una manera estándar de hacer las cosas, realmente una pena; apenas crece un poquito un proyecto C meterse es una tarea heroica.

[*]: término que nunca antes había escuchado :)
[**]: ant+ivy me parece una aberración mutante

Follow

Get every new post delivered to your Inbox.