Archive for the ‘Coding’ Category

NetBeans plugin migration

January 11th, 2017 No comments

After installing the latest version of NetBeans I found that my old plugins were not migrated. I did the following to migrate them:

Run the new version of NetBeans and tell it to import my old stuff. Then close it again.

Copy the modules directory in ~/.netbeans/ to ~/.netbeans/

cp -avn ~/.netbeans/<old version>/modules ~/.netbeans/<new version>

Copy additional items from ~/.netbeans/config/Modules

cp -avn ~/.netbeans/<old version>/config/Modules/* ~/.netbeans/<new version>/config/Modules

That did the trick for me though it might not always work depending on the version you are migrating from and to.

Categories: Coding Tags:

Atom plugin installation from command line

November 15th, 2016 No comments

Once you have set up your atom editor it is nice if you can store the list of installed plugins so you can easily reinstall or share with friends. Here are the commands to do so from the command line:


apm list --installed --bare > packages.txt


apm install --packages-file packages.txt


Categories: Coding Tags:

Java custom validation with predicate annotation

October 14th, 2016 No comments

Just two small classes I wrote to be able to do some easy validation when you need to have more contextual information when validating an entity. This will allow you to do that easily while preventing the rewriting of boilerplate code.

The annotation:

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Repeatable;
import javax.validation.Constraint;
import javax.validation.Payload;
@Constraint(validatedBy = PredicateValidator.class)
public @interface Predicate {
	String message() default "{predicate.invalid}";
	Class<?>[] groups() default {};
	Class<? extends Payload>[] payload() default {};
	String name();
	public @interface List {
		Predicate[] value();

The validator:

import java.util.HashMap;
import java.util.Map;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PredicateValidator implements ConstraintValidator<Predicate, Object> {
	private static final Map<String, java.util.function.Predicate> PREDICATES = new HashMap<>();
	private java.util.function.Predicate predicate;
	public void initialize(Predicate predicate) {
		if (!PREDICATES.containsKey( {
			throw new IllegalArgumentException("No predicate with name " + + " found");
		this.predicate = PREDICATES.get(;
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		return predicate.test(value);
	public static void addPredicate(String name, java.util.function.Predicate p) {
		PREDICATES.put(name, p);

And a small example:

import java.util.Objects;
@Predicate(name = "myPredicate")
@Predicate(name = "myPredicate2")
public class Pojo {
	static {
		PredicateValidator.addPredicate("myPredicate", obj -> {
			Pojo p = (Pojo) obj;
			System.out.println("Test 1");
			return Objects.equals(p.getValueOne(), p.getValueTwo());
		PredicateValidator.addPredicate("myPredicate2", obj -> {
			Pojo p = (Pojo) obj;
			System.out.println("Test 2");
			return Objects.equals(p.getValueOne(), p.getValueTwo());
	private String valueOne;
	private String valueTwo;
	public String getValueOne() {
		return valueOne;
	public void setValueOne(String valueOne) {
		this.valueOne = valueOne;
	public String getValueTwo() {
		return valueTwo;
	public void setValueTwo(String valueTwo) {
		this.valueTwo = valueTwo;

Maven and Grails

January 27th, 2014 No comments

I needed to push the generated Grails war into a maven repository. There are several ways to do this. I used the grails create-pom command (2.3.1) to create a pom.xml file. This seemed most logical to me.

Then I tried to do a mvn clean install from there to have it put in my local repo. This failed hard.

Fatal error forking Grails JVM: java.lang.reflect.InvocationTargetException

I changed the grails-maven-plugin to not fork to get a less cryptic description of the problem.

		<!-- Whether for Fork a JVM to run Grails commands -->

This got me the actual error description:

Unable to start Grails: java.lang.reflect.InvocationTargetException: Provider org.apache.xerces.jaxp.SAXParserFactoryImpl not found

The dreaded xerces error.

I apparently had some unwanted dependencies. I executed a mvn dependency:tree to see if any of these were in use.
DynamicJasper seemed to be the culprit here. It contained a runtime dependency on xml-apis.

[INFO] +-
[INFO] |  \- net.sf.jasperreports:jasperreports:jar:4.1.1:runtime
[INFO] |     +- commons-digester:commons-digester:jar:1.7:runtime
[INFO] |     +- com.lowagie:itext:jar:2.1.7:runtime
[INFO] |     |  \- org.bouncycastle:bctsp-jdk14:jar:1.38:runtime
[INFO] |     |     +- org.bouncycastle:bcprov-jdk14:jar:1.38:runtime
[INFO] |     |     \- org.bouncycastle:bcmail-jdk14:jar:1.38:runtime
[INFO] |     +- jfree:jcommon:jar:1.0.15:runtime
[INFO] |     +- jfree:jfreechart:jar:1.0.12:runtime
[INFO] |     +- xml-apis:xml-apis:jar:1.3.02:runtime
[INFO] |     +- eclipse:jdtcore:jar:3.1.0:runtime
[INFO] |     +- org.codehaus.castor:castor:jar:1.2:runtime
[INFO] |     \- org.apache.poi:poi-ooxml:jar:3.6:runtime
[INFO] |        +- org.apache.poi:poi:jar:3.6:runtime
[INFO] |        \- org.apache.poi:poi-ooxml-schemas:jar:3.6:runtime
[INFO] |           +- org.apache.xmlbeans:xmlbeans:jar:2.3.0:runtime
[INFO] |           \- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0:runtime

I then dropped the dependency in my pom.xml:


After this I could install/deploy the artifact.

Categories: Grails Tags:


June 12th, 2013 2 comments

I wanted to have a data package containing only JPA annotations.

I created a base class specifying the keytype (I use UUID and Long based Entities):

 * Absolute base class for persistable classes.
 * Contract forces get and set methods for id.
 * @author wytze
 * @param <KeyType>
public abstract class Persistable<KeyType extends Serializable> {
	public abstract KeyType getId();
	public abstract void setId(KeyType id);
import java.util.UUID;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
public abstract class UuidBasedEntity extends Persistable<UUID> {
	private UUID id;
	public UUID getId() {
		return id;
	public void setId(UUID id) { = id;

Sample entity:

import java.util.UUID;
import javax.persistence.Entity;
public class Sample extends UuidBasedEntity implements Serializable {
	private String someExampleProperty;
        /* ... getters and setters */

All these entities go in one separate jar.

Next I create another package using the entity jar.

package com.famvdploeg.dao;
public interface GenericRepository<Entity extends Persistable> {
	public void persist(Entity e);
	public Entity findById(Serializable id);
	public void merge(Entity t);
	public void remove(Serializable id);
	public Entity saveOrUpdate(Entity entity);

And a generic implementation of this dao: (Spring is used to inject the persistencecontext)

package com.famvdploeg.dao.jpa;
import com.famvdploeg.dao.GenericRepository;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
public class GenericJpaRepository<Entity extends Persistable> implements GenericRepository<Entity> {
	protected EntityManager em;
	public void persist(Entity e) {
	public Entity findById(Serializable id) {
		return em.find(returnEntityClass(), id);
	public void merge(Entity e) {
	public void remove(Serializable id) {
	public void flush() {
	public Entity saveOrUpdate(Entity entity) {
		if (entity.getId() == null) {
			return entity;
		} else {
			return em.merge(entity);
	protected List<Entity> findAll() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Entity> cq = cb.createQuery(returnEntityClass());
		return em.createQuery(cq).getResultList();
	protected Entity findByProperty(String property, Object value) {
		try {
			return em.createQuery(createQueryByProperty(property, value)).getSingleResult();
		} catch (NoResultException ex) {
			return null;
	protected List<Entity> findAllByProperty(String property, Object value) {
		return em.createQuery(createQueryByProperty(property, value)).getResultList();
	protected Entity findByProperties(Map<String, Object> properties) {
		try {
			return em.createQuery(createQueryByProperties(properties)).getSingleResult();
		} catch (NoResultException ex) {
			return null;
	protected List<Entity> findAllByProperties(Map<String, Object> properties) {
		return em.createQuery(createQueryByProperties(properties)).getResultList();
	public Class<Entity> returnEntityClass() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
		return (Class<Entity>) genericSuperclass.getActualTypeArguments()[0];
	private CriteriaQuery<Entity> createQueryByProperty(String property, Object value) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Entity> cq = cb.createQuery(returnEntityClass());
		Root<Entity> root = cq.from(returnEntityClass());
		cq = cq.where(cb.equal(root.get(property), value));
		return cq;
	private CriteriaQuery<Entity> createQueryByProperties(Map<String, Object> properties) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Entity> cq = cb.createQuery(returnEntityClass());
		Root<Entity> root = cq.from(returnEntityClass());
		for (Entry<String, Object> entry : properties.entrySet()) {
			cq = cq.where(cb.equal(root.get(entry.getKey()), entry.getValue()));
		return cq;

Now I want to use hibernate to map my UUID’s as PostgreSQL uuid type. We will add a mapping to do so.

(location: com/famvdploeg/data/CustomTypes.hbm.xml, place in DAO/Repository jar)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
		Section 6.5 covers type registry and registerTypeOverride method on the Configuration object,
		typedefs are the preferred way of registering custom types
    <typedef name="java.util.UUID" class="org.hibernate.type.UUIDCharType" />
        I want to store clob values as text and not as materialized clobs so we override that here.
        Otherwise the database will show long values when using an SQL tool to query the database.
    <typedef name="materialized_clob" class="org.hibernate.type.TextType" />
	<!-- Possible values:
	<typedef name="java.util.UUID" class="org.hibernate.type.UUIDBinaryTypee" />
	<typedef name="java.util.UUID" class="org.hibernate.type.UUIDCharType" />
	<typedef name="java.util.UUID" class="org.hibernate.type.PostgresUUIDType" />

Next we fill the persistence.xml

(location: META-INF/persistence.xml)

<?xml version="1.0" encoding="UTF-8"?>
	<persistence-unit name="jpa-example-postgres" transaction-type="RESOURCE_LOCAL">
			<!--<property name="hibernate.archive.autodetection" value="class, hbm"/>-->
			<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />
                        <!-- Use this only for testing!
			<property name="" value="create-drop" />
                        <!-- Nicer naming of tables with underscores fooName -> foo_name -->
			<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
			<!-- Connection properties, moved to datasource (@see applicationContext.xml)
			<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/jpa_example" />
			<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
			<property name="hibernate.connection.username" value="example" />
			<property name="hibernate.connection.password" value="example" />
			<!-- c3p0 connection pooling, setup when creating datasource (@see com.mchange.v2.c3p0.ComboPooledDataSource)
			<property name="hibernate.c3p0.min_size">5</property>
			<property name="hibernate.c3p0.max_size">20</property>
			<property name="hibernate.c3p0.timeout">300</property>
			<property name="hibernate.c3p0.max_statements">50</property>
			<property name="hibernate.c3p0.idle_test_period">3000</property>
                <!-- The specific mapping for UUID's is added here -->

And for completeness the applicationContext.xml for Spring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
	xmlns:xsi="" xmlns:context=""
	xmlns:mvc="" xmlns:tx=""
	xmlns:aop="" xmlns:task=""
	<!-- In production: <bean class=""> -->
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<!-- Test properties. Should be filled from Context.xml in production -->
		<property name="properties">
				<prop key="jpa-example-jdbc-url">jdbc:h2:mem:jpa_example</prop>
				<prop key="jpa-example-jdbc-username">sa</prop>
				<prop key="jpa-example-jdbc-password">sa</prop>
				<prop key="jpa-example-jdbc-driver">org.h2.Driver</prop>
				<prop key="jpa-example-jdbc-url">jdbc:postgresql://localhost:5432/jpa_example</prop>
				<prop key="jpa-example-jdbc-username">example</prop>
				<prop key="jpa-example-jdbc-password">example</prop>
				<prop key="jpa-example-jdbc-driver">org.postgresql.Driver</prop>
	<!-- Use pooled in production, @see com.mchange.v2.c3p0.ComboPooledDataSource -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url" value="${jpa-example-jdbc-url}" />
		<property name="username" value="${jpa-example-jdbc-username}" />
		<property name="password" value="${jpa-example-jdbc-password}" />
		<property name="driverClassName" value="${jpa-example-jdbc-driver}" />
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="jpa-example-postgres" />
		<property name="dataSource" ref="dataSource" />
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	<tx:annotation-driven transaction-manager="transactionManager" />
	<context:annotation-config />

It is also possible to store the UUID as a char(36) to do this we need to change the type in the CustomTypes.hbm.xml to org.hibernate.type.UUIDCharType.
We can then modify the mapping from the data jar through adding an orm.xml to the META-INF folder. It will normally create a varchar(255) column but that is useless. We want to specify the use of an char(36) column as UUID’s are stored as Strings of a fixed length of 36 characters.

<?xml version="1.0" encoding="UTF-8"?>
  xsi:schemaLocation=" orm_2_0.xsd"
	<mapped-superclass class="UuidBasedEntity" metadata-complete="false">
			<id name="id">
				<column column-definition="char(36)" />

That’s it! Awesome! Clean separation of JPA and Hibernate.

Categories: Java Tags:

Grails easy JSON DTO’s

May 25th, 2013 No comments

Some JSON is only used in specific places. For these occurrences I use extension methods / meta methods to easily convert my classes into the required JSON without the need for a specific mapping/dto class. To do this I declare a Markup interface (called Mappable) on which the method can be invoked.

I put the following interface in src/groovy:

package com.example.json
 * Markup interface so we can add extension methods to convert objects to maps.
 * @see MetaMethods.groovy
interface Mappable {}

I then add the following to my MetaMethods class in src/groovy:

package com.example.json;
class MetaMethods {
    static void register() {
        Mappable.metaClass.toMap { whitelist, blacklist ->
            /* metaClass, class */
            def map = [:];
            /* id seems to be a special case */
            if (("id" in whitelist) || (!"id" in blacklist)) {
                map["id"] = delegate["id"];
            if (whitelist) {
                whitelist.each {
                    map[it] = delegate[it]
            } else if (blacklist) {
       { prop, val ->
                    if (!(prop in blacklist)) {
                        map[prop] = val;
            return map;

I register the metamethods in my Bootstrap.groovy

class BootStrap {
    def init = { servletContext ->
        /* Register our own Meta Methods/Extension Methods */

Now we can create easy JSON dto’s based on our domain (don’t forget to add the Mappable interface to your domain classes).

Usage example:

        def jsonMap = myDomainClass.toMap(["id", "propertyX", "propertyZ"], []); // 1st level properties
        jsonMap["customer"] = myDomainClass.customer ? myDomainClass.customer.toMap(["id", "fullName", "firstName", "insertion", "lastName"], []) : null; // 2nd level properties
        render jsonMap as JSON; // or as XML

Happy Grailing!

Setting up an OrientDB server on Ubuntu

January 19th, 2013 13 comments

Go to the directory you want to install OrientDB.

cd /opt

Download one of the two flavors of OrientDB (standard or graph edition). (If you don’t know which to take, pick the Graph Ed.)

sudo wget
#sudo wget

Unpack the file

sudo tar -zxvf orientdb-1.3.0.tar.gz

I usually remove the tar.gz file and add a symlink

sudo rm orientdb-1.3.0.tar.gz
sudo ln -s orientdb-1.3.0/ orientdb

Configure the default orientdb password. (I use vi, you use your own favorite editor ;))

sudo vi orientdb/config/orientdb-server-config.xml

Go to the section [orient-server > storages > storage] in the xml, change the default username and password and save the file

<!-- Default in-memory storage. Data are not saved permanently. -->
<storage path="memory:temp" name="temp" userName="yourUsername" userPassword="yourPassword" loaded-at-startup="true" />

Get the root password for later use or/and add your own preferred account in [orient-server > users]:
(I prefer to remove the root account and add a new one)

<user name="yourUsername" password="yourPassword" resources="*"/>

As the file is holding passwords it might be a good idea to remove the read permission for other users.

sudo chmod 640 /opt/orientdb/config/orientdb-server-config.xml

Create a user that will run the server:

# -d, --home-dir HOME_DIR       home directory of the new account
# -M, --no-create-home          do not create the user's home directory
# -r, --system                  create a system account
# -s, --shell SHELL             login shell of the new account (/bin/false =  no login)
# -U, --user-group              create a group with the same name as the user
sudo useradd -d /opt/orientdb -M -r -s /bin/false -U orientdb

Change ownership of orientdb directory/links:

sudo chown -R orientdb.orientdb orientdb*

Modify the user group rights so that users in the orientdb group can invoke shell scripts.

sudo chmod 775 /opt/orientdb/bin
sudo chmod g+x /opt/orientdb/bin/*.sh
sudo usermod -a -G orientdb yourUsername

Copy the init.d script:

sudo cp orientdb/bin/ /etc/init.d/

Update the init.d script with this sed script or just edit the file. (The copied one)

sudo sed -i "s|YOUR_ORIENTDB_INSTALLATION_PATH|/opt/orientdb|;s|USER_YOU_WANT_ORIENTDB_RUN_WITH|orientdb|" /etc/init.d/

And change the following lines, we use sudo because our system account does not have a login shell.

# You have to SET the OrientDB installation directory here (if not already done so)
#su -c "cd \"$ORIENTDB_DIR/bin\"; /usr/bin/nohup ./ 1>../log/orientdb.log 2>../log/orientdb.err &" - $ORIENTDB_USER
sudo -u $ORIENTDB_USER sh -c "cd \"$ORIENTDB_DIR/bin\"; /usr/bin/nohup ./ 1>../log/orientdb.log 2>../log/orientdb.err &"
#su -c "cd \"$ORIENTDB_DIR/bin\"; /usr/bin/nohup ./ 1>>../log/orientdb.log 2>>../log/orientdb.err &" - $ORIENTDB_USER
sudo -u $ORIENTDB_USER sh -c "cd \"$ORIENTDB_DIR/bin\"; /usr/bin/nohup ./ 1>>../log/orientdb.log 2>>../log/orientdb.err &"

Update the rc.d dirs

cd /etc/init.d
sudo update-rc.d defaults

The server will now start and stop on startup/shutdown. For now we start it by hand.

sudo /etc/init.d/ start

Verify that it is running by opening the studio (e.g. http://localhost:2480/) or run ‘sudo /etc/init.d/ status’.

Now we can log in and create a new database,
Start the console:


Create a new database:

create database remote:/yourDatabaseName yourUsername yourPassword local

Done. Grab a beer, you’ve earned it. 😉

jQuery + Fancybox + Vimeo PlugIn

February 3rd, 2012 No comments

Just a small jQuery plugin that I wrote to quickly add playing of vimeo clips in a fancybox (unobtrusive).

(function ($) {
    $.fn.vimeoInFancybox = function (options) {
        var opts = $.extend({}, $.fn.vimeoInFancybox.defaults, options);
        $(this).each(function () {
            var url = $(this).attr("href");
            var optionRegex = new RegExp(".*?/([\\d]+)$");
            var vimeoId = optionRegex.exec(url)[1];
            var playerUrl = "" + vimeoId;
                href: playerUrl,
                type: 'iframe',
                width: opts.width,
                height: opts.height
    $.fn.vimeoInFancybox.defaults = {
        width: 640,
        height: 480
$(function () {

Example: (Just include the js on the page in a javascript tag or in a separate file that is included)

<a href="" class="fancybox-vimeo">Add image here if you want</a>
Categories: jQuery Tags:

jQuery + CSS3 rotating panel

January 17th, 2012 No comments

This is just a small proof of concept (so don’t blame me for the lame CSS I created. ;)).
I found out it can be done nicer. (Read this awesome article about flip effects) I only do 90 degree rotations on the Y-axis and do no backside-hiding.

The idea is that a visible panel is seemingly rotated and the backside becomes visible. This works by using transition events. The 1st panel is visible at start and the 2nd panel is hidden. Then when an event is triggered (Hovered in this example) the 1st panel will be rotated 90 degrees (y-axis). The panel is then invisible the animation is ended and an event is triggered. At that point the 2nd panel is made visible and an class is added to trigger to animate it from 90 degrees back to 0 degrees. Thus creating an animation which makes it seem like the panel was completely rotated.

The implementation is currently only working for webkit based browsers.

	<style type="text/css"> 
		    -webkit-transition: -webkit-transform 0.5s ease-in;
		    -webkit-transform: rotateY(90deg);
		    -webkit-transition: -webkit-transform 0.5s ease-in;
		    -webkit-transform: rotateY(90deg);
		    -webkit-transform: rotateY(0deg);
	<script type="text/javascript" src=""></script>
	<script type="text/javascript">
			function( event ) {
			}, false );
	<p><b>Note:</b> This example does not work in Internet Explorer.</p>
	<div id="slide1">Test</div>
	<div id="slide2" style="display: none;">Awesome</div>
	<p>Hover over the div element above, to see the transition effect.</p>
Categories: Coding Tags: , , , , ,

Adding awesomeness on the run with javassist

January 17th, 2012 No comments

Creating new classes during runtime can be nice when you need it. Below is a small example of what is possible. (No interface or existing base class is used in this example so reflection is required to invoke a method)

ClassPool classPool = ClassPool.getDefault();
CtClass cc = classPool.makeClass("AwesomeNewClass");
cc.addMethod(CtMethod.make("public String getValue() { return \"Hello World!\"; }", cc));
Class awesome = cc.toClass();
Object o = awesome.newInstance();
Method method = awesome.getMethod("getValue");
String returnValue = (String) method.invoke(o);
Categories: Java Tags: , , , ,