Java Articles

Accessing EJBs from Java SE Using WebSphere’s Embeddable EJB Container

Introduction

In this blog, we’ll explore how to employ the Embeddable EJB Container inside a Java SE application using WebSphere Application Server 8.x.

Embeddable EJB Container

One of the new features introduced in EJB 3.1 (part of Java EE 6) is the Embeddable EJB Container. The main two use cases for the Embeddable EJB Container are:

  1. Unit testing your EJBs without requiring a Java EE application server
  2. Embedding EJBs inside a Java SE application, which allows you to take advantage of their benefits (e.g., security and transactions)

The primary advantages of using the Embeddable EJB Container are:

  • You don’t need to install the application server if all you need to do is unit test or employ your EJBs within a Java SE-based application. You just need access to the vendor’s Embeddable EJB Container JAR file.
  • The Embeddable EJB Container starts almost instantaneously, unlike the server-based EJB container (which can take a minute or more to start up), since the Embeddable EJB Container initializes only EJB-related components.
  • The Embeddable EJB Container has a much smaller memory footprint than the equivalent server-based EJB container.

Read the rest of this entry »

1 Comment

How about a FREE set of WebSphere and Spring Eclipse Development Tools?

Lately I’ve been working quite a bit on expanding the classes available in our Spring 3.0 category.  One of the things that has always set our Spring training apart is that we offer options to develop Spring applications for WebSphere (in addition to other classes that use JBoss or Tomcat).  Spring has been a very popular framework and WebSphere a very popular server so it has always been a popular choice for our clients.

In the past, the downside has always been that WebSphere development required Rational Application Developer (RAD).  Doing Spring development in RAD was never a great fit since you couldn’t use the Spring Eclipse plug-ins that were available from SpringSource.  You also had some choices from MyEclipse for WebSphere and Spring tools but those weren’t free.  Now recently, IBM released FREE Eclipse tools so you can control and deploy to a WebSphere server directly from Eclipse, something that used to require RAD.  I’ve blogged about that before but that was without Spring tools.

So while developing our Spring 3.0 classes for WebSphere I wanted to take a fresh look at what would be the best environment for this.  The contenders would be:

  1. RAD without installing Spring tools
  2. MyEclipse Bling (WebSphere “Blue” tools and Spring)
  3. RAD with Spring tools added
  4. Eclipse with WebSphere and Spring tools installed

Read the rest to see the “Winner” and how to set it up!

Read the rest of this entry »

No Comments

WebSphere 9 Coming Soon?

UPDATE:  As it turns out my guess that there would be an “intermediate” release was correct.  WebSphere 8.5.5 was released recently which mostly has updates for the Liberty profile being a certified implementation of the Java EE 6 Web profile.  The Redbooks updates was obviously for this 8.5.5 version.  The other points are still true though and I would be surprised if there is not an announcement of WebSphere 9.0 at or before the Impact 2014 conference next spring.

ORIGINAL POST: I know for those of you out there using WebSphere, the initial reaction to the title of this blog post is probably “But we haven’t even finished migrating to WebSphere 8.0/8.5!”  I myself didn’t think a new WebSphere version could be waiting in the wings but there have been a few interesting data points to consider:

– Java EE 7 should be final by end of May this year (http://java.net/projects/javaee-spec/pages/Home).

– Many Java EE 7 JSRs are already in final review (http://jcp.org/en/jsr/stage?listBy=proposed).

– IBM Developerworks has betas of 9.0 versions of development tools (https://www.ibm.com/developerworks/mydeveloperworks/blogs/wasdev/entry/download?lang=en)

– IBM Redbooks had a residency open to update several core WebSphere Redbooks to “the latest release of WebSphere Application Server”.  This was only open to IBM employees since people who work on the Redbook would obviously get a “sneak peek” at the next WebSphere.

Although thinking about when WebSphere 9 might be released is interesting, I think there is another possibility, that there will be some “intermediate” release that includes updates mainly to the Liberty profile, the lightweight server that IBM is trying to tailor to developers.  Perhaps there will be something like an 8.5.5 release mainly to pick up updates to the Liberty profile.

Read the rest of this entry »

2 Comments

Getting ‘Closure’

I have been a Java developer since 1995, before that I worked in C++. So my language background is primarily statically-typed and object oriented. In the last several years, I’ve been involved in a number of projects that use JavaScript. I’ve come to recognize that JavaScript is a very powerful language in its own right — but it is dramatically different from the languages that I am used to. One of the features of JavaScript that was a mystery to me is closure.

Closure has no direct equivalent in my native language Java so it took a great deal of reading and experimentation for me to come to grips with this concept. The simplest description I can give is this.

In a closure a variable declared in an outer function is visible to an inner function even if the inner function’s lifecycle is longer than that of the outer function.

Here is an example using the Apache Cordova (PhoneGap) API. The phone Cordova API allows you to package HTML5/CSS/JavaScript applications natively for a number of mobile platforms. It also provides a JavaScript API to wrap many of the native device features like the accelerometer. This example shows a closure.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function startWatch() {

  var previousReading = { x: null, y: null, z: null };

  navigator.accelerometer.watchAcceleration(

    function (acceleration) {
      // use previousReading value here
    },
    onError,
    { frequency: 500 }
 );

}

In this example the startWatch() function declares a variable previousReading and sets its x, y and z members to null. The three values will be used to represent acceleration in meters per second squared. The function then calls navigator.accelerometer.watchAcceleration(), passing in an anonymous callback for success. The anonymous callback defined on line 7 in the source code will be called at a rate of once every 500ms and it will compare the current acceleration with previousReading then update previousReading with the current acceleration.

The code is relatively straightforward except for one important detail previousReading was declared in the scope of the outer function startWatch. But the anonymous inner function (on line 7) will be called repeatedly even after the outer function is out of scope! What happens here is that the inner function keeps a reference to any values in the outer scope that it will need when it is invoked.

For those of you who are Java programmers, don’t think you are immune from this discussion. Closures are on the proposed feature list for JDK 8.

1 Comment

The Performance Evil that is JSF dataTable

In JSF 1.x, dataTable was bizarrely inadequate and unnecessarily complicated. Things have become much easier in JSF 2.0 and it’s a pleasure to work with. But, don’t let that lull you into a false sense of security. There are major performance issues larking behind.

Let’s say that you have a managed bean that returns a list of products from the database by using the ProductDAO class.

@ManagedBean
public class Controller {
    private Product item = new Product();

    public List<Product> getProducts() {
        return ProductDAO.getProducts();
    }

    public String edit(Product toEdit) {
        this.item = toEdit;

        return "edit_product";
    }

    //getItem/setItem...
}

Now, we can build a view that shows the product list.

<h:dataTable id="products" value="#{controller.products}" var="current">
    <h:column>
        <f:facet name="header">Product Name</f:facet>
         #{current.name}
        <h:commandButton value="Edit" action="#{controller.edit(current)}" />
    </h:column>
</h:dataTable>

When the view is rendered, it will look something like this.

image

Now, let’s reveal the performance horror that the dataTable is. During the rendering phase, getProducts() is called repeatedly, once for each item in the list. That means, you are loading the entire list repeatedly from the database. This seems prodigiously wasteful. I don’t see why JSF couldn’t get the list once and simply iterate through it to render the table.

Next, when you click the Edit button, things get even worse. The getProducts() method is called 2xN number of times where N is the number of items in the list. To render the edit form, all you really need from the database is the item that is being edited. Under this circumstances, dataTable is doing a terrible job.

OK, so, what can we do about this. First, you need to cache the list in a member variable and access the database only if we haven’t already done so.

@ManagedBean
public class Controller {
    private Product item = new Product();
    private List<Product> productList = null;

    public List<Product> getProducts() {
        if (productList == null) {
            productList = ProductDAO.getProducts();
        }
        return productList;
    }

    public String edit(Product toEdit) {
        this.item = toEdit;

        return "edit_product";
    }

    //getItem/setItem...
}

This will cure most of the ills. But, there is still the issue of unnecessarily loading the entire list just to render the edit form. The solution for that is to use a GET request. Get rid of the edit() method and instead add the loadProduct() method that will load the product being edited.

@ManagedBean
public class Controller {
    private Product item = new Product();
    private List<Product> productList = null;

    public List<Product> getProducts() {
        if (productList == null) {
            productList = ProductDAO.getProducts();
        }
        return productList;
    }

    public void loadProduct() {
        int productId = item.getId();
        item = ProductDAO.getProductById(productId);
    }

    //getItem/setItem...
}

In the edit form page, say, edit_product.xhtml, setup GET request by adding this metadata.

<f:metadata>
    <f:viewParam name="productId" value="#{controller.item.id}"/>
    <f:event listener="#{controller.loadProduct}" type="preRenderView"/>
</f:metadata>

Finally, change the dataTable to use <h:link> instead of a <h:commandButton>.

<h:dataTable id="products" value="#{controller.products}" var="current">
	<h:column>
		<f:facet name="header">Name</f:facet>
		#{current.name}
		<h:link outcome="edit_product" value="Edit">
			<f:param name="productId" value="#{current.id}"/>
		</h:link>
	</h:column>
</h:dataTable>

That should do it. If you are still hatin’ dataTable, then go with <ui:repeat>.

1 Comment

First Java EE 6 Web Service Class Released

We have just released our first web service class as part of our Java EE 6 courses:

WA2087 Programming Java SOAP and REST Web Services – WebSphere 8.0 / RAD 8.0

Java EE 6 contains two ways to write web services, JAX-WS for “classic” SOAP web services and JAX-RS for REST web services.  This class covers how to implement both styles.  The course also covers securing both types of services and compares the two styles so you can decide which might be appropriate for different situations.

I think this course will be especially useful for people that support JAX-RPC web services from J2EE 1.4 but need to look to what are the more recent Java standards for web services.  Java EE 6 put JAX-RPC on the “proposed optional” list of technologies which means in the future Java EE servers may not be required to support JAX-RPC.  Although I expect WebSphere will still support it now is a good time to start looking for how to migrate JAX-RPC web services to more recent standards like JAX-WS and JAX-RS.

This course is part of our WebSphere Application Server 8.0 Programming course map.  We have other courses that cover just JAX-RS or just JAX-WS as well as a course that covers REST services with JAX-RS and the AJAX clients that are most common for REST services.

If you have any questions about these courses feel free to contact us.

No Comments

Eclipse Juno is Here!

What does the end of June and Java development have in common?  Looking forward to the yearly coordinated release of all the latest Eclipse updates.  This year the release is code named “Juno”.  The release in June 2011 was “Indigo”. 

This year marks the 7th time that the “Simultaneous Release” approach has been used that lets a new version of the underlying platform and all of the projects that build on top of it release.  This has helped to greatly improve the compatibility between projects and the stability of the Eclipse platform as a whole.  It also helps the numerous commercial products that are based on Eclipse count on a consistent schedule and release updates quickly based on the new updates.  This year there were about 70 Eclipse projects part of the Juno release which expands on the 62 that were part of Indigo last year.

If you want to get started the first place to go is probably the usual Eclipse downloads page.  This has been updated for links to the Juno versions of several different “pre-configured” combinations of Eclipse tools besides just the “basics” of the core platform.  One of the most popular downloads is the “Eclipse for Java EE Developers”.

Now I will be the first to admit that like most of you, I can’t spend too much time looking at the new features that are coming out before they are released. So this post is more of a “news” post and future posts will dive into some of the details about what is new. Probably one of the best places to start for this kind of info are some of the “New and Noteworthy” pages like the one for the Java EE tools and the one for the core platform itself and the Java tools.

Probably one of the biggest changes is that the “default” version for the Eclipse SDK, which is the core of the platform is Eclipse 4.2.  The Eclipse 4.x platform has been in the works for over a year but this is the first release where it is the “default”.  All of the previous simultaneous releases were using the Eclipse 3.x platform so this has definitely been a measured process that Eclipse has gone through.  It appears the “regular” Eclipse user won’t notice this much though compared to Indigo except for an updated UI style.  For anyone developing Eclipse plug-ins or perhaps RCP (Rich Client Platform) applications using Eclipse there are more changes, although it is said that Eclipse plug-ins developed for previous Eclipse versions will have “binary compatibility” with the new version so hopefully this would be a smooth process.  Certainly anyone in these categories will want to check out the Eclipse 4.x SDK page for more details.

BTW, if you want to set your calendars now, the next major release will be June 26th, 2013.  This will be codenamed “Kepler” in keeping with the astronomical theme which has also recently started picking names that are alphabetical.

No Comments

New Course on Changes in Java EE 6 and WebSphere 8.0 Posted

I’ve posted a new course which covers some of the changes in Java EE 6 and WebSphere 8.0.  WA2084 What’s New in WebSphere 8.0 and Java EE 6 will be a one day lecture-only class covering the following:

  • Changes in Java EE 6
  • Changes in JSF 2.0
  • Overview of Contexts and Dependency Injection (CDI)
  • What’s New in WebSphere Application Server 8.0
  • WebSphere installation with Installation Manager
  • WebSphere 8.0 HPEL logging

The idea is to cover an overview of all of the changes introduced in Java EE 6 and WebSphere 8.0 followed by more detail on some of the major areas of change.

I think this class will be a good overview for clients to quickly know what changes exist and how they may impact their own projects and WebSphere environments.  This class might be great to take early in the migration process with perhaps more detailed training, like our WebSphere Application Server 8.0 Administration and WebSphere Application Server 8.0 Programming courses to come later.

If you have any question about this or any other training class please contact us and we would be happy to help!

No Comments

Using jQuery With JSF 2.0

Today, I had to finally use both technologies in the same project. You need to do a few things for jQuery to work with JSF 2.0.

  1. Assign ID for all relevant UI components and their parents. Only then can you be sure about the DOM element ID of the component you are trying to manipulate.
  2. Escape the ":" character in the ID.

Let’s learn these two principles using an example. Let’s say, that we have a text box in a form. Make sure both have an ID.

<h:form id="form">
    <h:inputText size="20" value="#{ctrl.dateAsString}" id="dateOfExpense"/>
</h:form>

This means, the text box will have an ID of form:dateOfExpense. If your form has a complicated hierarchy, you can always look at the ID by viewing the source of the page rendered by JSF.

Unfortunately, the ":" character causes havoc in jQuery API. We need to protect it using two back slashes. So, to refer to the text box, we should use the selector "#form\\:dateOfExpense". For example, to convert the text box to a jQuery UI date picker, we will do this.

<h:head>
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<script type="text/javascript" src="scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.21.custom.min.js"></script>

<script type="text/javascript">
$(function(){
    $("#form\\:dateOfExpense").datepicker();
});
</script>
</h:head>

2 Comments

Understanding JSF View Parameters

JSF 2.0 adds support for view parameters. This, essentially adds some support for GET request making it possible to bookmark some of the pages. This feature was sorely lacking in JSF 1.x and is much welcomed by the development community. However, I was surprised by the lack of any good tutorial showing any real life use of the feature.

Primary use of a bookmarkable dynamic page is to lookup some data. The identifier of the data is provided in the URL parameters. For example:

  • /TrackOrderStatus?orderId=1029
  • /FindCustomer?id=1928

This wasn’t possible in JSF 1.x. For developers who already know JSF 1.x, view parameters are best learned by migrating an existing application.

Let’s say that we have a simple customer lookup application. We will first build it the old way that uses POST request.

The Customer class is as follows.

public class Customer {
	String id;
	String name;
	
	public Customer(String id, String name) {
		this.id = id;
		this.name = name;
	}
	
	public Customer() {
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

The CustomerDAO class looks like this with a dummy in-memory database.

public class CustomerDAO {
	static HashMap<String, Customer> data;
	
	static {
		data = new HashMap<String, Customer>();
		
		data.put("E001", new Customer("E001", "Bugs Bunny"));
		data.put("E002", new Customer("E002", "Daffy Duck"));
		data.put("E003", new Customer("E003", "Samity Sam"));
	}
	
	public Customer findCustomer(String id) {
		return data.get(id);
	}
}

Finally, the JSF managed bean looks like this.

@ManagedBean
@RequestScoped
public class MainController {
	String lookupId;
	Customer customer = new Customer();
	
	public String getLookupId() {
		return lookupId;
	}
	public void setLookupId(String lookupId) {
		this.lookupId = lookupId;
	}
	public Customer getCustomer() {
		return customer;
	}
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}
	public String doLookup() {
		CustomerDAO dao = new CustomerDAO();
		
		customer = dao.findCustomer(lookupId);
		
		return "result";
	}
}

Now, we can get to the page design. The index.xhtml page has a form where user can type in a customer ID and perform a lookup.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html">
<h:head>
	<title>Home</title>
</h:head>
<h:body>
	<h:form>
	Search customer by id:<br />
		<h:inputText value="#{mainController.lookupId}"/><br />
		<h:commandButton type="submit" value="Submit"
			action="#{mainController.doLookup}" />
	</h:form>
</h:body>
</html>

The result.xhtml page looks like this. Note: JSF 1.x developers pay attention. The doLookup() method returns an outcome of "result". In absence of any matching navigation rule, JSF 2.0 will navigate to result.xhtml.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html">
<h:head>
	<title>Result</title>
</h:head>
<h:body>

	<p>
		<b>Name:</b> ${mainController.customer.name}
	</p>
</h:body>
</html>

This is pretty straightforward and works almost the same way as things did in JSF 1.0 (except there is no need for faces-config.xml for a simple app like this). After you deploy the application, you can execute index.xhtml.

image

Enter a valid id and click Submit. You should see the result.

image

So far so good. Except, we are using POST request and the result page can’t be book marked. How can we migrate that to use GET? The answer is view parameters. This will need a change in the result.xhtml page. We need to do two things:

  1. Map URL parameters in a GET request to managed bean properties.
  2. Have the action method doLookup() invoked so that we can populate the Customer bean.

Open result.xhtml in editor. Between the head and body tags, define the view parameter:

<h:head>
	<title>Result</title>
</h:head>

<f:metadata>
	<f:viewParam name="id" value="#{mainController.lookupId}" />
	<f:event listener="#{mainController.doLookup}" 
		type="preRenderView"/>
</f:metadata>

<h:body>
	<p>
		<b>Name:</b> ${mainController.customer.name}
	</p>
</h:body>

There are many things going on here:

  1. <f:viewParam> must appear within <f:metadata>.
  2. <f:metadata> must appear directly under the view root. That is, you can not define it within <h:head> or <h:body>.
  3. The name attribute of <f:viewParam> defines the name of the URL parameter. This value is set to the property identified by the value attribute. That means, in our case, the id URL parameter will be set as the lookupId property of MainController.
  4. The <f:event> tag is used to have the action handler method invoked when a GET request arrives for result.xml.

After you deploy the application, you should be able to execute the result page directly by supplying the id URL parameter. For example: http://localhost:9080/JSFTest/result.faces?id=E001. Depending on the URI path binding of the JSF servlet, it can also be: http://localhost:9080/JSFTest/faces/result.xhtml?id=E001.

You can put hyperlinks in your application using <h:link outcome="result?id=E001">Bugs</h:link>.

There is a slight problem at this point. If you submit the original form, doLookup() will be called twice – first time due the POST request and next time due to the <f:event> tag in result.xhtml. The solution is to change the action of the commandButton to an outcome, rather than an action handler method. Open index.xhtml and change the action of the commandButton to "result" outcome.

<h:form styleClass="form" id="form1">
Search customer by id:<br />
	<h:inputText value="#{mainController.lookupId}"></h:inputText>
	<br />
	<h:commandButton type="submit" value="Submit"
		action="result" />
</h:form>

No Comments