Tag Archives: java

How to unit test EJB3 without a container

Unit test EJB3 without a container has become much easier since the EJB 3.1 spec with the introduction of the embeddable EJBContainer concept. An embeddable EJBContainer is a container for enterprise beans that does not require a Java EE server to run.

Interesting usage scenarios are:

  • EJB unit testing: you don’t need to install a JavaEE server for EJB development, unit testing and deployment to the container
  • Lightweight: the embeddable container has a much smaller footprint
  • Fast: starts faster than the full server, because it only initializes EJB-related components

Sample code

Below you can find a simple setup method for a JUnit test that configures the Embeddable EJBContainer.

@Before
public void setup() {
	Properties properties = new Properties();
	properties.setProperty(EJBContainer.MODULES, "myModule");
	properties.put(EJBContainer.PROVIDER, "tomee-embedded");
	Context context = EJBContainer.createEJBContainer().getContext();
}

@After
public void tearDown() throws NamingException {
	ejbContainer.close();
}

Here myModule is the module-name defined in ejb-jar.xml file

So how does the EJBContainer start an embedded EJB container? You’ll need to provide an embedded EJB container on the classpath. Normally all Application servers supporting JavaEE6 have to provide such an embedded EJB container.

Apache TomEE container This example uses Apache TomEE as it provides an easy way to specify the correct dependencies via Maven.

<dependency>
	<groupId>org.apache.openejb</groupId>
	<artifactId>tomee-embedded</artifactId>
	<version>1.5.2</version>
</dependency>            
<dependency>
	<groupId>javax</groupId>
	<artifactId>javaee-api</artifactId>
	<version>6.0</version>
	<scope>provided</scope>
</dependency>

The properties.put(EJBContainer.PROVIDER, “tomee-embedded”) makes sure that we will use Apache TomEE when running the test. (even if there is another provider on the classpath)

How to solve CoreMessageLogger NoClassDefFoundError in Weblogic

When deploying an application in Weblogic you can come across a Hibernate CoreMessageLogger NoClassDefFoundError on Weblogic:

Hibernate Logo

Caused By: java.lang.NoClassDefFoundError: org/hibernate/internal/CoreMessageLogger
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at weblogic.utils.classloaders.GenericClassLoader.defineClass(GenericClassLoader.java:342)
at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:301)
at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:269)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:178)
at org.hibernate.ejb.Ejb3Configuration.(Ejb3Configuration.java:142)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:72)
at weblogic.persistence.BasePersistenceUnitInfo.initializeEntityManagerFactory(BasePersistenceUnitInfo.java:446)
at weblogic.persistence.BasePersistenceUnitInfo.initializeEntityManagerFactory(BasePersistenceUnitInfo.java:439)
at weblogic.persistence.BasePersistenceUnitInfo.init(BasePersistenceUnitInfo.java:117)
at weblogic.persistence.BaseJPAIntegrationProvider.createPersistenceUnitInfo(BaseJPAIntegrationProvider.java:53)
at weblogic.persistence.AbstractPersistenceUnitRegistry.storeDescriptors(AbstractPersistenceUnitRegistry.java:404)
at weblogic.persistence.EarPersistenceUnitRegistry.initialize(EarPersistenceUnitRegistry.java:72)
at weblogic.persistence.PersistenceDeployment$PersistenceDeploymentExtension.prepare(PersistenceDeployment.java:81)
at weblogic.application.internal.flow.AppDeploymentExtensionFlow.prepare(AppDeploymentExtensionFlow.java:23)
at weblogic.application.internal.BaseDeployment$1.next(BaseDeployment.java:706)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:237)
at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:61)
at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:158)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.createAndPrepareContainer(ActivateOperation.java:207)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:96)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:229)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:747)
at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1216)
at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:250)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:171)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:13)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:46)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:545)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)

Solving CoreMessageLogger NoClassDefFoundError

This problem can occur when you have a Hibernate 3.x and a Hibernate 4.x dependency in your classpath, and the Hibernate 3 dependency was first on your classpath.

Look in your Maven Dependency hierarchy to see where the Hibernate 3 / 4 dependencies come from and solve it by eg. excluding transitive dependencies in your POM.

Devoxx 08: HTML 5 WebSockets and Server Sent Events

A few weeks back on Devoxx 08, Jonas Jacobi and John R. Fallows did a talk about 2 future web technologies  that’ll change the way we architect our webapplications.
(in the same manner then AJAX did a few years back).

The technologies are called WebSockets and Server Sent events and are part of the HTML5 specification. (which is now in Editor’s draft and thus not finished)

WebSockets and Server Sent events can enable us to create a full-duplex web application. Eg. a sample application could be a poker game with thousands of viewers connected and that those viewers need to be notified in realtime. Another example could be a continuously updated stock ticker.

Prior to the introduction of WebSockets, bi-directional browser communication was an elusive beast, commonly known as Comet or ReverseAjax and typically achieved with an astonishing assortment of browser hacks. But, with the emerging standards outlined in the HTML 5 specification, developers can now take advantage of a full-duplex communications channel that operates over a single socket.

Real time web

With real time web, we mean that web clients can receive server updates (server initiated communication) and end users receive those updates concurrently.

Long polling with AJAX (XML Http Request) gives us near real time updates, but they are requested from the client and cause increased network traffic. Also these short AJAX requests generally have a small payload and relatively high amount of http headers. (wasted bandwith)

Comet technologies support HTTP Streaming, this setups a persistent http connection which only has to be setup/teardown only once. (especially nice for performance for https traffic)

HTML 5 Overview

HTML 5 not only contains WebSockets and Server Sent events.  It also contains standard features like:

  • communication (sockets, cross-site)
  • graphics (2D)
  • drag n drop
  • storage (transient, (offline)    persistent)
  • compatibility

Here we focus on two: Server-sent events and WebSockets

Server-sent events

Server-sent events standardizes how we stream data from the server to the client (in fact standardizing comet/reverse ajax).

It introduces a new DOM Element: eventsource. The eventsource element provides a simple interface for allowing servers to dispatch DOM events into documents that expect it.

Here is how to create it:

var es = document.createElement(“eventsource”);
es.addEventSource(“http://www.javablog.be”);

(where the event source is an URL).

WebSockets

WebSockets provide a full duplex TCP connection to communicate between the browser and the server. It traverses firewalls and routers and allows authorized cross domain communication.

An example is provided below:

var myWebSocket = new WebSocket(“ws://www.websocket.org”);

The WebSocket(url) constructor takes one argument, url, which specifies the URL to which to connect. When a WebSocket object is created, the User Agent must parse this argument and verify that the URL parses without failure and has a <scheme> component whose value is either “ws” or “wss”. Only then the user agent must asynchronously establish a Web Socket connection to url.

myWebSocket.postMessage(“Hello”);

=> text based data transmission using the connection.

myWebSocket.onopen = function(evt) { }

=> The open  event is fired when the Web Socket connection is established.

myWebSocket.onmessage = function(evt) { }

=> The message event is fired when when data is received for a connection.

myWebSocket.onclose = function(evt) { }

=> The close event is fired when the connection is closed

myWebSocket.disconnect();

=> close the conncetion

Browser support

Opera already has Server sent events, for Mozilla/Firefox there is patch available (bug 338583)
WebSockets is not yet available natively in browsers.

But fortunately for current browsers Kaazing.com provides an emulation Javascript library. (IE5.5+, Firefox 1.5, Chrome 0.2+, Safari 3.1+, Opera9+)
The Javascript only emulates the parts which are not yet implemented in a certain browser.
It can be any of the following layers: ByteSocket, Websockets, Server sent events, Cross site XML HTTP Request, XML Http Request IFrame postMessage

Devoxx 08: Major Servlet 3.0 features

Martin Marinschek divided his talk in two main topics: Servlet 3.0 and JSF 2.0.

The first part of the talk showed us the new features planned for Servlet 3.0.

What follows is based on the Public Review draft.
So be sure to check if the following still applies to the final Servlet 3.0 version.

Modularization of the web.xml settings

Right now the web.xml is one big configuration file. In Servlet 3.0 it’s possible to modularize it into multiple files.
These files are called “web-fragment.xml” files and they are merged together on application initialization.
Because these fragments can conflict with each other, the specification has specified rules for conflict resolution. (we could take a deeper look at this in a future blog post).

Martin also said that fragment ordering is not defined; this eg. could mean that a filter you want to be executed first may have to be repeated in multiple fragments.

Annotation support in your servlets

A few annotations were added that you can use in your servlets:

@WebServlet

This annotation is used to define a Servlet component in a web application. The urlPatterns or the value attribute on the annotation MUST be present. (value is for 1 URL mapping, urlPatterns for multiple URL mappings)
Classes annotated with @WebServlet class MUST extend javax.servlet.http.HttpServlet class except when applied on a JAX-RS / JAX-WS endpoint.

Example:

@WebServlet(name=”MyServlet”, urlPatterns={“/foo”, “/bar”})
public class SampleUsingAnnotationAttributes extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) {
}
}

Other optional attributes for the @WebServlet annotation are: supportAsync and asyncTimeout

@ServletFilter

This annotation is used to define a Filter in a web application. Classes annotated with @ServletFilter MUST implement javax.servlet.Filter

@InitParam

This annotation is used to specify Init Parameters for a servlet or a filter

@WebServletContextListener

The WebServletContextListener annotation is used to annotate a context listener to get events for various operations on the particular web application context.
Classes annotated with @WebServletContextListener MUST implement javax.servlet.ServletContextListener

Asynchronous requests

Sometimes a filter and/or servlet is unable to complete the processing of a request without waiting for a resource or event before generating a response. For example, a servlet may need to wait for an available JDBC connection, for a response from a remote web service, for a JMS message, or for an application event, before
proceeding to generate a response. Waiting within the servlet is an inefficient operation as it is a blocking operation that consumes a thread and other limited resources. Frequently a slow resource such as a database may have many threads blocked waiting for access and can cause thread starvation and poor quality of service  for an entire web container.

Servlet 3.0 introduces the ability for asynchronous processing of requests so that the thread may return to the container and perform other tasks.

When asyncSupported is set to true in the filter/servlets annotation the application can start asynchronous
processing in a separate thread by calling the HttpServletRequest.startAsync method passing it a
reference to the request and response objects.

After I’ve played with the asynchronous requests I’ll post some code samples to Java Blog to explain how exactly it works.

Devoxx 08: what’s new in Java 7?

In the thursday keynote at Devoxx, Mark Reinhold (from Sun) presented the new features slated for the Java 7 release. (the expected release date of Java 7 is early 2010)

One of the most important new features will be the modularization of Java SE7. Modularization is needed because both Java and the JDK have become quite big. This for example gives issues when trying to run it on smaller (mobile) devices. Cutting the JDK into modules will avoid loading unnecessary classes, which on their turn result in shorter start-up times for applications. To print a simple string “Hello world”, Java needs over 300 classes in the current version!.

A list of the other new features can be found here!

Devoxx 2008: my session picks for University day 1

I’ll be again present on Europe’s largest Java conference Javapolis Devoxx.

Here is a list of what sessions I’ll be following.

If you want to meet me let me know via my Twitter.

Scrum in Practice

The agile Scrum process will be explained: its roles, its artefacts and the challenges in implementing it in an organization.

Servlet 3.0 & JSF 2.0

I’m especially interested in the new features in JSF2.0 and the modularization support for web applications in Servlets 3.0

JFreeChart

Having used JFreeChart v0.9.x a few years ago, I’m looking forward to seeing the enhancements/new features in the current version.

Agile Testing of Java Rich Clients

Traditionally a difficult area to automate tests for, I’m wondering how Fit, FEST and TestNG will fare.

Bringing Designers and Developers Together with JavaFX and Project Nile

As a Flex developer, I’m wondering how JavaFX and Flex compare to each other.

Weblets 1.1 now officially released

Weblets 1.1 has been released at weblets.dev.java.net

Weblets is a Java servlet based framework that provides an easy way of loading resources (Javascript, CSS, images, …) directly out of JAR files. For an overview of what Weblets can do for you, check our Weblets overview.

Below we’ll highlight some of the new features in Weblets v1.1:

  • Weblets 1.1 provides a stable api to build your own Weblets upon
  • Asynchronous In-server reporting of url usage is possible. (eg. for traffic analysis). In-server means that the logging is done in the same JVM server process. Asynchronous because reports that are triggered and executed can run for a longer period of time.
  • General reporting API for in server reporting instances
  • Configurable cache timeouts for better browser cache control

Weblets 1.0 only had the possibility to host resources within your classpath. It was only possible to host Weblets related resources within a jar or within your WEB-INF/classes directory!

Weblets 1.1 now enhances this with a very common usecase. expanded application hosted resources . This means you can put any resource hosted within your local web application under Weblet control. For instance if your application is hosted under /myapplication and your resource under /myapplication/images/myimage.png it until now was not possible to put this resource under Weblets control.

  • Server Mime Type overrides: some servers don’t set default mime types. (eg Weblogic 8.1). If you’re not able to edit them in the web.xml, the Weblets configuration provides another possibility.
  • Resource Whitelists: a mechanism to allow the serving of resources only for certain filetypes given in a resource whitelist (eg. only allow serving of png files)
  • Weblets 1.1 corrects Maven2.0 transitive dependencies (Maven should now pickup all needed dependencies of Weblets)

See http://weblets.dev.java.net/doc_11/longdoc/whatsnew.html for a more detailed description of the new features!

JSF 1.1 performance fixes

JSF 1.1_02 is the latest officially released reference implementation of JSF1.1 by Sun. It’s still widely used by companies who have not yet migrated to Java5 (as it is not always easy to migrate all applications to a new target platform).

While looking through the FishEye source code view, I came accross some interesting unreleased performance fixes:

https://javaserverfaces.dev.java.net/issues/show_bug.cgi?id=125

I have been investigating the size of views as they are stuffed in the session for scalability reasons, and have found a couple of issues with the RI code:

1. The biggest problem I found was in StateManagerImpl.The function removeTransientChildrenAndFacets causes the lazy init of the child list, facet map, and client id of every component in the tree! Very, very sloppy.

Fixing this literally halved the size of the view in memory.

https://javaserverfaces.dev.java.net/issues/show_bug.cgi?id=223

StateManager for stateSaving Server has a synchronization lock on (this), blocking all threads. I thought this was fixed a while back.

https://javaserverfaces.dev.java.net/issues/show_bug.cgi?id=222

Currently the checkIdUniqueness forces creation of child and facet arrays onevery component, the suggestion is to switch over togetFacetsAndChildren() which is now optimized within UIComponentBase to avoid unecessary eden creation in memory.

Has anybody already used these JSF 1.1_03 rolling fixes and noticed memory reduction? If so please let us know in the comments!

Fix your Richfaces AJAX (performance) problems

Richfaces supports AJAX functionality in a lot of it components. However a servlet filter is needed for correct functioning of partial page refreshes.

In this post we’ll show you how to add this filter and at the same time optimize Richfaces performance.

The following Richfaces filter is defined in the web.xml:

<filter>
        <filter-name>richfaces</filter-name>
        <display-name>RichFaces Filter</display-name>
        <filter-class>org.ajax4jsf.Filter</filter-class>
        <init-param>
			<param-name>forceparser</param-name>
			<param-value>false</param-value>
		</init-param>
    </filter>

What this filter does, is to ‘tidy’ all HTML HTTP Responses so that they are valid XHTML (thus XML compliant). This is needed as dynamic DOM updates in the browser need correct XML.

If you don’t define this filter, it is possible that you’ll not see your AJAX update being rendered on the screen, although you’ll see the html response coming back in eg. Firebug

Of course, parsing HTML incurs a performance overhead.
This can be minimized by setting the forceparser setting to false. In that case only AJAX responses will be ‘tidied’. In the other case all JSF responses are ‘tidied’. That is because the filter is mapped on the Faces servlet:

<filter-mapping>
        <filter-name>richfaces</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>

Richfaces has a few parsers onboard. The default one is based on Tidy, but it is quite slow. The Neko parser is faster and can be used by setting the following context-param’s:
<context-param>
        <param-name>org.ajax4jsf.xmlparser.ORDER</param-name>
        <param-value>NEKO</param-value>
    </context-param>

    <context-param>
        <param-name>org.ajax4jsf.xmlparser.NEKO</param-name>
        <param-value>.*\..*</param-value>
    </context-param>

Here we say we only use the NEKO filter and it should be applied to all URLs (.)
There is more configuration possible, like using NONE for some pages that don’t need HTML correction to further speedup things if needed.

Example can be found at: http://jboss.com/index.html?module=bb&op=viewtopic&t=116231

How to redirect to an external link with Spring Webflow?

Below you can find an easy way to redirect to an external site via a Spring Webflow view state. What happens here is the following:

  1. a JSF command link backing bean action method returns the String link1
  2. Spring Webflow will redirect you to the viewstate OpenLink1
  3. The OpenLink1 view-state uses the externalRedirect functionality with a backingbean/dataholder stored link value

<view-state id=”myViewState” view=”/viewstates/mypage.jspx”>
<transition to=”OpenLink1″ on=”link1″/>
</view-state>

<view-state id=”OpenLink1″ view=”externalRedirect:${conversationScope.dataHolder.link1}”/>