Tag Archive | java

Efficiently delete data with JPA and Hibernate

You may come to the situation where you have to perform a bulk deletion on a huge amount of datasets stored in a relational database. If you use JPA with Hibernate as underlying OR mapper, you might try to call the remove() method of the EntityManager in a way like the following:

public void removeById(long id) {
    RootEntity rootEntity = entityManager.getReference(RootEntity.class, id);
    entityManager.remove(rootEntity);
}

First of all, we load a reference representation of the entity we want to delete and then pass this reference to the EntityManager. Let’s assume the RootEntity from above has a child relation to a class called ChildEntity:

@OneToMany(mappedBy = "rootEntity", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set childEntities = new HashSet(0);

If we now turn on the property show_sql of hibernate, we will wonder what SQL statements are issued:

    select
        rootentity0_.id as id5_1_,
        rootentity0_.field1 as field2_5_1_,
        rootentity0_.field2 as field3_5_1_,
        childentit1_.PARENT as PARENT5_3_,
        childentit1_.id as id3_,
        childentit1_.id as id4_0_,
        childentit1_.field1 as field2_4_0_,
        childentit1_.field2 as field3_4_0_,
        childentit1_.PARENT as PARENT4_0_
    from
        ROOT_ENTITY rootentity0_
    left outer join
        CHILD_ENTITY childentit1_
            on rootentity0_.id=childentit1_.PARENT
    where
        rootentity0_.id=?

    delete
    from
        CHILD_ENTITY
    where
        id=?

   delete
   from
       ROOT_ENTITY
   where
       id=?

Why does Hibernate first load all data into memory in order to delete this data immediately afterwards? The reason is that JPA’s lifecycle requires that the object is in “managed” state, before it can be deleted. Only in this state all lifecycle functionality like interceptors is available (see here). Therefore Hibernate issues a SELECT query before the deletion in order to transfer both RootEntity and ChildEntity to the “managed” state.
But what can we do, if we just want to delete RootEntity and ChildEntity, if we know the id of RootEntity? The answer is to use a simple DELETE query like the following one. But due to the integrity constraint on the child table, we first have to delete all depending child entities. The following code demonstrates how:

List childIds = entityManager.createQuery("select c.id from ChildEntity c where c.rootEntity.id = :pid").setParameter("pid", id).getResultList();
for(Long childId : childIds) {
    entityManager.createQuery("delete from ChildEntity c where c.id = :id").setParameter("id", childId).executeUpdate();
}
entityManager.createQuery("delete from RootEntity r where r.id = :id").setParameter("id", id).executeUpdate();

The above code results in the three SQL statements we would have expected by calling remove(). Now you may argue, that this way of deletion is more complicated than just calling the EntityManager’s remove() method. It also ignores annotations like @OneToMany and @ManyToOne we have placed in the two entity classes.
So why not write some code that uses the knowledge about the two entities that already exists in the two class files? First of all, we look for @OneToMany annotations using reflection in the RootEntity class, extract the type of the child entity and then look for its back relation field annotated with @ManyToOne. Having done this, we can easily write the three SQL statements in a more generic way:

public void delete(EntityManager entityManager, Class parentClass, Object parentId) {
    Field idField = getIdField(parentClass);
    if (idField != null) {
        List oneToManyFields = getOneToManyFields(parentClass);
        for (Field field : oneToManyFields) {
            Class childClass = getFirstActualTypeArgument(field);
            if (childClass != null) {
                Field manyToOneField = getManyToOneField(childClass, parentClass);
                Field childClassIdField = getIdField(childClass);
                if (manyToOneField != null && childClassIdField != null) {
                    List childIds = entityManager.createQuery(String.format("select c.%s from %s c where c.%s.%s = :pid", childClassIdField.getName(), childClass.getSimpleName(), manyToOneField.getName(), idField.getName())).setParameter("pid", parentId).getResultList();
                    for (Long childId : childIds) {
                        entityManager.createQuery(String.format("delete from %s c where c.%s = :id", childClass.getSimpleName(), childClassIdField.getName())).setParameter("id", childId).executeUpdate();
                    }
                }
            }
        }
        entityManager.createQuery(String.format("delete from %s e where e.%s = :id", parentClass.getSimpleName(), idField.getName())).setParameter("id", parentId).executeUpdate();
    }
}

The methods getFirstActualTypeArgument(), getManyToOneField(), getIdField() and getOneToManyFields() in the code above are not depicted here, but do what their name sounds like. Once implemented we can easily delete all entities beginning with the root of the tree.

A simple example application that can be used to examine the behavior and solution described above, can be found on github.

Passing SFSBs as an argument to a custom JSF component?

Have you ever developed a custom JSF component that renders an img tag? If so, you will know that this component consists at least of two parts: The first part is the implementation of UIComponent that actually renders the img tag, the second part is the servlet filter or phase listener that answers the asynchronously incoming request for the image URL. Does it work, to use a stateful session bean (SFSB) to load the image data from the database?
First of all we start with the UIComponent. As base class we choose UIOutput, which is sufficient for the current case:

@FacesComponent("EjbComponent")
public class EjbComponent extends UIOutput {
    private static final Logger logger = LoggerFactory.getLogger(EjbComponent.class);
    private static final String COMPONENT_FAMILY = "martins.developer.world.jsf.component.helloWorld";

    private enum PropertyKeys {
        statefulEjb
    };

    @Override
    public String getFamily() {
        return COMPONENT_FAMILY;
    }
    ...
}

We override the encodeBegin() method to render the img tag. We get the stateful session bean, which is passed as an argument to the component, using JSF’s StateHelper:

    @Override
    public void encodeBegin(FacesContext facesContext) throws IOException {
        ResponseWriter writer = facesContext.getResponseWriter();
        String imageSrc = createImageUrl(facesContext);
        writer.startElement("img", this);
        writer.writeAttribute("src", imageSrc, "");
        writer.endElement("img");
        Map<String,Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        sessionMap.put("ejbComponent", getStatefulEjb());
    }

    public StatefulEjbLocal getStatefulEjb() {
        return (StatefulEjbLocal) getStateHelper().eval(PropertyKeys.statefulEjb);
    }

    public void setStatefulEjb(StatefulEjbLocal statefulEjb) {
        getStateHelper().put(PropertyKeys.statefulEjb, statefulEjb);
    }

The createImageUrl() method adds a parameter to the HTTP request, such that we can detect this specific request later on in the PhaseListener:

    private String createImageUrl(FacesContext context) {
        StringBuilder builder = new StringBuilder(context.getExternalContext().getRequestContextPath());
        if (builder.indexOf("?") == -1) {
            builder.append('?');
        } else {
            builder.append('&');
        }
        builder.append("ejbComponent").append("=").append("ejbComponent");
        return builder.toString();
    }

The PhaseListener has the task to detect the incoming request issued by the img tag rendered by the component above:

public class EjbComponentPhaseListener implements PhaseListener {
    private static final Logger logger = LoggerFactory.getLogger(EjbComponentPhaseListener.class);

    @Override
    public void beforePhase(PhaseEvent phaseEvent) {
        FacesContext facesContext = phaseEvent.getFacesContext();
        ExternalContext externalContext = facesContext.getExternalContext();
        String ejbComponentParameter = requestParameter.get("ejbComponent");
        if (ejbComponentParameter != null) {
            Map<String, Object> sessionMap = externalContext.getSessionMap();
            StatefulEjbLocal ejbComponent = (StatefulEjbLocal) sessionMap.get("ejbComponent");
            if (ejbComponent != null) {
                byte[] image = ejbComponent.getImage();
                HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
                ServletOutputStream outputStream = null;
                try {
                    outputStream = response.getOutputStream();
                    IOUtils.copy(new ByteArrayInputStream(image), outputStream);
                    outputStream.flush();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    IOUtils.closeQuietly(outputStream);
                    facesContext.responseComplete();
                }
            } else {
                logger.debug("Could not retrieve ejbComponent from session.");
            }
        } else {
            logger.debug("Request parameter not found");
        }
    }

    @Override
    public void afterPhase(PhaseEvent phaseEvent) {
        logger.debug("afterPhase()");
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

As you see, we try to see if the currently handled request has a parameter with the name “ejbComponent”. If this is the case, we look up the SFSB from the session map, as we have put it in there before (see code for the JSF component). Now that we have a reference to the SFSB, we can use it to load the image data and pass it to the browser.
In our web application we now create a simple backing bean that holds a reference to the SFSB, which later on is passed to the component on the JSF page:

@Named
public class HelloWorldBackingBean {
    @EJB
    private StatefulEjbLocal statefulEjb;
    ...

Finally we pass the SFSB from the backing bean to the component on our JSF page:

<mdw:ejbComponent statefulEjb="#{helloWorldBackingBean.statefulEjb}"/>

If we compile and deploy the application, the JSF will render the image as expected. But there is one caveat: If the same SFSB is used to render more than one image within the same web session, the concurrent access to the SFSB is serialized as the EJB 3.1 specification demands this in section 4.3.14. This means that each invocation locks/blocks the other threads until a timeout occurs. This timeout can be given with the @AccessTimeout annotation, the default in the JBoss AS 7.x container is 5 seconds. If the waiting threads therefore have to wait too long, a ConcurrentAccessException is thrown. This may lead to sporadic failures that only happen, if the system is under load.
Sample code can be found in my github repository.

Setting up your application server with maven

In many cases there is no way to deploy an application without the need to setup your application before. In JBoss AS 7.x you may want to configure for example your database connection. Or you have to configure a security realm. Maybe you also want to adjust the SLSB pool… In any of these cases all developers in the team have to share a common or at least a similar configuration.
Often this information can be found in sporadically sent emails or on some wiki page. But what happens sometime after a release, when you have to check out a branch to fix some bug or to add a new feature? You will have to reconstruct the configuration that was valid for this branch. So why not add the configuration files to your version control system and together with the mere configuration files, a maven configuration that sets up the whole application server?
Let’s try to keep it simple and use only public available and commonly used plugins. First of all let’s add all versions that we will need in the following to the properties part of the pom.xml:

	<properties>
		<jboss.install.dir>${project.build.directory}/jboss</jboss.install.dir>
		<jboss.version>7.2.0.Final</jboss.version>
		<app.version>${project.version}</app.version>
		<ojdbc.version>11.2.0.1.0</ojdbc.version>
	</properties>

We also define here the installation directory of the JBoss AS. This way we can change it, if we want, using the command line option -D. Now we add a new profile, such that we have to explicitly switch the setup procedure on and that it is not part of the normal build:

<profile>
	<id>setupAs</id>
	<build>
		<plugins>
		...
				</plugins
		</build>
</profile>

If we have the current JBoss version as a maven artifact deployed in our maven repository, we can use the maven-dependency-plugin to download and unpack the JBoss to the installation directory given above:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-dependency-plugin</artifactId>
	<version>2.8</version>
	<executions>
		<execution>
			<id>unpack-jboss</id>
			<phase>package</phase>
			<goals>
				<goal>unpack</goal>
			</goals>
			<configuration>
				<artifactItems>
					<artifactItem>
						<groupId>org.jboss</groupId>
						<artifactId>jboss-as</artifactId>
						<version>${jboss.version}</version>
						<type>zip</type>
						<outputDirectory>${project.build.directory}/jboss</outputDirectory>
					</artifactItem>
				</artifactItems>
			</configuration>
		</execution>

Now that the application server is unpacked, we have to add the JDBC driver as well as our application (or anything else you need). We set this up by adding another execution block to the maven dependency plugin:

<execution>
	<id>copy</id>
	<phase>package</phase>
	<goals>
		<goal>copy</goal>
	</goals>
	<configuration>
		<artifactItems>
			<artifactItem>
				<groupId>our-company</groupId>
				<artifactId>our-application-ear</artifactId>
				<version>${app.version}</version>
				<type>ear</type>
				<outputDirectory>${jboss.install.dir}/jboss-as-${jboss.version}/standalone/deployments</outputDirectory>
			</artifactItem>
			<artifactItem>
				<groupId>com.oracle</groupId>
				<artifactId>ojdbc6</artifactId>
				<version>${ojdbc.version}</version>
				<outputDirectory>${jboss.install.dir}/jboss-as-${jboss.version}/standalone/deployments</outputDirectory>
				<destFileName>ojdbc6.jar</destFileName>
			</artifactItem>
		</artifactItems>
	</configuration>
</execution>

Last but not least, we also want to adjust the standard configuration files to our needs. We can use the maven-resources-plugin to substitute variable values within each file. Therefore we add templates for these files to the resources folder of our JBoss module and call the goal copy-resources:

<plugin>
	<artifactId>maven-resources-plugin</artifactId>
	<version>2.6</version>
	<executions>
		<execution>
			<id>copy-jboss-configuration</id>
			<phase>package</phase>
			<goals>
				<goal>copy-resources</goal>
			</goals>
			<configuration>
				<outputDirectory>${jboss.install.dir}/jboss-as-${jboss.version}/standalone/configuration</outputDirectory>
				<resources>
					<resource>
						<directory>src/main/resources/jboss/standalone/configuration</directory>
						<filtering>true</filtering>
					</resource>
				</resources>
			</configuration>
		</execution>
		<execution>
			<id>copy-jboss-bin</id>
			<phase>package</phase>
			<goals>
				<goal>copy-resources</goal>
			</goals>
			<configuration>
				<outputDirectory>${jboss.install.dir}/jboss-as-${jboss.version}/bin</outputDirectory>
				<resources>
					<resource>
						<directory>src/main/resources/jboss/bin</directory>
						<filtering>true</filtering>
					</resource>
				</resources>
			</configuration>
		</execution>
	</executions>
</plugin>

The values for the filtering can be given on the command line with the -D option. If the team has more than a few members, it is also possible to create for each user a properties file that contains his/her specific configuration values. If we use the OS user as filename, we can easily choose the file by the name of the currently logged in user. This way each team member can easily setup its own completely configured application server instance by simply running:

mvn clean install -PsetupAs

In order to prevent that the newly configured server is deleted with the next clean invocation, we disable the maven clean plugin for the normal build:

<plugin>
	<artifactId>maven-clean-plugin</artifactId>
	<version>2.5</version>
	<configuration>
		<skip>false</skip>
	</configuration>
</plugin>

Within the setupAs profile created above, we have to enable it of course, such that we can delete the whole installation just by calling “mvn clean -PsetupAs”. Now switching to an older branch is easy as we don’t lose any time searching for the right configuration…

Developing your own maven plugin to verify the bytecode of your artifact

In this article the goal is to develop your own maven plugin that accesses at build time the artifact of your project and verifies the class files. I used this concept for my library jb5n to verify that for each MessageResource interface an appropriate key/value pair is available in the underlying resource bundle.
The first step is of course to create a new maven module or project using the mojo archetype:

mvn archetype:generate \
  -DgroupId=sample.plugin \
  -DartifactId=hello-maven-plugin \
  -DarchetypeGroupId=org.apache.maven.archetypes \
  -DarchetypeArtifactId=maven-archetype-plugin

This will create a ready-to-run maven project of type maven-plugin for you:

  <groupId>sample.plugin</groupId>
  <artifactId>hello-maven-plugin</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>maven-plugin</packaging>

All necessary dependencies to develop your own maven plugin are already available. The archetype also creates a simple Mojo class:

/**
 * @goal verify
 * @phase verify
 */
public class MyMojo extends AbstractMojo {

    /**
     * @parameter default-value="${project}"
     */
    private MavenProject mavenProject;

The maven goal as well as the default phase of the lifecycle the plugin runs in is given by the javadoc elements @goal and @phase. Newer versions of maven let you define these values with annotations. To access the outcome of the current build process we let our plugin run in the verify phase. We can access the file of our artifact by accessing the member variable mavenProject, which is injected by maven into our plugin with the above definition:

File artifactFile = mavenProject.getArtifact().getFile();

The File object from the above snippet will point to the jar file (in case we have chosen jar packaging for our artifact). Therefore we can open the jar file using Java’s SDK classes JarFile and JarEntry:

JarFile jarFile = new JarFile(artifactFile);
Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()) {
	JarEntry jarEntry = entries.nextElement();
	String jarEntryName = jarEntry.getName();
	if(jarEntryName != null && jarEntryName.endsWith(".class")) {
		getLog().debug(String.format("Processing jar file entry '%s'.", jarEntryName));
		...
	}
}

Now we can use a library like javassist or Java’s reflection API to analyze each class file within the artifact.

Compiler aware access to properties files in Java

The standard way in the Java world to provide internationalization to your application is the usage of properties files. You create a simple text file where you store your key/value pairs. Access to these files is normally done through the JDK class ResourceBundle:

ResourceBundle myResources = ResourceBundle.getBundle("MyResources", currentLocale);
myResources.getString("OkKey");

So far, so good. But what if your project grows? How do you keep track of the link between the Java code, i.e. means all the lines that access a particular key, and the properties files? You have to find a way to cope with this, because otherwise it becomes difficult to answer questions like: “Can I remove this key/value pair from my properties file or is it still referenced by some Java code?”. Or what if you want to rename a key? You’ll have to find all occurrences of this string in the Java code. Hopefully you will find all, otherwise ResourceBundle will throw a MissingResourceException.
A simple concept to overcome this problem is to route all access to your properties files to Java interfaces. Let a proxy implementation of this interface fetch the required key from the properties file. This way your IDE can help you to find all lines in your Java code where a certain property is accessed:

MyMessageResource myMessageResource = JB5n.createInstance(MyMessageResource.class);
String ok = myMessageResource.ok();

The Google Web Toolkit (GWT) has introduced this mechanism as Messages. As I needed this kind of functionality quite often, I have implemented a library that implements this idea. In contrast to other implementations I wanted to be backward compatible, so that you can upgrade an existing application step by step. For this I have added an annotation to the interface methods that lets you define the key to use to access the properties file. Normally the name of the method is used as key.

@Message(key = "no.default.key")
String noDefaultKey();

Beyond that the library should also stay extensible. If your requirements change and your customer wants to be able to change the translations without the need of recompilation, you could easily implement your own InvocationHandler that loads the messages e.g. from a database or some other kind of storage:

@MessageResource(invocationHandler=MyDatabaseMessageResource.class)
private interface MyInvocationHandler {
	String ok();
}

Like Google’s GWT my implementation can of course also handle arguments to the message, using Java’s MessageFormat:

public interface MyMessageResource {
	String youHaveNREtries(int numberOfRetries); // "You have {0} retries."
}

And last but not least the jb5n library also allows you to use inheritance to group the messages/translations and distribute the methods over different interfaces and therewith the messages over different files:

public interface MyMessageResource {
	String ok();
}
public interface MySpecificMessageResource extends MyMessageResource {
	String specificMessage();
}

But the library is not yet finished. A maven plugin as well as an ant task are on my todo list. This way you can check that interface and properties file are in sync during the build process.
The source code can be found on github: https://github.com/siom79/jb5n.

Implementing a custom JSF 2.0 component with maven

Some time ago, I have written my own custom JSF component. But at that point in time, JSF 1.0 was still up to date and the project didn’t use maven as build system. Thus, I always wanted to write a custom JSF2 component with maven. So let’s start:

First of all we setup a maven project with two modules. Here is the pom.xml file of the parent project:

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>martins-developer-world</groupId>
	<artifactId>jsf-component</artifactId>
	<packaging>pom</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>jsf-component Maven Webapp</name>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.2.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>jsf-component</finalName>
	</build>
	<modules>
		<module>jsf-component-webapp</module>
		<module>jsf-component-impl</module>
	</modules>
</project>

As you can see, we have added the JSF dependencies in the top level pom.xml, so that we inherit them in the child modules. As we will use the JBoss Application Server to test our web application, we have to set the scope for the maven dependencies to provided, so that our war file and our component jar won’t deploy them.
The implementation of our component will reside in jsf-component-impl, thus we chose jar as packaging type for this module:

<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>martins-developer-world</groupId>
		<artifactId>jsf-component</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>jsf-component-impl</artifactId>
	<name>jsf-component-impl</name>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
	</dependencies>
</project>

Now let’s implement a Java class that extends UIOutput. I have chosen UIOutput because as a first step I just want to implement a simple helloWorld tag, that prints the first and last name given as attribute within a span element. As this component doesn’t receive any input, UIOutput it appropriate:

package martins.developer.world.jsf.component.impl;

import java.io.IOException;

import javax.faces.application.ResourceDependencies;
import javax.faces.application.ResourceDependency;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

@ResourceDependencies({ @ResourceDependency(name = "css/jsf-component.css", target = "head") })
@FacesComponent("HelloWorld")
public class HelloWorldComponent extends UIOutput {
	private static final String COMPONENT_FAMILY = "martins.developer.world.jsf.component.helloWorld";

	private enum PropertyKeys {
		firstName, lastName
	};

	@Override
	public String getFamily() {
		return COMPONENT_FAMILY;
	}

	@Override
	public void encodeBegin(FacesContext context) throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("span", this);
		writer.writeAttribute("class", "helloWorldClass", "");
		writer.writeText(String.format("Hello %s %s!", getFirstName(), getLastName()), "");
		writer.endElement("span");
	}

	public String getFirstName() {
		return (String) getStateHelper().eval(PropertyKeys.firstName, "???firstName???");
	}

	public void setFirstName(String firstName) {
		getStateHelper().put(PropertyKeys.firstName, firstName);
	}

	public String getLastName() {
		return (String) getStateHelper().eval(PropertyKeys.lastName, "???lastName???");
	}

	public void setLastName(String lastName) {
		getStateHelper().put(PropertyKeys.lastName, lastName);
	}
}

The getFamily() method is the only method that we are enforced to implement. Interesting is here the method encodeBegin(). This is the place where we implement our span tag. As it should have a CSS class attribute, we add it with the writeAttribute() method of the Writer. The two attributes of the resulting JSF tag are modelled as simple properties with getter and setter methods. The implementation of these getters and setters uses the StateHelper available in JSF 2.0. In encodeBegin() we use the getters to retrieve the value given by the user.
Interesting is also the annotation @ResourceDependencies. With this annotation we can tell the JSF framework that we have some files we depend on. In this case it is a CSS file that resides with the folder src/main/resources/META-INF/resources/css.
The annotation @FacesComponent registers this component in the boot process at the JSF framework. The given name is used in the taglib file to reference this class:

<?xml version="1.0"?>
<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee">
	<namespace>https://martinsdeveloperworld.wordpress.com</namespace>
	<tag>
		<tag-name>helloWorld</tag-name>
		<component>
			<component-type>HelloWorld</component-type>
		</component>
	</tag>
</facelet-taglib>

In this taglib file under src/main/resources/META-INF we define the available components, here only our helloWorld tag. The attributes of the tag are derived from the properties of the Java class.
Finally we want to test our newly created component. To be able to do this, we setup a simple JSF2 webapp project and add the following snippet to the web.xml, in order to declare that we want to use our custom component:

	<context-param>
		<param-name>facelets.FACELETS_LIBRARIES</param-name>
		<param-value>/META-INF/jsf-component.taglib.xml</param-value>
	</context-param>

Now we can write a simple JSF page that references our new tag:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:mdw="https://martinsdeveloperworld.wordpress.com">
<h:head>
<title>Hello JSF 2!</title>
</h:head>
<h:body>
	<h2>Hello World!</h2>
	<mdw:helloWorld firstName="Martin" lastName="Developer"/>
</h:body>
</html>

When we deploy this application to the JBoss Application Server and call the corresponding URL, we get the following HTML output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Hello JSF 2!</title>
	<link type="text/css" rel="stylesheet" href="/jsf-component-webapp/faces/javax.faces.resource/css/jsf-component.css" />
</head>
<body>
	<h2>Hello World!</h2>
	<span class="helloWorldClass">Hello Martin Developer!</span>
</body>
</html>

Clearly we can see the span tag with the CSS class and the output. The CSS file is referenced in the head of the HTML document.

The sources of the whole project can be found on GitHub: https://github.com/siom79/jsf-component.

Benchmarking the famous refactoring of GeneratePrimes in Robert C. Martin’s ‘Clean Code’

Inspired by Tomasz Nurkiewicz’ blog post about how aggressive the inlining capability of the Java Virtual Machine is (original blog post), I asked myself what impact the refactorings to the famous GeneratePrimes class in Robert C. Martin’s book ‘Clean Code’ (see page 71) are. Therefore I set up a small benchmark project that can be found here on GitHub: https://github.com/siom79/generate-primes-cleancode-benchmark.

Under src/main/java you will find the two classes as they are published in the book and under src/test/java a unit test that runs the generatePrimes() method of the two classes with different values for the argument maxValue, ranging from 10 to 1.000.000.000. The unit test prints out the measured time in milliseconds like this:

OneMethod : 1083,00 ms for 10
PlentyMethods: 490,17 ms for 10
OneMethod/PlentyMethods: 2,21 (< 1 means OneMethod is faster)
OneMethod : 12,40 ms for 100
PlentyMethods: 19,68 ms for 100
OneMethod/PlentyMethods: 0,63 (< 1 means OneMethod is faster)
OneMethod : 125,75 ms for 1000
PlentyMethods: 179,22 ms for 1000
OneMethod/PlentyMethods: 0,70 (< 1 means OneMethod is faster)
OneMethod : 1386,68 ms for 10000
PlentyMethods: 2069,76 ms for 10000
OneMethod/PlentyMethods: 0,67 (< 1 means OneMethod is faster)
OneMethod : 10096,85 ms for 100000
PlentyMethods: 10365,03 ms for 100000
OneMethod/PlentyMethods: 0,97 (< 1 means OneMethod is faster)
OneMethod : 26232,72 ms for 1000000
PlentyMethods: 8215,29 ms for 1000000
OneMethod/PlentyMethods: 3,19 (< 1 means OneMethod is faster)
OneMethod : 184577,74 ms for 10000000
PlentyMethods: 184149,59 ms for 10000000
OneMethod/PlentyMethods: 1,00 (< 1 means OneMethod is faster)
OneMethod : 2100707,11 ms for 100000000
PlentyMethods: 2103006,56 ms for 100000000
OneMethod/PlentyMethods: 1,00 (< 1 means OneMethod is faster)

The logging statement beginning with OneMethod is the old-styled implementation which computes all prime numbers up to the given maximum value with only one method, whereas the statement beginning with PlentyMethods uses the refactored version using plenty methods for the implementation of the same algorithm. As you will notice, the difference between both implementations converges against 1.00. This means that after some time all private methods of the refactored implementation have been inlined and do not cause any runtime overhead. Until 100.000 the one method implementation is faster, afterwards (interestingly except for the 1.000.000 measurement) the difference in runtime is 1. Surprisingly the first measurement shows up that the plenty method implementation is even faster than the old-styled implementation.

PS: The measurement were taken on the following setup: Intel Core i5, 2.4 GHz, 4GB RAM, 64Bit; Windows 7, Java(TM) SE Runtime Environment (build 1.7.0_21-b11).

Analyzing deadlocks in Java applications with thread dumps

Recently I was given the task to analyze a problem with some multi-threaded Java application that got stuck if you run that application within a batch script again and again. On some invocations the application just did nothing (no CPU utilization, no exceptions). So how to analyze what the application is doing right now?
In cases like this, jstack enables you to create a thread dump for a running java application and gives a look inside. First you have to look up the id of the running application with jps and then provide its PID as the first argument to jstack:

C:\Users>jps
884 org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
2344 Jps
5188 ThreadA

C:\Users>jstack 5188 > stack.txt

As I opened the text file stack.txt, I found something like the following (reconstructed here with a simple example):

"Thread-18":
	at martin.ThreadB.run(ThreadB.java:13)
	- waiting to lock <0x00000000ec102070> (a java.lang.Object)
"Thread-0":
	at martin.ThreadB.run(ThreadB.java:15)
	- waiting to lock <0x00000000ec103b68> (a java.lang.Object)
	- locked <0x00000000ec102070> (a java.lang.Object)
"Thread-15":
	at martin.ThreadA.run(ThreadA.java:15)
	- waiting to lock <0x00000000ec102070> (a java.lang.Object)
	- locked <0x00000000ec103b68> (a java.lang.Object)

As you can see, Thread-18 is waiting to lock 0x00000000ec102070, which is already locked by Thread-0. Thread-0 on the other hand is waiting to lock 0x00000000ec103b68, which again is already locked (by Thread-15). And Thread-15 is also waiting to lock 0x00000000ec102070. Thus, we have a classic deadlock situation.

Using interfaces to subdivide enums into smaller semantic units

Recently I stumbled upon a huge enum with a lot of values. While working with this enum I realized, that in some situations you only needed a few enum values while in other situations you needed other values. This clearly indicated that the enum subsumed values from different semantic fields.
But how can you subdivide such a enum into separate units?
A first thought was to establish some kind of inheritance. But Java does not support inheritance for enums. The reason why is shown in the following example:

 enum First {One, Two}   
 enum Second extends First {Three, Four}   

 First a = Second.Four;   // clearly illegal 

But instead of using inheritance one could create separate enums and define a common interface for them:

interface Os {

}
enum WindowsOs implements Os {
    Windows95,
    Windows98,
    ...
}
enum UnixOs implements Os {
    Linux,
    Solaris,
    ...
}

Now you can write methods, that only accept operating systems of type WindowsOs or UnixOs or any Os:

	private boolean isWindowsOs(Os os) {
		return (os instanceof WindowsOs);
	}

	private void rebootAfterInstallation(WindowsOs windowsOs) {
		System.out.println("Rebooting");
	}

Even if you want to refine the UnixOs enum, you could create one more interface (e.g. UnixOs that extends Os) and create enums like LinuxOs and SolarisOs that implement the new interface:

interface UnixOs extends Os {

}
enum LinuxOs implements UnixOs {
    CentOs,
    RedHat,
    Debian,
    ...
}

JNDI load balancing with jboss-ejb-client on JBoss AS 7

Let’s assume we have a client application that accesses a remote stateful session bean (SFSB) on a JBoss Application Server AS 7. The SFSB is accessed via JNDI lookup as described here: EJB invocations via JNDI. The SFSB is clustered via the @Clustered annotation as described here: Clustered EJBs.

@Stateful
@Clustered
@Remote(TestRemote.class)
public class TestBean implements TestRemote {
...
}

Note that the infinispan cache used to cluster the SFSB is only started, when during the deployment one SFSB with the @Clustered annotation is found. If we want to start two JBoss servers on the same machine, we can do this with the following command line invocations:

standalone.bat -c standalone-ha.xml -Djboss.node.name=nodeA -b 127.0.0.1
standalone.bat -c standalone-ha.xml -Djboss.socket.binding.port-offset=100 -Djboss.node.name=nodeB -b 127.0.0.1

It is important to note, that both servers have to be bind to a specific ip address. If you bind both server with the option “-b 0.0.0.0” the clustering doesn’t start (see here). Both servers also do have to have a different node name.

The client uses the following properties file to access the SFSB via JNDI:

remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
invocation.timeout=10000
remote.connections=default

remote.connection.default.host=127.0.0.1
remote.connection.default.port=4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false

remote.clusters=ejb
remote.cluster.ejb.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.cluster.ejb.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
remote.cluster.ejb.connect.options.org.xnio.Options.SSL_ENABLED=false

Two things are important. First of all we only have to define one of the two servers (here 127.0.0.1:4447). The other server is detected automatically via a topology message that the client receives after he has connected to the first server. It is also important to mention that this topology information is received with some latency, thus if you try to lookup all your SFSBs directly after the first lookup, your client program could be to fast to integrate the information about the second server and therefore all SFSB are executed on the first server. The name of the cluster has also to be defined (here with the property remote.clusters). Then for each defined cluster (here ejb) the SASL_POLICY as well as the SSL configuration is given.

If you now look up the remote bean with the following code, all invocations are load balanced to both server instances:

	private TestRemote lookupRemoteBean() throws NamingException {
		logger.info("Using jboss-ejb-client.");
		final Hashtable<String, String> jndiProperties = new Hashtable<String, String>();
		jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
		final Context context = new InitialContext(jndiProperties);
		final String appName = "jboss-ejb-client";
		final String moduleName = "server-ejb";
		final String distinctName = "";
		final String beanName = TestBean.class.getSimpleName();
		final String viewClassName = TestRemote.class.getName();
		String lookupString = "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!"
				+ viewClassName + "?stateful";
		logger.debug(String.format("Looking up: %s", lookupString));
		return (TestRemote) context.lookup(lookupString);
	}

The appName and moduleName are chosen as described here.

There is also one more caveat: You can set a selector for the EJB client context to use programmatically:

final EJBClientConfiguration ejbClientConfiguration = new PropertiesBasedEJBClientConfiguration(
				clientConfigProps);
final ContextSelector<EJBClientContext> ejbClientContextSelector = new ConfigBasedEJBClientContextSelector(
				ejbClientConfiguration);
EJBClientContext.setSelector(ejbClientContextSelector);

Here the properties object clientConfigProps is created dynamically during runtime and contains in our example the same information as the properties file from above. If you set this selector directly before each lookup, the topology information is requested again and arrives too late, due to the latency mentioned before. Therefore again all clients are executed on the first server.

Design a site like this with WordPress.com
Get started