Friday, September 24, 2010

Runtime Shared Library (RSL) – Flex 3

The best way to reduce the size of your Flex application (or the resultant SWF file) is to use Runtime Shared Library which uses the concept of dynamic linking.

Normally a Flex application consists of your application code as well as the framework code and the both of these codes are statically merged together in a single SWF file. It makes the resultant size of your application (the SWF file) larger by adding some 500 KB’s of data to it, which has to be downloaded each time the application is downloaded to a client.

On the other hand, RSL allows you to decouple your application code with the framework code and allows you to dynamically link both of them as and when needed (while running the application). Without wasting time, lets try and configure our project to use RSL instead of static linking. It can be done either using command line Compiler Options or by changing certain settings in Flex Builder. We’ll go the easy way:

Setup in Flex Builder

Following Steps are needed to Compile and Build a Project in Flex Builder with RSL in it:

  1. Select your Flex Project. Click on Project –> Properties
  2. Go to Flex Build Path
  3. Open Library Path Tab. By default the framework linkage is statically linked --> Merged into Code as shown below:

clip_image002

Change the drop down to Runtime Shared Library (RSL) for dynamic binding.

clip_image004

Make sure that Verify RSL digests checkbox is checked. Click Ok to complete the changes and the project will be recompiled with updated compiler settings.

This will create 2 files for RSL in the Output Folder of your project:

  • framework_3.X.X.XXX.swf (Unsigned/Failover RSL)
  • framework_3.X.X.XXX.swz (Signed RSL)

By default, the Flash player will try and use the Signed RSL to link with your application code on loading but the signed RSL works only with Flash Player 9.0.115 and later. If your clients are using a lower version, then it will be unable to load the Signed RSL (swz) and will automatically switch over to the failover RSL (swf) and use it in place of Signed RSL.

A Major benefit of using Framework RSL is caching. RSLs are cached when they are first used. When they are needed by another application, they can be loaded from the cache rather than across the network. The signed framework RSL (RSL’s can be signed by Adobe only) can be cached in the Flash Player cache as well. This benefits by reducing the initial download time as there is no need to download the framework code every time you need to run your Flex Application. And since the caching is done in the special cache of the Flash Player and not in the browser cache, so this signed RSL can be used for some other Flex Application (served from a different domain than yours) On the other hand, the failover RSL is cached in the browser’s cache.

Compiler Settings

Apart from RSL, while building the project for Production Environment, the debug option must be set to false, else the resultant SWF file will also contain the debug information, which is unnecessary for the production environment. To do so, right click the project, go to Project Properties and open the Flex Compiler View and add

-debug=false

in Additional Compiler Arguments as shown below:

clip_image002[8]

Without doing this also, it will work but the resultant SWF file will have debug information with it. The default value of this parameter is true.

Go Check the output folder of your web application and you will definitely see a reduced SWF file there Happy Flexing :-)

Friday, August 20, 2010

Thread-safe Generic Class in Java

Assuming that you are a Java Developer, I can say that you have at some point or the other must have used Generics in your code, be it using a Generic Collection (if you have worked with Java5+) or in any other way. Even if you are not a Java developer, you must have played with Templates (in C++) in your school/college days.

Today, we are going to do something similar in Java. We are going to create a Generic Stack class in Java, which you can use to create a Stack of Integers, Floating Point Numbers, or a Stack of Students or any custom type that you have. Just to make code a bit more interesting and tough, I have also made it thread-safe so that multiple threads can use this stack without leaving it in an inconsistent state.

public class GenericStack<T> {

private List<T> items;
private int top;
private int size;
private static final int INIT_SIZE = 100;

public GenericStack(){
size = INIT_SIZE;
items = new ArrayList<T>(INIT_SIZE);
top = -1;
}

public GenericStack(int size){
this.size = size;
items = new ArrayList<T>(size);
top = -1;
}

private boolean isEmpty(){
return (top==-1);
}

private boolean isFull(){
return (top == size-1);
}

// Push an Item in Stack
public void push(T item){
synchronized(items){
// While stack is Full
while(isFull()){
try{
// Wait till Stack is Full
items.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
// Produce Item
items.add(++top, item);
// Notify other threads
items.notify();
}
}

// Pop an item out of stack
public T pop(){
T item = null;
synchronized(items){
// While Stack is Empty
while(isEmpty()){
try{
// Wait if its empty
items.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
// Consume an item
item = items.get(top--);
// Notify other threads
items.notify();
}
return item;
}
}

Most of the above code is self-explanatory but lets highlight some of the major concepts used here:
  • To create a Generic class, one must specify the Type along with the class name (as done using T).
  • When you initialize it, all the occurrences of T will be replaced by that particular type.
  • We have also made the above Stack class thread-safe, i.e. it can be shared and updated by multiple threads in a consistent manner using synchronized blocks.
  • We have checked before pushing for a Full Stack and we also check for an Empty Stack before popping an element
  • We have not made the isFull() and isEmpty() methods as synchronized as they are private (hence not visible to clients) and are always called from an synchronized context from within the class.
  • If you need isFull() and isEmpty() to be public then make them also synchronized to make them thread-safe
  • It is always better to have synchronized blocks rather than synchronized methods as it is always better to synchronize as less code as possible. Although, here we could not make much use of this concept but rather than obtaining the lock on the calling object, we obtain a lock on the shared list of items.
  • Calling synchronized(items) means if some other thread has not yet acquired a lock on items (By the way, each Object in Java has an associated Lock with it), then this current thread acquires the associated lock and proceeds. Otherwise if some other thread has currently acquired the synchronized block, then it must wait in the wait list of the object (items) in question. The thread then waits until it receives a notification that the lock has become available for acquisition and then it competes with other waiting threads to acquire the lock.
  • Calling items.wait() results in the current thread being placed in the wait list of items after releasing the lock. You can only call object.wait() after you have acquired the lock on the object.
  • Calling items.notify() results in sending the notification to one of the threads in the wait pool of threads which can then compete for the lock.
  • Note that items.notify() does NOT releases the lock. Only exiting the synchronized block/method releases the lock that was acquired when the thread entered the synchronized block/method.

You can easily create two or more threads (viz. Producer and Consumer) and pass them the same Stack and play with them to randomly create and consume data and check that you Stack class is indeed thread-safe.

Generic Methods

Talking more about generics, you can also make a method accept Generic parameters without the enclosing class declaring the Generic type as done in the following example:

public <T> List<T> createArrayList(T t){
List<T> arr = new ArrayList<T>();
return arr;
}

This weird looking syntax has a meaning:

  • This method basically lets you create an arraylist of any type, type is passed to it as an argument.
  • Since you are not defining the type at Class-level, then there must be a place where you should define the type of your method and distinguish it from other non-generic methods for the compiler.
  • So, we declare the type <T> immediately after public modifier to say that we use a Generic Type T in this method, which like others will be replaced at runtime with any real type. (just like in case of Generic classes)
  • We call this method passing to it a valid reference to any Object of any type (Integer, Float, or you own custom class Student). For example, we can do:
Integer i = 23;
List<Integer> intList = createList(i);

or

Student st = new Student();
// Do anything with st here
List<Student> students = createList(st);

Ok, I agree this is not one of really useful examples for showcasing the power of a generic method but I hope that the intent is clear and so is the syntax. As always, your valuable comments are welcome and desired. Any corrections must also found place in comments. Sayonara :-)

Sunday, August 15, 2010

Mixing Generic & Non-generic code in Java

Can you spot the error in the following code:

public class MixingGenerics{

public static void main(String[] args){
List<Integer> arr = new ArrayList<Integer>();
arr.add("String 1");
arr.add("String 2");

// add something more
addToList(arr);
}

public static void addToList(List arr){
arr.add(new Integer(1));
}
}

I’m sure you are able to point out the mistake that we are adding an Integer to an ArrayList of Strings. That’s definitely not done. But can you tell without compiling this code that we get an error at compile-time or at run-time ?

Unfortunately and even more surprisingly, this code doesn’t give any compilation error or runtime exception. Everything works fine and an Integer is added into your ArrayList (of Strings) !! Yes, you do get a compiler warning that says something about Type Safety of your code. We will get back to this point later on.

But first examine how is possible that you can actually store an Integer in a String Arraylist? Actually, it is an unfortunate outcome of mixing Generic & Non-generic code. The reason why we get no error is due to a property of Generics called Type-Erasure. We’ll get to it soon but first lets see when the previous code will throw an Error/Exception. This code will explode as soon as you would try and iterate the ArrayList of Strings, in which you have put an Integer unknowingly as shown below:

public class MixingGenerics{

public static void main(String[] args){
List<Integer> arr = new ArrayList<Integer>();
arr.add("String 1");
arr.add("String 2");

// add something more
addToList(arr);

// print the list
printMyList(arr);
}

public static void addToList(List arr){
arr.add(new Integer(1));
}

public static void printMyList(List<String> arr){
for(String s:arr){
System.out.println("String : "+s);
}
}
}

So we get a runtime exception now on iterating the list. It prints the first two strings and then throws ClassCastException as we are trying to cast an Integer into a String s. That’s okay but why does it allows you to add an Integer into List of Strings.

Type-Erasure

Generic code in Java exhibit a very important property: Type-erasure. What it means is that the so-called type-safe collection of yours (the generic collection here: ArrayList<String>) loses its type information at run-time and acts as if its just a List (like pre-Java 5 lists, the non-generic list). This has been made such so that we can integrate pre-Java 5 (the non-generic code) with newly written Generic code (Java 5 or later), but then while mixing them, you must be careful. Very careful indeed, else you could happen to write a code that will explode unpredictably.

So the answer to our question that why it allows an Integer to a list of Strings is because at runtime we only have a list, just like we had a list in pre-Java 5 days. Without generics, we had to take care while taking object out of the list and casting them but with Java 5 and above code, that casting is implicitly inserted by the compiler. So when we say

String s = arr.get(0) gets converted into String s = (String) arr.get(0)

Doing exactly the same with our list, it gives an error when we try and cast an Integer into a String and hence the error: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

Apart from giving the error, the compiler does his best and warns you when you are trying to mix Generic code with Non-Generic Code. If you are very sure about your code and do not want any compiler warning, then you can do by using following Annotation (valid with Java5+ code)

@SuppressWarnings("unchecked")
public static void addToList(List arr){
arr.add(new Integer(1));
}

This lets the compiler know that you are pretty sure about the code that you have written and do not give me any warnings with this method. Generally, it is not recommended to use such Annotations and if you really need to use one, you must do proper documentation of your code.

Any comments and corrections are welcome :-)

Thursday, July 15, 2010

JBoss – Basic & Digest Authentication

This blog entry is a replication of my previous blog entry: Tomcat – Container Managed Security. It is extending the same entry for JBoss, so I’m gonna skip all the introduction and straight-away get to work.

Basic Authentication

1. Open the login-config.xml file located at ${JBOSS_HOME}/server/${USER_PROFILE}/conf

This file sets up the configuration for the security domains available to applications running in the server. JBoss uses JAAS for the underlying security infrastructure, and JAAS interacts with a security store for authenticating credentials.

In simple words, we specify an application policy in this file, which tells the Login Module that we will use (Like Tomcat, here also we have plenty of options like LDAP, Database, Property Files etc for Login Modules). Basically, Login Module specifies the usernames, passwords and roles used for protecting your application. To start with, we will use UsersRolesLoginModule, which uses a property file to specify all the above mentioned information. Obviously, this isn’t secure and not really a choice for a system in production. Time to make changes:

Make changes in login-config.xml file : Add the following policy at the end of the file:

ApplicationPolicy

  • The "name" attribute on the "application-policy" element specifies the name of the security domain. This name is important because it is what will be used to tie the security domain to the web application later. We will mention it in application’s web.xml.
  • The "login-module" element specifies the login module that this domain will use.
  • The "module-option" elements specify some values to pass into the login module's "initialize" method. For UserRolesLoginModule, we will specify the property files for user information and role information. These paths are relative to the ${JBOSS_HOME}/server/${USER_PROFILE}/conf directory.

2. Open the ${jboss.dist}/server/${server.name}/conf/props and create 2 files:

  1. web-users.properties (user information)
  2. web-roles.properties (role information)

In web-users.properties property file, add

userNamePassword

In web-roles.properties, add

userRoleInfo

3. Open web.xml of your web application and make following changes -- add following security constraint:

securityConstraints

4. Open jboss-web.xml of your web application and add following line inside the <jboss-web> element:

JAASSettigns

This element tells JBoss to connect the web application to the "webPasswordProtection" security domain (application policy) we defined in the login-config.xml file earlier. JBoss exposes security domains via JNDI by pre-pending "java:/jaas/" to the name element in the application-policy element in the login-config.xml file.

Voila!! You are done now. Just restart the JBoss Server and your authentication should work fine.

DIGEST Authentication

Having already said that this basic authentication is not recommended for production purposes, we will try using a different authentication mechanism : Digest Passwords. We will save the passwords in a digest (hashed) form in the properties file instead of saving them in clear-text form. Make following changes:

1. Change in login-config.xml file

Digest

2. Find the new hashed password using built-in RFC2617Digest class:

digestpassword

The RFC2617Digest class is present in jbosssx.jar which is present in ${JBOSS_HOME}/server/default/lib directory. So this jar file must be on your classpath when you execute the above command. If it is not so, then use –cp option of java tool to set CLASSPATH as done above. The generated password is b63289befb5c9bb0509eed20b253e985. Note that the arguments passed to this class are

  1. User Name
  2. Realm Name
  3. Password

in that order. Now is the time to store this hashed password in your web-users.properties file.

3. Change web-users.properties file as follows:

digestpass

Now, just restart JBoss to see the effect. And it is more secure than Basic authentication as you are not transmitting the password over the wire.

Sunday, June 27, 2010

SSL Configuration in Tomcat

Today, we are going to learn about how to setup SSL on your Tomcat so that you can access your application on HTTPS instead of HTTP and provide a secure interface to your clients. But before going into that, lets understand the basic difference between HTTP & HTTPS.

Introduction to HTTPS

HTTPS (HyperText Transfer Protocol Secure) combines HTTP protocol with SSL (Secure Sockets Layer) or TLS (Transport Layer Security) and offers a secure channel to browse the web so that you can trust the connection to send sensitive information like payment transactions details or your bank account details. The difference between the two clearly shows in the address bar where you can see https:// instead of http://. Also HTTPS uses port 443 as the default port, whereas HTTP uses port 80 as the default port for communication.

Using HTTPS, the two-way communication that occurs between your web browser and the host server is now secure and encrypted. This means that the data being sent is encrypted by one side, transmitted, then decrypted by the other side before processing.

When a web browser initially attempts to contact a web server over a secure connection, it is presented with a “certificate” (set of credentials), as a proof of the site is who what it claims to be. These certificates are signed (digitally verified) by certain authorities like VeriSign and typically purchased by the web server. Remember that you need to buy a certificate for each port on which you want a secure connection. For this blog entry, we will sign our own certificate and make other changes to Tomcat configuration so that it starts accepting connection on port 443 using HTTPS protocol.

But before we begin setting up SSL on Tomcat, its very important to iterate that this is valid only if you are using Tomcat as a stand-alone web server, the other possibility being Microsoft IIS or Apache Server serving as the main interface to the outside world and Tomcat is serving as the JSP/Servlet Container at the backend, communicating with one of these servers. In that case, you have to make SSL configuration changes in IIS or Apache, while Tomcat will continue to work normally sending cleartext responses (no encryption at Tomcat level).

Creating a Certificate

Fortunately, Java provides us with a utility (keytool) which can be used to create a self-signed certificate. This is not validated by any authority, hence not suitable for production use. But it can certainly be used for development purposes. So, lets  create a certificate from scratch for our application:

Type in the following command and enter details(credentials) about your organization that users of your site/application would see in the certificate given to them when they use it. The default password for Tomcat is “changeit” (all in lower-case). It would be asked when you type the following command to generate your self signed certificate:

>> keytool –genkey –alias –tomcat –keyalg RSA

Note, you must enter the password (as told above) and then all the credentials as shown below:

newCertificate

After doing this correctly, a .keystore file will be generated in your home folder (in the home folder of the user who did this). This is the certificate your tomcat would use and present to any user who visit the secure site.

Configuring Tomcat

Now, we make changes in Tomcat configuration to reflect this change. Tomcat uses 2 different implementations for SSL: Apache Portable Runtime (APR) implementation and JSSE Connector implementation, provided by default with JRE (Java Runtime). Most of the users (like me) do not have APR installed by default, so following steps are valid for JSSE implementation

We now open server.xml present in $CATALINA_HOME/conf. An example <Connector> element for SSL is included by default in most server.xml that comes with Tomcat. It looks something like this:

SSLconnector

All you have to do is to uncomment this connector and add to it the location of your certificate (.keystore) that we generated and the password we used to generate it. So finally the entry for the connector looks like:

NewConnector

Also, make sure that the Non-SSL Connector (the default one) which accepts connection on 8080, should have a redirectPort attribute set to 8443 or to the port that you specified for SSL Connection in the connector above. The entry looks like:NonSSLConnector

That’s all you need to do to make sure that Tomcat starts accepting secure connections on 8443 and redirects users who attempt to access a secure page with http to https. For more details regarding each attribute of the connector, you can refer Java HTTP Connector configuration reference.

Go ahead, try it out and feel the magic that Tomcat provides you. :-) Please post any bugs, queries and corrections as comments.

Saturday, May 29, 2010

Tomcat – Container Managed Security

If you are a web developer, then I will not think twice before saying that you must have used Tomcat knowingly or unknowingly for deploying your web applications.

For me, Tomcat is a pretty basic web server, which mainly serves as a JSP/Servlet Container. Today, we explore some basic security features that are provided by the container itself. There are different ways in which this authentication can be provided. In this blog entry, we will try to understand and implement Basic & Form-based Authentication using MemoryRealm.

What’s a Realm?

According to the Tomcat specification, a Realm is a "database" of usernames and passwords that identify valid users of a web application (or set of web applications), plus an enumeration of the list of roles associated with each valid user. Obviously, there are many ways to specify the valid username-password combinations and the associated roles. We will use something known as MemoryRealm, which uses a file: tomcat-users.xml to specify this database.

Steps to Enable Authentication

  1. Change the configuration file (server.xml) of the Tomcat Server to specify the realm that you will use
  2. Change the tomcat-users.xml file to list the valid username-passwords and the associated roles
  3. Change the deployment descriptor (web.xml) for your web application to reflect security constraints needed by the application.

Step1: Change server.xml of Tomcat

The default server.xml has the UserDatabaseRealm enabled as shown below:

 serverXml

Note: This can change depending on the versions of the Tomcat, but for Tomcat 5.5 and Tomcat 6, it is the default one. We change it to use MemoryRealm by commenting the previous line and adding the following declaration as shown below:

serverXmlChanged

Step2: Change tomcat-users.xml of Tomcat

The default tomcat-users.xml file, which is present at $CATALINA_HOME/conf/tomcat-users.xml  where $CATALINA_HOME is the directory in which your Tomcat server is installed, looks like:

tomcatUsers

To this, add your own role and associate with it, some valid combination of username and password as done below:

tomcatUsersChanged

Step3: Change web.xml of your web application

So far, we have made changes in the Tomcat server itself, its time we must modify our application to reflect the security constraints that we want. To do so, we add the following to our web.xml file:

a) Security Constraints as per the need

securityConstraint

Here, We specify that in order to access any URL in our application which comes after http://{context_App}/jsp/…  should be password-protected. Also, we associate a role with it, so users associated with that role can only access these URLs now.

b) Declaring the Security Role

securityRole

c) Specifying the Type of Authentication

basicAuthntication

We tell Tomcat that we want to use BASIC authentication for our web application and the realm that we will use will use your tomcat-users.xml file. 

That’s it. All you need to do now, is to restart Tomcat and check whether this works or not. Obviously you need to create a basic web application to deploy onto the Tomcat , for which you have specified the security constraints. You can download my test web application here. (Provide a Link)…………………

This was pretty basic stuff, but it has several limitations. For one, this is not suitable for production environments and we must use FORM-based authentication instead of BASIC. Secondly, it is not a good practice to use clear-text passwords in tomcat-users.xml file. We can save the encrypted password (encrypted by any algorithm like SHA, MD2, MD5 etc) supported by the realm.

Changes to overcome limitations

1. Use Digested Passwords

Obviously, storing passwords in clear-text readable format in tomcat-users.xml cannot be considered safe or practical. In a production environment, it is essential to use some encryption to provide security. Tomcat provides us with several digest algorithms (SHA, MD2, MD5 etc) supported by MessageDigest class. To enable it, change the realm declaration in server.xml of Tomcat to the following:

memoryRealmMD5

Also, change the password you specified in tomcat-users.xml to the encrypted version of the original password, by using RealmBase class. You can find this class in catalina.jar in $CATALINA_HOME/lib directory. Use it as follows: RealmBase.digest(“password”, “MD5”, null) . Now, restart your Tomcat and test your authentication.

2. Use FORM-based Authentication

Since using BASIC authentication, you have very little control over the authentication/login method used by Tomcat and it is not considered practical for production environment. So we demonstrate another way: FORM-based authentication. The whole setup remains same, only you can provide your own custom login and error pages (with your company logo and whatever you want) instead of just popping up a window (as done by Tomcat in BASIC mode)

We will change the <login-config> element declared in your application’s web.xml as follows:

form-login-config

We will now add login.jsp and error.jsp to our application. login.jsp is used to authenticate the user: hence it would provide a form while error.jsp is the page to which user is redirected in case of an error: invalid username-password.

login.jsp will have at least a login field with name as “j_username” and password field with name as “j_password”. This must be same so that tomcat can identify the password and login fields in the form. Also the action of the form must be “j_security_check”. You can find the link to download the whole project at the end. My authentication page looks like this, which I believe is much better and safer than basic mode.

authenticate

Still, we have one limitation:

Any changes made to the file: tomcat-users.xml will be reflected only when the Tomcat server is restarted. So, if you add a new username-password combination to it, you must restart Tomcat in order to have its effect. We can also overcome this limitation by specifying the username-password and roles in a database table and using a JDBCRealm instead of MemoryRealm. You can download entire project from here.

Sunday, May 23, 2010

Flex Remoting with Java Part 2

In the last blog entry, I wrote about setting up a simple Flex Application and integrating it with Java so as to be able to make Remote Calls to Java Methods and display the result in Flex.

Today, we are going to make those efforts valuable by seeing how a user-defined object can be passed between Java & Flex. We will create a Employee List in Java and show it in a DataGrid in Flex. As Simple as that. To start with, you must have all the environment setup as explained here.

RPC with User Defined Objects

To be able to do so, we must create classes in both ActionScript and Java and bind them together as shown below:

Employee.java

EmployeeJava

Employee.as

EmployeeAS

The Java and the ActionScript file have the same attributes and they map to each other using Flex Metadata: RemoteClass(alias=””) which maps the java object returned from server to ActionScript object which can be displayed. This metadata tag used in ActionScript Class (Employee.as) specifies the fully qualified name of the corresponding Java Class. We now create a Utility class for getting Employee details:

EmployeeUtils.java

EmployeeUtils

Here, we have hard-coded the Employees Data, but it is as easy to get these employees from a database by firing a query. We now make a RPC call from Flex to get this list so that we can display it in a DataGrid.

getAllEmployees

We create a RemoteObject in Flex and specify a destination “employee” which is present in a remoting-config.xml to specify the Java Class file to look for methods called (getAllEmployees) using this RemoteObject. Part of flex-config.xml which specifies this looks like:

remotingConfig 

We specify the result and fault handlers with the remote object, which are called when result or fault occurs. In the result handler function, we save the result in a ArrayCollection, which we bind with our DataGrid as shown below:

employeeDatagrid

We set the dataProvider property of our DataGrid component to __employeeList, which is a bindable ArrayCollection which contains the result data. The advantage of making the ArrayCollection as bindable is that any changes made to this ArrayCllection (due to any event) is reflected in our DataGrid automatically.

When we run this example, we get a DataGrid as shown below:

output

Again this is not a best-way to code your flex application. The intent was to show how user-defined objects can be passed between Java & Flex. In practice and in large scale application, we would use tested frameworks like Cairngorm or PureMVC.

Wishing you very Happy Coding with Flex :-)

Wednesday, April 28, 2010

Flex Remoting with Java

Flex is one of those technologies that has taken the RIA (rich internet applications) world by storm and surprise. It has never been so easy to create interactive user interfaces before. Flex offers various ways to interact with languages like Java, PHP and Coldfusion:

  • RPC Services which enables Flex applications to make asynchronous calls to remote services following a call and response model.
  • Data Management Services provides data synchronization and real-time updates, on-demand data paging and many other data integration features to Flex Applications.
  • Message Services that provides Flex with a publish-subscribe mechanism to create rich and collaborative real-time applications

All these capabilities are provided as a part of Adobe’s LiveCycle Data Services Pack. But unlike the Flex SDK, the entire LiveCycle Data Services Pack is not free and open Source. Rather, Adobe has open sourced a part of it, basically the RPC services and Message Services known as BlazeDS.

Using the RPC Services, one can

  • Call and invoke remote Java Methods directly and bind the result to a Flex component. (using RemoteObject Component ). It follows a request and response model making asynchronous calls to the backend.
  • Invoke an already deployed SOAP-based Web Service over HTTP using WebService Component.
  • Send and receive data using HTTP GET and POST using HTTPService Component.

Today, we are going to make use of RemoteObject to invoke Java Methods and show the result in Flex. For this purpose, we are going to use

  1. Flex 3 SDK
  2. Flex Builder 3
  3. BlazeDS for making asynchronous calls to Java

Open Flex Builder. Create a new Java Project. Name it ‘testFlexRPC’.

Project Structure

Structure of a typical flex application that we will use looks like:

projectStructure

web’ is our output folder. We will deploy it as a WAR file later on. The output folder contains the WEB-INF folder, in which we will add the deployment descriptor ‘web.xml’ file and other folders such as classes. (the path web/WEB-INF/classes should be your default output folder in Java Build Path, which will store the class files). Make two other folders, flex and lib which will contain the flex files for remoting purposes (remoting-config.xml and services-config.xml) and the libraries needed for Flex Remoting (typically the BlazeDS JARs for messaging).

Deployment Descriptor

Lets add the deployment descriptor (web.xml) to the project. It will typically contain an entry for the MessageBroker Servlet (which is used by the flex framework for RPC communication) and specify the location of services-config.xml, which is used to define the kind of RPC services to be used.

web.xml

deploymentDescriptor

Services-Config.xml

Line 14 of web.xml specifies the location of services-config.xml in your project. It is the top-level configuration file that contains security-constraint definitions, channel definitions, logging settings that each of the services can use. Create an empty XML file on that location and add the following to it:

servicesConfig1

Firstly, it defines the kind of RPC services that we will use in this project. It includes another file: remoting-config.xml which will contain the destinations for RPC Calls.

Next, it defines the channels that are actually used by the flex application to transfer data between client and server. It defines two channels: HTTP channel and AMF Channel (AMF stands for Actionscript Messaging Format). These channels are used in remoting-config.xml as we will see in a moment. These channels are a key element of the destinations that are specified and perform all work needed for the asynchronous communication that is required by the application.

The other part of this file: services-config.xml specifies the logging information and looks like:

servicesConfig2

Remoting-Config.xml

Lets create another XML file, which will list the destinations that we will make use of, for making asynchronous calls to remote Java methods from Flex.

remotingConfig

It specifies the channels (HTTP and AMF that we configured in services-config.xml) that these destinations will use to communicate between client and server. This file also lists the adapter (server-side code) that interacts directly with the object or the service.

Next, it defines the destinations that can be used with <mx:RemoteObject>, <mx:WebService> and <mx:WebService> tags in MXML or its equivalent in Actionscript code.

Here, we define a destination (sayHelloToMe) and bind it with the Java Class SayHello.java present in java.myPackage package.

Now, add the following libraries in your project. You can find them in the BlazeDS zipped file that you downloaded at the start.

libraries

Now, right click on the project node and go to Flex Project Nature –> Add Flex Project Nature

A popup would appear asking for Flex Project Settings. Choose the default settings: application server type to J2EE and check the box Using remote object access service. Click Next to configure J2EE server for your application

flexProjectNature

Enter your application deployment settings like your application server’s port number and the context root that you want for this application. Also specify the output folder, where you want the resulting SWF file (and the html wrapper) to be stored. Click Finish to successfully add the Flex Project Nature to your Java application.

It will automatically create a default MXML application file with the same name as the project to the source folder (configurable in Flex Build Path). We move this mxml file to flex folder that we created under src/flex folder (not necessarily needed, but we have a thing for being organized :-) ). Though for this, we also have to change the Flex Build Path. So, right click on the project node, go to properties. Click on Flex Build Path tab and set the following settings:

Click Add Folder and add “src”. Also change the main source folder from “src” to “src/flex”. Click Ok to update the compiler settings. You still need to set the testFlexRPC.mxml as the default mxml application. so, right click Project node, go to Properties, Go to tab Flex Application. click on Flex folder and click add. Now add the testFlexRPC.mxml file and click set on default button to make it default application file.

If you check out, the project must be giving you a compile-time error since we have not created any html file (wrapper) to embed the SWF file which contains the compiled flex application. So right click on the error and click ‘Re-create HTML Templates’ to create the default html wrapper which can be used as is.

Now, your application is ready to be deployed (technically), but since we have not added any display element and made use of Flex Remoting (the long and tiring process that we have done so far), so there is no use of deploying it currently.

Now, comes the easy part. Click the src/java and add a new package: mypackage and create a new Java File: SayHello.java ( as specified in remoting-config.xml ) It looks like the following:

SayHello.java

SayHelloToMe

Now, this is a very simple example (because I think you already have had enough !!) and this is not something for which you have to go to Java from Flex. But it is enough to show you how things can be done and results calculated in Java can be passed to Flex (whether its a primitive or any other object: String or any user-defined object as well)

Now, we will call this java Method in Flex. Add the following code in testFlexRPC.mxml file, already created.

testFlexRPC.mxml

ApplicationMXML

Again, this is not a best-practice way to code, but since I’m running out of space and you are running out of patience, so I’m doing things quickly :-)

Finally, we are ready for deployment and I’m using Tomcat to deploy my web application. To accomplish this, we create the following XML file specifying the context.

flexRPCJava.xml

flexRPCJavaXML

To learn more on how to deploy Web Applications on Tomcat, please read my previous blog entry about the same.

Now, all you need to do is to start Tomcat and check whether your application is working correctly or not by checking the HTML wrapper that Flex Builder created for you:

output

I hope you are with me till now and would be happy to know that this (perhaps the longest blog I ever wrote) has finished and you have successfully learned how to use Flex with Java.

I could have taught the same in a very concise manner using the BlazeDS Turnkey Server and pre-configured examples, but that would have defeated the purpose of structuring and creating a web-application from scratch. Hope you had fun. Cheers !!

Any suggestions, corrections or Comments are welcome and wanted :-)

Wednesday, March 24, 2010

Singletons, Threads & Double Checked Locking

This blog entry extends on the first entry I wrote about Singletons. Today I try to explain the usage of Singletons in a multi-threaded environment.

A typical Singleton would look like the following:

MySingletonJava

This Singleton class would work perfectly fine in a single-threaded environment. But, how many Java based applications that you have worked on, are single-threaded? None, perhaps.

Can you see what’s terribly wrong with it when your application has multiple threads running simultaneously ??

Well, the answer lies in the way the instance is lazy initialized. The null-checking and initializing the instance need to be an atomic operation. Lets see what would happen if following sequence of events happen:

  • Thead A calls getInstance() for the first time. And checks whether instance is null or not. It finds it true and goes to execute line 11.
  • At this point, it is pre-empted by another thread: Thread B, which also calls getInstance(), checks for the instance null check, since it is not yet initialized, the private constructor is called and instance is now initialized with a state.
  • Thread A resumes control back and starts from where it left i.e line 11. Now the real problem occurs. Since it checked for the null-check on line 10 when it last run and found it to be true, so when it resumes execution, it will execute from line 11 and again initialize the instance and hence two objects would be created and the whole point of having a single object is violated.

Thus, we really need to do something about the situation. No problems, Synchronization comes to the rescue. Most of us (naive programmers) would tend to get rid of this problem by writing code like below:

MySynchronizedSingletonJava

The only change that occurs here is that we have made our static factory as synchronized method, which makes sure that no possible combination of interleaving of threads could create two objects like it did in the previous case. Although, this works fine but on close inspection, we find that synchronization is necessary only for the first time, and not needed later on (since instance will always be non-null later on) And synchronizing the whole method is thus uncalled for and pretty expensive. We must think of other ways of accomplishing this.

1. Do Not Lazy Initialize

If we do NOT need lazy initialization of the resource, then a perfect method to do away with synchronization would be:

Singleton1Java

Using this, we depend on the JVM’s capability to execute the static block as soon as the class is loaded first (when it is accessed or referred in code).

Thus, the VM makes sure that the instance is well initialized, before any thread tries to call getInstance() method. And since static blocks are executed only once, so no chance of creating more objects. One scenario that I could fail this approach is when this class is loaded again (perhaps by a different classloader in a different namespace)

Another way to write the above code would be:

Singleton2Java

However, I prefer the first way (with static blocks) that gives us more flexibility by allowing us to write a block of code instead of just calling the constructor.

2. Use Double Checked Locking

A very common, popular and misunderstood programming idiom that looks like the following and works with Java 1.5 and above only.

Singleton3Java

See how cleverly, we have limited the scope of synchronization here. The synchronization occurs only for the first time (when the instance is null), after that the synchronization never occurs as the instance is not null. This is what we needed. But you must make this variable as volatile to work it correctly (due to Java Memory Model implementation)

To better understand this programming idiom, I would suggest reading this and this.

I think its enough for one blog post. Any code corrections, new ideas and comments are welcome.

Saturday, February 27, 2010

Creating Immutable Objects in Java

Immutable Objects are those objects, who cannot change their STATE once they are created. Most common examples of such objects are String, Integer, Double etc.. (other Wrapper classes). By State, we mean the values assigned to the instance variables of the object in question.

Immutable Classes are one of the most robust classes that you can ever build and the reasons that we love them are:

  • They are Thread-safe, hence no need to synchronize them for concurrent access.
  • They are Easy to construct, test and use
  • They Serve as good Map and Set keys
  • If such an object throws an exception, it is never left in undesirable or inconsistent state.

Strategy to Construct Immutable Objects

If we follow the following steps, we can easily create Immutable objects or convert an existing Mutable class into Immutable:

  • Since we have to restrict our object to change its state once they are created, we must not provide any setter methods.
  • If a object has references to other mutable objects, then do not provide getter methods that simply return a reference to the mutable object. Rather, create a new object containing the copy of the mutable object.
  • Don't allow any subclass to override methods of the given class. This can be done by making the class as final. Another way is to make the constructor as private and provide factory methods to construct the object.
  • Make all the fields private and final. This way only your class has  the control how these fields are to be manipulated.

Person1

  • Also, do not provide any other methods that modify the object. In case you have to, then do not modify the existing object, rather create a copy of the original object, modify it and return the modified object.
  • Construct the whole object in one go, initialize the whole object (assign values to all the instance variables) while creating the object.

Person2

One may argue that immutable objects calls for creation of unnecessary objects every now and then, for example if we do

Person3

then a new String is created and the original string is not modified. For argument sake, we have 3 Strings created here. viz. “Agraj”, “ Mangal” and “Agraj Mangal”.

But this so-called shortcoming is taken care of by the Garbage Collector in Java, which marks any dead object for Garbage Collection (any object which has no active reference to it in any thread of execution)