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.