12 April 2018

Karaf Cellar 4.1.1 deserialization issue

Due to a import limitation on the Cellar project, it is impossible to deserialize objects outside the cellar or hazelcast namespace:

[KARAF-5636] Enable dynamic import on cellar-hazelcast and dynamic import in Cellar DOSGi in order to support user defined class transport

The issue is solved in the next version, but there is a simple workaround. Make sure your bundles containing the classes for deserialization have the following namespace added to the manifest import-package statement:

org.apache.karaf.cellar

Forcing this into the manifest with the maven bundle plugin is not that straightforward when the bundle does not contain a real dependency on Cellar. But it is possible by declaring the namespace optional:

<Import-Package>
    org.apache.karaf.cellar*;resolution:=optional,*
</Import-Package>

On Karaf startup or on bundle install, Cellar will scan the import statements and detect and register your API bundles (OSGi extender pattern). Now it is able to find the required classes for deserialization and do a tccl switch to load it from the API bundle classpath.

Happy clustering...

13 March 2018

JSR 349 Hibernate Bean Validation 1.1 on OSGi

Validation of objects and object graphs is a cross cutting concern and used within several architectural layers, and therefore should be separated from the business logic. The JSR349 specification describes a mechanism using annotations. At the time of writing, the latest reference implementation of the JSR 349 spec is the Hibernate Validator version 5.4.2.Final. The metadata API can be configured by XML, and the constraints can be extended by creating custom validation annotations.

Hibernate Validator requires special handling on OSGi, a proof of concept is located under net.betzel.javax.osgi.beanvalidation. Build the project and drop the produced Karaf archive file into the Karaf deploy folder to see the mechanism in action.

Readables:

http://beanvalidation.org
http://www.baeldung.com/javax-validation


1 January 2018

JavaCPP libpostal preset

Parsing and normalizing street addresses around the world


Street addresses are among the most difficult artifacts of human language for any piece of parsing software. If you have ever tried it yourself, you know what i am talking about. Having to parse addresses from around the world where each country’s addressing system has its own set of conventions and peculiarities makes this even more difficult.
Searching the net for solutions to this problem i stumbled upon libpostal: a multilingual street address parsing/normalization library, written in C, that can handle addresses all over the world.
Libpostal uses machine learning and is informed by tens of millions of real-world addresses from OpenStreetMap. It currently supports normalization's in 60 languages and can parse addresses in more than 100 countries.
Since my veins are filled with caffeine i needed a Java JNI bridge to span my platform gap. There are bindings available under jpostal,  but having to hassle with all the compiler stuff and the native library handling in your project afterwards makes this not an attractive option.
To ease Java integration there is a great JNI library called JavaCPP. A tool that can not only generate JNI code but also build native wrapper library files from an appropriate interface file written entirely in Java. It can also parse automatically C/C++ header files to produce the required Java interface files. As a topping it generates a Maven artifact containing the whole setup including the specific platform native lib and loading capabilities, ready for use in your Maven projects.
I have used some presets of this project several times before and i believe it is a perfect fit for libpostal, giving the opportunity to add a complete new preset to this great project.

A big thanks to Samuel Audet for the support he provided throughout the process, providing the needed native platform knowledge i was lacking.

The 1.4 release also incorporates the new Systems preset, providing low level API access for Linux, MacOS an Windows.

Resources:

5 November 2017

Dynamic Vaadin on OSGi

Vaadin 8 - Java 8 - Karaf 4 - OSGi 6 : The easy way to real µservice web apps.



There have been numerous articles on describing how to avoid or split up a monolithic architecture into a micro-services setup. A YouTube presentation of Christian Schneider springs to mind (audio gets better after about a minute). I especially like this slide that says it all:


OSGi has done a great job enabling µservice architectures and enforcing clean modular design on the middleware and backend layers but i have not had the chance of putting it into action on the frontend. Finding a modular web UI technology was no great deal, thanks to the people at Vaadin and the basic OSGi integration they have mastered on there latest major version. Getting the two frameworks to play nice is still no trivial task, and resources on the net for Vaadin 8 on OSGi are rare. So, time to get my hands dirty.

My requirements for a modular UI are:
  • Split the UI in vertical modules based on separation of business concerns
  • Runtime addition, removal and updating UI modules and configuration
  • Communicate between these modules using events and/or messaging
  • Discover remote UI modules using DOSGi
  • And maybe we can reach the ultimate goal of SCS, but this could be too much ivory

I cooked up a small setup that demonstrates a possible way of dynamic updating the UI using OSGi declarative services. To get it up and running do the following:

First check out and maven install ops4j-pax-web version 6.0.7.1 from my github account as this contains several corrections to make Vaadin-push work on Karaf. Details can be found here.

Download Karaf 4.1.2 extract and execute.  On the Karaf console add the pax web feature:
feature:repo-add mvn:org.ops4j.pax.web/pax-web-features/6.0.7.1/xml/features
and install the pax-http-whitboad extender:
feature:install pax-http-whiteboard/6.0.7.1
Maven install this project producing a Karaf Archive file (osgi-karaf-vaadin-kar-2.0.0.kar)

Drop this file into the deploy folder found under the Karaf main folder to install all needed bundles at once.

Open up a web browser and open http://localhost:8181/service to display the Vaadin SPA.

Start the dynamic bundle on the Karaf console to see the dynamic parts working.

Any new Ideas regarding this project are always welcome!

Background information:

Christian Posta: Prefer verticals not layers and The Hardest Part About Microservices: Your Data
innoQ: Self contained systems
Arun Gupta: Monolithic to Microservices Refactoring for Java EE Applications

30 September 2017

Vaadin 8 on OSGi

Java 8 - OSGi 6 - Karaf 4 - Vaadin 8

 

The new Vaadin 8 release comes with improved OSGi integration and promises true dynamic and modular UI development. There is not much information on the net concerning this topic so i created this simple example to get up and running quickly. The service is packaged as a JAR file with a valid OSGi bundle manifest created by the bnd-maven-plugin. All the dependencies of the application are OSGi bundles and get installed on deploy.

For more information about Vaadin OSGi support please visit  https://vaadin.com/docs/framework/v8/advanced/advanced-osgi.html.

The project is published on GitHub: Vaadin on OSGi.
Be aware of issue 10220 on version 8.1.x .

Have fun analyzing.

17 March 2017

Lightning Memory-mapped Database on OSGi

Now and then i get what i call a niche requirement, something that does not hold to any standard or good practice. These kind of requirements are usually very development intensive, time consuming and great fun, or a real PITA when having to deal with a deadline.

I am in need of a fast, local, in process atomic counter for daily file name creation, which is thread and crash save, runs within a Java/OSGi environment and can participate in a XA transactions. The files being published are getting consumed and modified by other applications as soon as they are marked with a done file, making a stateless file counting solution impossible. A RDBMS springs to mind thinking of state, but the overhead in production is unproportional as the data generated is only valid for a short period of time and in limited scope.

After turning my toolbox upside down, finding nothing even remotely fitting this job description, I heated up the search engines ready to burn time. My data structure is simple and the amount of data generated is small so a simple key/value store should be just right. This results in a long hit list, but only few libraries support file persistence, and only one made a near perfect match: lmdb. Let me emphase, near perfect match, since it is no Java, no OSGi and has no transactional integration.

The Symas page lists wrappers, and sure enough, java is listed with a JNI implementation called lmdbjni. Strange thing is that this binary has no more Maven support for Windows, MacOS and Android from 0.4.7 onward, bummer. While browsing the github repo i stumbled (by accident via RxLMDB) upon lmdbjava supporting the latest and greatest lmdb version.

So, Java is tackled with a big thanks to the people of lmdbjava. OSGi brings its own mechanism for handeling runtime files and since version 0.0.6 of  lmdbjava the path to the lmdb binary, extracted by OSGi, can be set manually to allow the JNI part to link to it. A example bundle is on github and i leave the JCA integration as exercise.

Happy coding.

2 March 2017

Twelvemonkeys on OSGi

Using Java for working with images has never been first choice, especially if the requirement for advanced computer vision functionalities needs to be met. For these cases please study OpenCV and JavaCV.
For the more daily use cases there is of course the standard Java ImageIO, providing limited image format support. My project required extensive MTIFF with CCITT compression capabilities and the good old JAI-ImageIO seemed to be a good candidate. But MTIFF support requires some extra steps to be taken, and the 10 jear old code base is missing active development. I wanted something fresh and after some research i found myself staring at the github page of twelvemonkeys ImageIO.
TwelveMonkeys is a pure Java based collection of plugins and extensions for Java's ImageIO with few optional dependencies, and under active development. It provides all i need, with a flick of the service provider switch. But lets not make this too easy now. The library is not bundled like JAI, and since i am a heavy OSGi user i want to put it on Karaf.
The first thing to do is get the jars in a bundle, ready for Karaf deployment. The Apache-felix-maven-bundle-plugin tool brings the solution in the form of embedding dependencies, putting the twelvemonkeys jars inside of a single bundle. The registration of these plugins with ImageIO gets handled by the classloader through the javax.imageio.spi.ServiceRegistry. This is a type of Java service loader responseble for finding ImageIO extensions in the classpath under the META-INF/services folder, bringing us straight to the core of our problem. Every OSGi bundle has its own classloader, meaning any image plugin loaded in one bundle is not visible to ImageIO in others. This is also true for every other library on OSGi using the java service loader mechanism.
The OSGi Enterprise R5 ServiceLoader Mediator specs discribe a standard solution for this kind of integration problem, and the reference implementation is Apache Aries Spi Fly. Under the hood it uses some fancy runtime bytecode weaving, resulting in a short classloader switch as soon as the ImageIO Serviceregistry in a bundle starts to look for plugins on the classpath, loading the plugins from the bundle containing the twelvemonkeys embedded dependencies.
Getting the MTIFF utilities in the contrib package functional under OSGi is as simple as adding a  blueprint or declarative service to the bundle containing the twelvemonkeys jars.

Sample project on github.

Recommended reading:

OSGi Alliance javautilserviceloader in OSGi

10 September 2016

A Bio mimetic human retina model with JavaCV

In my job as a software developer for HMM Deutschland, i received a requirement to preprocess and enhance binary images of documents taken in the field with a Tablet or Smartphone. The people making these pictures are not professional photographers and do not have the knowledge nor the time to model the lighting to produce a perfect illuminated and sharp picture of the document. The result is loss of detail and strong luminance changes within one image, making it hard to process further down the pipeline.
Nature already solved the problem at hand , and as we may take it for granted, our vision is a expert in dealing with such circumstances. Jeanny Herault's research (1) has produced a model for human retina spatio-temporal image processing, performing texture analysis with enhanced signal to noise ratio and enhanced details robust against input images luminance ranges. Briefly, here are the main human retina model properties:

  • spectral whitening (mid-frequency details enhancement)
  • high frequency spatio-temporal noise reduction (temporal noise and high frequency spatial noise are minimized)
  • low frequency luminance reduction (luminance range compression) : high luminance regions do not hide details in darker regions anymore
  • local logarithmic luminance compression allows details to be enhanced even in low light conditions
This is not a complete representation of our complex human vision system but it already presents interesting properties that can be involved for a enhanced image processing experience.
OpenCV has a implementation of this model in its contributed section under the bioinspired module(2). OpenCV documentation can be found under 3. 
Since i favor OpenCV on caffeine i added the bioinspired module to the JavaCV project. At this time it is parked on pull request #282 in the javacpp-preset project, meaning for now you have to build it yourself. Samuel Audet did a great job with JavaCPP and describes how to do this on the Bytedeco github pages(4).
A sample project can be found on my github(5) which produced the following output:



The first image is a picture of a document taken by my mobile phone having a lot of noise and luminance variation. The second picture was processed with the retina model using its standard settings. The luminance difference and noise were greatly reduced. The retina model has quite some parameters to play with so have some fun.

Update: available as of version 1.2.2


Acknowledgments

HMM Deutschland GmbH for investing work-time into the project



  1. Herault Jeanny. Vision: Images, Signals and Neural Networks-Models of Neural Processing in Visual Perception. World Scientific, 2010.
  2. https://github.com/opencv/opencv_contrib
  3. http://docs.opencv.org/3.1.0/d3/d86/tutorial_bioinspired_retina_model.html
  4. https://github.com/bytedeco
  5. https://github.com/Maurice-Betzel/net.betzel.bytedeco.javacv.bioinspired

11 July 2016

ServiceMix-7.0.0.M2 Camel Context not resolving

ServiceMix 7.0.0.M2 containing Karaf 4.0.5 installs on first boot the Blueprint Core version 1.6.0  which clashes on XSD level with the containing Camel Blueprint and produces the following error if you deploy a bundle with a Camel context:

Unable to start blueprint container for bundle xxx/x.x.x.SNAPSHOT
org.xml.sax.SAXParseException: src-import.3.1: The namespace attribute, 'http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0',
of an <import> element information item must be identical to the targetNamespace attribute,
'http://camel.apache.org/schema/blueprint', of the imported document.


Strange thing is, in the parent pom version 1.6.1 is declared. I did not search for the root cause of this issue since the 1.6.1 has issues with offline enviroments.
To get this solved we override the old versions with 1.6.2.  In the ServiceMix build just by add the following to the overrides.properties:

# workaround for Blueprint Core version 1.6.0 Camel XSD alignment issue, force usage of version 1.6.2
mvn:org.apache.aries.blueprint/org.apache.aries.blueprint.core/${aries.blueprint.core.version};range="[1,2)"

and the next to <installedBundles> in the assembly POM:

<bundle>mvn:org.apache.aries.blueprint/org.apache.aries.blueprint.core/${aries.blueprint.core.version}</bundle>

This forces Karaf to use the 1.6.2 version of Blueprint Core. Do not forget to increase the property placeholder in the parent pom.

10 March 2016

KIE Server Apache Thrift extension

I am using the JBoss KIE Server and Drools for some time now in the Java Domain, telling my colleagues, who are mostly PHP experts, how great it is to get the spaghetti code out of my imperative code base. After getting on there nerves one too many times, they nailed me to give a presentation on the subject and find a way for letting the PHP fraction benefit from this great piece of technology.
Since i already introduced the Apache Thrift(1) protocol (without the underlying transport part of the Thrift stack) a while ago for binary integration with Java based micro-services, it seemed natural to extend the KIE Server ReST transport with Apache Thrift. The JBoss Principal Software engineer Maciej Swiderski wrote a great blog(2) about the new possibilities for extending the KIE Server.

So why add Apache Thrift to the equation, since we already have JSON/XML and even SOAP right out of the KIE Server box?
  • Speed
    • very few bytes on the wire, cheap (de)serialization  (think large object graphs)
  • Validation
    •  encoding the semantics of the business objects once in a Thrift IDL scheme for all services, for all supported languages, in a object oriented typed manner (as supported by the target language)
  • Natural language bindings
    •  for example, Java uses ArrayList. C++ uses std::vector
  • Backward Compatibility
    •  The protocol is allowed to evolve over time, with certain constraints, without breaking already running implementations

There are a number of Protocols to choose from within Apache Thrift, but for optimal performance there is only one: TCompactProtocol. It is the most compact binary format which is typically more efficient to process than the other protocols.

The project is published on github(3) and consists mainly of  two parts. The org.kie.server.thrift repo and the thrift-maven-plugin repo. Please build the thrift-maven-plugin first as it is a dependency for the server. It contains the Thrift compiler version 0.9.2 for Windows and Linux (tested on Centos / RHEL) for compiling the Thrift IDL files.
The org.kie.server.thrift repo dowloads the KIE Server war file, extracts it, adds the Thrift extension and repackages the sources into a new war file ready for deployment. Tested on Wildfly 8.2.1.
How to setup a KIE server and accompanying workbench is explained under (4).
Test facts and rules with matching PHP and Java clients are also provided under (3).

Workflow



Workflow

Architecture

From the view point of the KIE Server there is a known and a unknown model. The known model consists of the objects used internaly by the KIE Server to handle its commands (Command pattern). These objects are mirrored to IDL in the kie-server-protocol maven module to make them available to all Thrift supported languages. The unknown model is ofcourse the graph of objects that needs to be transported into the KIE core engine for execution. The unknown model must also be designed with the Thrift IDL so all objects that have to pass the Thrift protocol layer are of type TBase. These two object models force a sequential two step (de)serialization.
In the first step the known model is (de)serialized revealing the KIE Server internal objects. This gets handled by the Thrift message reader and writer class that get registered on the resteasy framework, as used by Wildfly, for the application/xthrift content type.  These known objects contain binary fields holding the unknown object bytes.
For the second deserialization I am forced to use a not so smooth a trick. Since there is no way to tell by the bytes what type is represented (due to the compactness of  the Thrift TCompactProtocol which does not deliver a class name like xstream),  the fully qualified Java class name from the IDL generated objects must be provided within the transporting known KIE Server objects. Now the (de)serialisation can take place using the classloader from the deployed KIE Container holding the unknown object model.  On the client side deserialisation after reply is easy as the models are both known.
To allow other languages the use of Java objects like BigDecimal, which is great for monetary calculations, there are integrated converters with Thrift IDL representations in the maven kie-server-java module to ease development. If such a TBase Java representation is not wrapped within another struct it is converted automaticaly. Wrapped represenrations (forced to bind to a TBase type) can make use of the static conversion helper methods.

Please study the source code for further details on the combination of technologies used.

Acknowledgments

HMM Deutschland GmbH for investing work-time into the project
Maciej Swiderski for his informative blog http://mswiderski.blogspot.de
My colleague Alexander Knyn, for being my PHP integration sparring partner

Links:


(1) Apache Thrift
(2) Extending the KIE Server

(3) KIE Server Apache Thrift extension
(4) Installing KIE Server and Workbench 

2 June 2015

Remote KIE Server, XStream and Hibernate Collections

If it is not possible or wanted to add the Hibernate-Core package to the classpath of the remote KIE Server in order to deserialize org.hibernate.collection.internal.PersistentBag and other Hibernate enchanged collections then XStream offers a solution. The xstream-hibernate project offers support to drop the internals of Hibernate enhanced collections, proxied types and Hibernate's collection proxies when marshalling such objects to XStream. All converters and the mapper have to be registered for the XStream instance:
final XStream xstream = new XStream() {
protected MapperWrapper wrapMapper(final MapperWrapper next) {
return new HibernateMapper(next);
}
};
// configure XStream for KIE!
xstream = XStreamXML.newXStreamMarshaller(xStream);
xstream.registerConverter(new HibernateProxyConverter());
xstream.registerConverter(new HibernatePersistentCollectionConverter(xstream.getMapper()));
xstream.registerConverter(new HibernatePersistentMapConverter(xstream.getMapper()));
xstream.registerConverter(new HibernatePersistentSortedMapConverter(xstream.getMapper()));
xstream.registerConverter(new HibernatePersistentSortedSetConverter(xstream.getMapper()));

Maven:
<dependency>
<groupid>com.thoughtworks.xstream</groupid>
<artifactid>xstream-hibernate</artifactid>
<version>1.4.8</version>
</dependency>

10 May 2015

Domain Extensions for Data Modeller

Drools: Drools workbench is getting domain extensions to the Data Modeller. This will allow different domains to augment the model - such as custom annotations for JPA or OptaPlanner. No more XML mapping!

23 February 2015

Setting up Drools Workbench and Execution Server (6.2.0.CR4)

Get Wildfly-8.1.0.Final.zip and unzip it into a directory. Then add three user names before start up.
Use the /bin/add-user.sh (or .bat) script to add three users.
These settings by default are stored in:

/standalone/configuration/mgmt-users.properties and application-users.properties

with the passwords hashed.

Use the $WILDFLY_HOME/bin/add-user.sh (or .bat for Windows) script to add three users.
The first user will become Admin on Wildfly and will be stored in mgmt-users.properties:
*What type of user do you wish to add?
Insert a
*Enter the details of the new user to add.
Username: admin
Password: xxxxxxxx
*What groups do you want this user to belong to? (Please enter a comma separated list,
or leave blank for none)[ ]:
Just leave this blank by hitting enter
*Is this new user going to be used for one AS process to connect to another AS process?
e.g. for a slave host controller connecting to the master or for a Remoting connection
for server to server EJB calls.
yes/no?
Insert no

Now we have our Wildfly Admin. Next up is the Drools Workbench user with admin rights.
*What type of user do you wish to add?
Insert b
*Enter the details of the new user to add.
Username: wb-user
Password: xxxxxxxx
*What groups do you want this user to belong to? (Please enter a comma separated list,
or leave blank for none)[ ]:
Insert admin
*About to add user 'wb-user' for realm 'ApplicationRealm'
Is this correct yes/no?
Insert yes
*Is this new user going to be used for one AS process to connect to another AS process?
e.g. for a slave host controller connecting to the master or for a Remoting connection for
server to server EJB calls.
yes/no?
Insert no

So, this is our Drools Workbench user. The last user is needed for the Drools execution server.
*What type of user do you wish to add?
Insert b
*Enter the details of the new user to add.
Username: ks-user
Password: xxxxxxxx
*What groups do you want this user to belong to? (Please enter a comma separated list,
or leave blank for none)[ ]:
Insert kie-server
*About to add user 'wb-user' for realm 'ApplicationRealm'
Is this correct yes/no?
Insert yes
*Is this new user going to be used for one AS process to connect to another AS process?
e.g. for a slave host controller connecting to the master or for a Remoting connection for
server to server EJB calls.
yes/no?
Insert no

To use one user for Drools Workbench and Execution server, combine the groups.

Start Wildfly using /bin/standalone.sh (or .bat for Windows) and browse to
http://127.0.0.1:9990 and log in as Wildfly admin.
Now we need to download the Drools Workbench and Execution server .war files.
They are locared in the Jboss Release repository under:
https://repository.jboss.org/nexus/index.html#view-repositories;releases~browsestorage.
Navigate in the lower panel to org/kie/kie-drools-wb-distribution-wars/6.2.0.CR4
and download the wildfly8.war file. For the Kie server navigate to
org/kie/kie-server-distribution-wars/6.2.0.CR4 and download the
kie-server-distribution-wars-6.2.0.CR4-ee6.war or -ee7.war file according to the
Java Enterprise version in use. Use the Wildfly Management to load and enable the two war files.
The Wildfly log files can be found under /standalone/log.
Login to the Drools Workbench user the second user:
http://localhost:8080/kie-drools-wb-distribution-wars-6.2.0.CR4-wildfly8/
(I have issues loading the Workbench in Chrom and Firefox, but IE seems to work fine)
All that is left is to test the Kie server deployment, type the following url into the browser
and login using user number 3:
http://localhost:8080/kie-server-distribution-wars-6.2.0.CR4-ee7/services/rest/server
If succesfull you wil get the following response:

<response msg="Kie Server info" type="SUCCESS">
<kie-server-info>
<version>6.2.0.CR4</version>
</kie-server-info>
</response>

The Execution server is registered with Drools Workbench under menu item Deploy/Rule Deployments and then Register (on the right of the Window).
Endpoint:
http://localhost:8080/kie-server-distribution-wars-6.2.0.CR4-ee7/services/rest/server
Name:
container-name
Username
ks-user
Password
xxxxxxxx
and Connect.

This will create a named Container to deploy and execute the Rules.

Have fun!

26 August 2014

OpenCV, Java and CLAHE

As it seems that the OpenCV guys have missed porting the creation of the Contrast Limited Adaptive Histogram Equalization algorithm to Java in OpenCV 2.4.9, so my colleage developer Michael Niephaus and myself have implemented a version in Java using the objects from the OpenCV  project.

import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Range;
import org.opencv.core.Rect;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

public class CLAHE {

private final static int BUFFER_SIZE = 256;
private final double clipLimit_;
private final int tilesX_;
private final int tilesY_;
Mat lut_ = new Mat();

public CLAHE() {
this(40, 8, 8);
}

public static int saturateCast(int x) {
return x > BUFFER_SIZE - 1 ? BUFFER_SIZE - 1 : (x < 0 ? 0 : x);
}

public static int saturateCast(float x) {
return (int) (x > BUFFER_SIZE - 1 ? BUFFER_SIZE - 1 : (x < 0 ? 0 : x));
}

public int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}

public CLAHE(double clipLimit, int tilesX, int tilesY) {
this.clipLimit_ = clipLimit;
this.tilesX_ = tilesX;
this.tilesY_ = tilesY;
}

public Mat apply(Mat src) {
if (src.type() != CvType.CV_8UC1) {
throw new IllegalArgumentException("Mat not of type CV_8UC1!");
}
Mat dst = new Mat(src.size(), src.type());
lut_.create(tilesX_ * tilesY_, BUFFER_SIZE, CvType.CV_8UC1);

Size tileSize;
Mat srcForLut;

if (src.cols() % tilesX_ == 0 && src.rows() % tilesY_ == 0) {
tileSize = new Size(src.cols() / tilesX_, src.rows() / tilesY_);
srcForLut = src;
} else {
Mat srcExt_ = new Mat();
Imgproc.copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows() % tilesY_), 0, tilesX_ - (src.cols() % tilesX_), Imgproc.BORDER_REFLECT_101);
tileSize = new Size(srcExt_.cols() / tilesX_, srcExt_.rows() / tilesY_);
srcForLut = srcExt_;
}

double tileSizeTotal = tileSize.area(); // int ?
float lutScale = (float) ((BUFFER_SIZE - 1) / tileSizeTotal); // why BUFFER_SIZE - 1 ?
int clipLimit = 0;
if (clipLimit_ > 0.0) {
clipLimit = (int) (clipLimit_ * tileSizeTotal / BUFFER_SIZE);
if (clipLimit < 1) {
clipLimit = 1;
}
}
CLAHE_CalcLut_Body calcLutBody = new CLAHE_CalcLut_Body(srcForLut, lut_, tileSize, tilesX_, clipLimit, lutScale);
calcLutBody.execute(new Range(0, tilesX_ * tilesY_));

CLAHE_Interpolation_Body interpolationBody = new CLAHE_Interpolation_Body(src, dst, lut_, tileSize, tilesX_, tilesY_);
interpolationBody.execute(new Range(0, src.rows()));

return dst;
}

private class CLAHE_Interpolation_Body {

Mat src_;
Mat dst_;
Mat lut_;
Size tileSize_;
int tilesX_;
int tilesY_;

CLAHE_Interpolation_Body(Mat src, Mat dst, Mat lut_, Size tileSize, int tilesX_, int tilesY_) {
this.src_ = src;
this.dst_ = dst;
this.lut_ = lut_;
this.tileSize_ = tileSize;
this.tilesX_ = tilesX_;
this.tilesY_ = tilesY_;
}

void execute(Range range) {
int lut_step = (int) lut_.step1();
int lut_break = tilesX_ * lut_step;

for (int y = range.start; y < range.end; ++y) {

float tyf = (y / (float) tileSize_.height) - 0.5f;
int ty1 = (int) Math.floor(tyf);
int ty2 = ty1 + 1;
float ya = tyf - ty1;
// keep largest
if (ty1 < 0) {
ty1 = 0;
}
// keep smallest
if (ty2 > tilesY_ - 1) {
ty2 = tilesY_ - 1;
}

int lutPlane1 = ty1 * tilesX_;
int lutPlane2 = ty2 * tilesX_;

for (int x = 0; x < src_.cols(); x++) {

float txf = (x / (float) tileSize_.width) - 0.5f;
int tx1 = (int) Math.floor(txf);
int tx2 = tx1 + 1;
float xa = txf - tx1;
// keep largest
if (tx1 < 0) {
tx1 = 0;
}
// keep smallest
if (tx2 > tilesX_ - 1) {
tx2 = tilesX_ - 1;
}
// original pixel value
double[] ptr = src_.get(y, x);
int srcVal = (int) ptr[0];

int ind1 = tx1 * lut_step + srcVal;
int ind2 = tx2 * lut_step + srcVal;

int column1 = (ind1 + (ty1 * lut_break)) % lut_step;
int row1 = (ind1 + (ty1 * lut_break)) / lut_step;

int column2 = (ind2 + (ty1 * lut_break)) % lut_step;
int row2 = (ind2 + (ty1 * lut_break)) / lut_step;

int column3 = (ind1 + (ty2 * lut_break)) % lut_step;
int row3 = (ind1 + (ty2 * lut_break)) / lut_step;

int column4 = (ind2 + (ty2 * lut_break)) % lut_step;
int row4 = (ind2 + (ty2 * lut_break)) / lut_step;

float res = 0;

double[] lut_ptr1 = lut_.get(row1, column1);
res += ((byte) lut_ptr1[0] & 0xFF) * ((1.0f - xa) * (1.0f - ya));

double[] lut_ptr2 = lut_.get(row2, column2);
res += ((byte) lut_ptr2[0] & 0xFF) * ((xa) * (1.0f - ya));

double[] lut_ptr3 = lut_.get(row3, column3);
res += ((byte) lut_ptr3[0] & 0xFF) * ((1.0f - xa) * (ya));

double[] lut_ptr4 = lut_.get(row4, column4);
res += ((byte) lut_ptr4[0] & 0xFF) * ((xa) * (ya));

dst_.put(y, x, saturateCast(res));
}
}
}
}

private class CLAHE_CalcLut_Body {

Mat src_;
Mat lut_;
Size tileSize_;
int tilesX_;
int clipLimit_;
float lutScale_;

CLAHE_CalcLut_Body(Mat srcForLut, Mat lut_, Size tileSize, int tilesX_, int clipLimit, float lutScale) {
this.src_ = srcForLut;
this.lut_ = lut_;
this.tileSize_ = tileSize;
this.tilesX_ = tilesX_;
this.clipLimit_ = clipLimit;
this.lutScale_ = lutScale;
}

void execute(Range range) {
int[] tileHist;
int[] lutBytes = new int[lut_.height() * lut_.width()];
for (int k = range.start; k < range.end; ++k) {
int ty = k / tilesX_;
int tx = k % tilesX_;
// retrieve tile submatrix
Rect tileROI = new Rect();
tileROI.x = (int) (tx * tileSize_.width);
tileROI.y = (int) (ty * tileSize_.height);
tileROI.width = (int) tileSize_.width;
tileROI.height = (int) tileSize_.height;
Mat tile = src_.submat(tileROI);
// calc histogram
tileHist = new int[BUFFER_SIZE];
int height = tileROI.height;

for (int h = height; h > 0; h--) {
int x;
double[] ptr;
for (int w = 0; w < tileROI.width; w++) {
ptr = tile.get(h - 1, w);
tileHist[(int) ptr[0]]++;
}
}
// clip histogram
if (clipLimit_ > 0) {
// how many pixels were clipped
int clipped = 0;
for (int i = 0; i < BUFFER_SIZE; ++i) {
if (tileHist[i] > clipLimit_) {
clipped += tileHist[i] - clipLimit_;
tileHist[i] = clipLimit_;
}
}
// redistribute clipped pixels
int redistBatch = clipped / BUFFER_SIZE;
int residual = clipped - redistBatch * BUFFER_SIZE;
for (int i = 0; i < BUFFER_SIZE; ++i) {
tileHist[i] += redistBatch;
}
for (int i = 0; i < residual; ++i) {
tileHist[i]++;
}
}
// calc Lut
int sum = 0;
for (int i = 0; i < BUFFER_SIZE; ++i) {
sum += tileHist[i];
lut_.put(k, i, saturateCast(Math.round(sum * lutScale_)));
}
}
}
}
}

//  DISCLAIMER :
// This software is provided "as is".
// Any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the blog writer be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.

4 January 2014

OpenCV CMake Java Maven OSGi toolchain

OpenCV is a cross platform computer vision library written in c / c++ with a Java interface. The first thing to solve is the generation and compilation of the sources using CMake and Maven. The Maven plugin  cmake-maven-project does great things here. Now we can add this as a dependency to our OpenCV Maven project and use it for cross platform compilation.
Download the OpenCV sources from github and add them to your OpenCV Maven project. The OpenCV-CMake make-files produce, depending on platform compiling, a .dll or .so file and the Java source files. These are copied into src/main/resources and src/main/java respectively. Now we are ready for the Maven Bundle plugin.
OSGi has a easy way to resolve dependencies on native code called the bundle native code tag. Point this to the .dll / .so file in resources. Add a bundle activate class to the package, calling System.loadLibrary, and your of deploying OpenCV to OSGi.

2 October 2013

Automate p2 Eclipse plugin transfer to Maven

In my last post i discribed a way to transfer Eclsipe p2 plugins to a Maven repository. To automate this in a Maven project one can setup a pom like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>your-group-id</groupId>
    <artifactId>your-artifact-id</artifactId>
    <version>1.0.0</version>
    <name>your-name</name>
    <packaging>pom</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

     <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <inherited>false</inherited>
                <executions>
                    <execution>
                        <id>copy-eclipse-resources-to-maven</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>to-maven</goal>
                        </goals>
                        <configuration>
                            <eclipseDir>${basedir}/src/main/config/eclipse</eclipseDir>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.4.0</version>
                <inherited>false</inherited>
                <executions>
                    <execution>
                        <id>obr-indexing</id>
                        <phase>install</phase>
                        <configuration>
                            <urlTemplate>maven</urlTemplate>
                        </configuration>
                        <goals>
                            <goal>clean</goal>
                            <goal>index</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

After the transfer the maven bundle plugin will do an indexing so all plugins are also available in the Object Bundle Repository.

29 September 2013

Using Eclipse plugins in a Equinox - Karaf setup.

Using a modular standard like OSGi promises manny goodies, even the ability the swap out the core implementing the OSGi model and deploying bundles on different OSGi implementations ... but not quite. Every implementation brings in its own background like provisioning, restricting things even more. But now i am getting ahead of myself, back to the beginning.

My main OSGi (development) platform so far is Felix wrapped in a Karaf container backed by Maven for provisioning. Now i had to implement the Open Health Tools Model-Driven Health Tools (MDHT) which, as i was about to find out, is Eclipse based and thus uses the provisioning system called p2.

My first thought was to retrieve all the MDHT sources and convert them to Maven projects, there was even a standalone setup provided which proved functional. Looking into the source i discovered MDHT makes heavy use of the Eclipse Modeling Framework (EMF) and the Eclipse Object Constraint Language (OCL), powerful and non trivial frameworks with a lot of dependencies of their own that are mostly not even Mavenized. The deployment on my favorite OSGi combo was bound to fail, i needed an environment matching that of Eclipse.

Then i remembered that Karaf could swap out Felix, and guess for what: Equinox! Simply edit the etc/config.properties file and modify the karaf.framework property to equinox and finished. This leaves me with the provisioning problem since Karaf has a preference for Maven. Converting the sources myself for such big frameworks is not an option for obvious reasons and after some digging i found myself looking at the Maven website: http://maven.apache.org/plugins/maven-eclipse-plugin/.
MDHT is also a modeling tool for Clinical Document Architecture (CDA) templates based on Eclipse, and thus Equinox, meaning it exists out of Eclipse plugins provisioned by p2.
Using the Maven Eclipse Plugin goal eclipse:to-maven i was able to copy the MDHT Eclipse artifacts out of p2 to my local Maven repository and after a re-indexing by the OSGi Bundle Repository (OBR) i finally could install EMF and OCL on my Equinox - Karaf combo. And of course one can now use the Eclipse artifacts in any Maven project.

More practical experiences are bound to follow.

10 July 2013

Monitoring OSGi services and bundles

Keeping track of OSGi services and bundles can be a tedious task. Declerative Services provide a good degree of control here, but for fine grain control the OSGi api presents the org.osgi.util.tracker package.
With the ServiceTracker and BundleTracker classes it is really easy to monitor your enviroment for add, modify or remove events. It provides filtering capabillities trough the customizer interfaces and keeps a record of all registred objects being tracked.
This is also the perfect location to hook into these events, like for updating any logging to be done on the bundles or services in your framework.
The bruise to be avoided here is the addingService / Bundle methodes. These normally return the object that raised the event for the add methode. However, this can be overridden in a subclass to customize the object to be tracked for the one just being added!