Platform Independent Mobile Development

One of the challenges facing every organization entering the mobile space is deciding which mobile platforms to support. The three major platforms today are: iOS, Android and Blackberry. If the organization provided the device (e.g. company issued Android phone) the problem is relatively simple. The organization simply standardizes on a single platform and single device.

The difficulty is that customer facing organizations must provide their products and services to consumers on the consumer’s preferred device. For many organizations that means parallel development on incompatible platforms. For iOS that means Objective C, for Android and Blackberry it’s Java. Even though Android and Blackberry are both in the Java family, their GUIs are completely different. To make things worse, the expected Q4 release of Windows 8 Mobile may make Microsoft a player in the mobile space again. Supporting Windows Mobile would necessitate creating a development team to work in C#, yet another incompatible language.

Even organizations that provide devices to employees will find themselves under pressure from the rank and file to allow a Bring Your Own Device (BYOD) policy.

An alternative to doing parallel development on multiple platforms is to consider platform independent application development. Today using a combination of HTML5 and JavaScript it is possible to create mobile applications that run natively on nearly every mobile device and do not require a browser! Of course HTML5 and JavaScript are normally thought of as Web technologies. Using an API from Apache called Cordova (formerly PhoneGap) developers can write HTML and JavaScript code that is packaged to run as a native application on all of the major mobile platforms. These technologies, combined with a powerful mobile JavaScript library like JQuery Mobile or Sencha Touch, make a compelling solution to simplify and standardize mobile development for a variety of platforms.

We at Web Age Solutions are hard at work in this area ourselves. Check out the outline for our new Sencha Touch based Platform Independent Mobile Development course. If you have any question please contact us and we would be happy to help!

2 Comments

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

WebSphere 8.5 Released

For those used to the measured releases of IBM, the title might come as a surprise.  After all, WebSphere 8.0 was just released last summer and many clients were just starting to prepare to move to 8.0 when IBM announced that it would release 8.5 this summer.  This also includes a new release of RAD 8.5 at the same time.

We will certainly have much more information on what is new in this version coming out over the next several months but I just wanted to give a quick summary now.  You can also look for some more information posted at the WASdev blog or a recent IBM Developerworks article.

Since we’re just looking at the important points here I’ve broken them down by job role:

Developers:

  • Ability to use Eclipse for WebSphere development.  We’ve detailed this previously in this blog post.
  • WebSphere 8.5 supports Java EE 6 just like WebSphere 8.0 does
  • Both WebSphere 8.5 and 8.0 support prior versions of J2EE/Java EE to help minimize application changes required during migration
  • WebSphere 8.5 includes a “Liberty profile” which is a lightweight server featuring extremely short startup time and other features beneficial to developers.  This will certainly be something we focus on more in the near future
  • Simplified server configuration of the Liberty profile with a single XML file
  • Any applications developed to run on the Liberty profile will also run on the “full” WebSphere Application Server
  • Support for JDK 7, although JDK 6 is still the default

Administrators:

  • WebSphere 8.5 still has the changes introduced in the 8.0 server.  The most major of these was the installation with the ‘Installation Manager’ tool and an optional logging framework, HPEL, which provides better performance and usability of logging.
  • Many of the features previously available in the ‘WebSphere Virtual Enterprise’ edition have been added to the ‘WebSphere Network Deployment’ edition.  This means IBM is providing an expanded set of features that used to cost much more to get your hands on.
  • Use of an ‘On Demand Router’ to intelligently route and prioritize application traffic.
  • ‘Application edition management’ which will allow deploying and testing a new application version while the current one is still active for users.  New application versions can then be activated seamlessly without interruption.
  • Health management and dynamic provisioning whereby policies can be established for the desired service level of an application and actions can be taken automatically to ensure these policies are met.  These actions could be as simple as restarting servers or as complex as adding new servers to a cluster.  Establishing these policies would let the WebSphere environment respond automatically without waiting for manual intervention of administrators.
  • Being able to track and rollback administrative changes.  This can be used to rollback administrative changes if needed without needing to manually track changes yourself.

Certainly, even this short list of new features provides a lot of things to look forward to as you start using WebSphere 8.5.  Be sure to follow our blog for more articles about WebSphere 8.5 and announcement of training and consulting offerings around this exciting new version.

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

Data Encryption in SQL Server 2008, 2008R2, 2012 (Part 1)

Data is very important asset. If it’s stolen or “misplaced” then that can cost a fortune to the company. SQL Server provides encryption that can avoid the embarrassment and legal issues if data is stolen. Here we will discuss two important levels at which SQL Server supports encryption. In this part 1 of the blog post we will explore column level encryption. In Part 2 we will explorer encryption at the entire database level.

1. Data Encryption (column level encryption)

You can decide and select the columns that are of utmost importance and encrypt the data for those columns. Benefit is that if you have low end server then encrypting and decrypting hand picked columns won’t hurt the performance. Example of candidate columns for encryption would be password, credit card number, SIN number (Canadian, eh Smile), account number, PIN number etc.

Let’s create a sample database and table and apply encryption at column level

  1: CREATE DATABASE Bank
  2: GO
  3: USE Bank
  4: GO
  5: CREATE TABLE Account
  6: (
  7:   AccountId int NOT NULL IDENTITY(1,1) PRIMARY KEY,
  8:   AccountNumber varchar(50),
  9:   EncryptedAccountNumber varbinary(128)
 10: )
 11: GO
 12: 

AccountNumber will contain the data without any encryption where as EncryptedAccountNumber will contain the encrypted version of AccountNumber.

Now our next step is to create master key. Master key will be used for creating digital certificate and certificate will be used for generating the symmetric key that will finally be used for encrypting data in individual columns.

Create master key:

  1: CREATE MASTER KEY ENCRYPTION BY 
  2: PASSWORD = 'Pa$$w0rd'

 

Create digital certificate

  1: CREATE CERTIFICATE BankCert
  2:    WITH SUBJECT = 'Account Numbers';
  3: GO

Create symmetric key for encrypting data

  1: CREATE SYMMETRIC KEY BankAccountKey
  2:     WITH ALGORITHM = AES_256
  3:     ENCRYPTION BY CERTIFICATE BankCert;
  4: GO

For encrypting the data we use the EncryptByKey function and in order to use this function we have to first open the symmetric key that we created in one of the previous steps. Let’s insert some records:

  1: OPEN SYMMETRIC KEY BankAccountKey
  2:    DECRYPTION BY CERTIFICATE BankCert;
  3: 
  4: --insert original and encrypted values
  5: INSERT INTO Account 
  6: VALUES 
  7: ('123456789', EncryptByKey(Key_GUID('BankAccountKey'), '123456789')),
  8: ('987654321', EncryptByKey(Key_GUID('BankAccountKey'), '987654321'))
 
Let’s query the table and find out how the encrypted data looks like:
image

In the 3rd column we can see that Account Number is encrypted. Original data occupies 9 bytes but encrypted data is occupying 68 bytes. There’s overhead involved due to encryption.

Now how do we decrypt and read the data? Good question. Actually it’s quite similar to encryption. We use DecryptByKey function and before that we have to open the symmetric key that was used for encrypting the data. Let’s do it

  1: OPEN SYMMETRIC KEY BankAccountKey
  2:    DECRYPTION BY CERTIFICATE BankCert;
  3: GO
  4: 
  5: --list original and decrypted values
  6: SELECT AccountNumber, EncryptedAccountNumber,len(EncryptedAccountNumber) AS Size, CONVERT(varchar, DecryptByKey(EncryptedAccountNumber)) AS DecryptedAccountNumber FROM Account

And that’s about it.

Conclusion:

Column level security is useful for securing hand picked columns. DBA’s will have to make sure that they encrypt the certificates and keys so that we can recover the encrypted data in case of a disaster. Developers are responsible for writing the code that encrypts and decrypts the data. Actually it’s pretty straight forward to create stored procedures that encrypts and decrypts the data.

9 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

Goodbye Tomcat!

Tomcat has been a very popular alternative to other application servers like JBoss, WebLogic and WebSphere. People preferred it for its simplicity. I am writing this article to point out how Java EE 6 changes things and why using tomcat could be downright harmful.

Let’s have a quick summary of what makes Java EE 6 so great:

  • Contexts and Dependency Injection (CDI).
  • Java Server Faces (JSF) 2.0.
  • No interface EJB and ability to create EJB in a web module.
  • RESTful Web Service using JAX-RS.

There is the problem with Tomcat right there. None of the above technologies are supported by Tomcat out of the box. Surely, you can add enough JAR files to your web project to get CDI, JSF and JAX-RS. After you are done doing that, you have pretty much created a JBoss look alike. Even then, CDI will be semi-functional. CDI really needs a proper Java EE web and EJB container.

Finally, lack of EJB remains a huge elephant in the room. Sure, EJB was complicated and over engineered. There were good reasons to shun it. That’s not the case any more. EJB has been simplified to the extent it is downright criminal not to use session EJB as your façade to the model layer.

EJB buys you several valuable architecture attributes:

  • You get automated transaction management.
  • You get role based security.
  • Doing audit logging from the model layer becomes a breeze (since you know the user Principal).
  • @Startup and @Singleton classes for better application initialization.
  • Stateless session EJBs can be directly exposed as RESTful Web Services, there by creating a fully transactional and secure interface. With JAX-RS, you can secure a POJOs resource but don’t get transaction support.

All it takes is one extra line to create an EJB:

@Stateless //No interface local EJB
public class OrderManager {

}

You can even create these EJBs right within your web module. There is no excuse not to use them.

Edited: Apache TomEE project has assembled these missing pieces and integrated them with Tomcat. This is the correct direction for the Tomcat project. My problem with Tomcat is that most shops that will use it will shy away from what is so great about Java EE 6. Don’t do that to yourself. Switch to JBoss, Glassfish or TomEE.

22 Comments