Tuesday, April 8, 2008

J2EE/JBoss webapp authentication for the impatient

I just went through tons of articles and documents and howtos to implement a simple web application authorization, so I thought I should save the effort for other impatient people like me. Read through the extensive JBoss documentation for detailed specifications and such, if you're in the mood.

Basic concept:
I want a set of pages to require username-password authentication.

* The username-password combination should be stored in a database
* I am not concerned about EJB security right now, just the webapp
* I don't want to write my own code for this
* I'm using MySQL



Secure the protected URLs in your web.xml. Put the following lines into the web.xml file in your WEB-INF directory:

Secure Content



The Restricted Zone

The role required to access restricted content

This means that any page that's within the /restricted URL will get protected, the authentication mechanism will be BASIC (ugly popup screen which requests the credentials), and anyone who is in the AuthorizedUser role will be able to see it. See the login-config documentation about how to configure a JSP page with form based authentication instead of this.


Make the database accessible for JBoss. Drop the mysql client jar into your JBoss domain's lib folder, and customize the mysql-ds.xml file, which you can find in the JBoss docs/examples/jca directory, using your own database's URL, login, etc. Drop the modified file into your JBoss domain's deploy folder. This is a great feature for datasource configuration!


Create a Users and Roles table in mysql, with the following structure:
- Users should have an username and password field
- Roles table should have a username field, and a roles and role_group field.


Configure JBoss to use your new table for the JBoss-provided DatabaseServerLoginModule. This is configured in your JBoss domain's conf folder, in the login-config.xml file. Basically you need to provide the datasource, and the SQL selects you would use to return these values.


select passwd from Users where username=?

select role, role_group from Roles where username=?

Make sure your Datasource name matches the one you configured in the Mysql DS xml file.


Connect your webapp's J2EE standard authorization settings with the JBoss-specific provider implementation. The place for this is the jboss-web.xml file in your webapp's WEB-INF directory.


This will make JBoss look up the myOwnDomain settings in the login-config.xml file, which will use the JDBC based module to query your database for authentication.

It is quite straight forward to use hashed passwords as well, this is documented in the DatabaseServerLoginModule provider's documentation. Enjoy!
Do you want to sync your phone contacts to a remote data source? No problem, use the bundled HttpClient and write a service. Do you have a buddy that likes to drunk dial you at 3:00 a.m.? Why not have a service that can filter his calls out during certain hours. Things like this would be hard or downright impossible in the past. Now we have Android!

I thought I'd do a little tutorial showcasing the Location API that ships with android. This is definitely a fun API to play with, so allow me to introduce the TrivialGPS application.

Android ships with a mock LocationProvider, which simulates a route in the bay area. You can use it to develop and test GPS enabled applications in a simulated device.

The aptly named TrivialGPS application will display a MapView, and center it on our current location as we move through the bay in "real-time". We use the observer pattern with the LocationManager, so our application can receive updates about changes in our current position and update the MapView accordingly.

At this point, I'm going to assume that you have either looked at the Android tutorials and have at least a rudimentary understanding of the framework, or that you're so damn intelligent that you don't need to.

As of the m5-rc14 version of the SDK, your manifest file must declare a couple of permissions for this application to work. The following is what I've placed in my manifest file.


The TrivialGPS is a single activity that displays a map, so to do this our activity must extend MapActivity.

Android allows a form of IPC via Intents. When you create an Intent, you need an "action", which is basically a string that will uniquely identify the Intent. There are many of these built into the Intent class itself (DIAL_ACTION, EDIT_ACTION, etc). For TrivialGPS we will just invent our own action called LOC_UPDATE. We'll use this Intent to receive periodic updates from the LocationManager.

We also need three instance fields: The MapView which we will be displaying, a MapController which can center the map, and a LocationManager which we can query for providers and request geo information from.

public class TrivialGPS extends MapActivity {

public static final String UPDATE_LOC = "com.test.TrivialGPS.LOC_UPDATE";

private MapController mapController;
private MapView mapView;
private LocationManager locationManager;

Our onCreate method starts out very simple. We create a new MapView, set the zoom level to 22 (pretty close up, so we can see the streets), store a reference to the MapController, and then tell Android to display the map. We'll be revisiting this method a little bit later.

public void onCreate(Bundle icicle) {

mapView = new MapView(this);
mapController = mapView.getController();

In order to receive notifications about location updates, we need an IntentReceiver. An IntentReceiver is basically a callback handler. The simplest way to do this is with an inner class. The class overrides the onReceiveIntent method. The guts of this pull the Location object from the intent bundle, create a latitude/longitude point, and then uses the MapController to center the view on the new point.

public class handleLocationUpdate extends IntentReceiver {
public void onReceiveIntent(Context context, Intent intent) {
Location loc = (Location) intent.getExtra("location");

Double lat = loc.getLatitude()*1E6;
Double lng = loc.getLongitude()*1E6;
Point point = new Point(lat.intValue(), lng.intValue());
mapController.centerMapTo(point, false);


As promised, we now return to onCreate method.

The first thing we've added is a call to initialize the LocationManager.

Next, we retrieve the mock location provider, "gps" using the getProvider method from the LocationManager.

The observer pattern here is decoupled, our handleLocationUpdate doesn't register itself directly with the LocationManager. Rather, we register with android itself and tell it the particular Intent that we're interested in. We do this by calling registerReceiver and handing it the IntentReceiver and an IntentFilter that specifies what actions we are interested in hearing about.

The other end of this is telling the LocationManager to broadcast an Intent continually that will be handled by handleLocationUpdate. We create an Intent identified by our LOC_UPDATE action, and then tell the LocationManager to continuously broadcast updates via a call to requestUpdates.

public void onCreate(Bundle icicle) {

// create a map view
mapView = new MapView(this);
mapController = mapView.getController();

// get a hangle on the location manager
locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);

// get the "gps" mock provider
LocationProvider provider = locationManager.getProvider("gps");

// register our IntentReceiver as an observer.
registerReceiver(new handleLocationUpdate(), new IntentFilter(UPDATE_LOC));

// instruct the location manager to broad cast the UPDATE_LOC intent
// continually as we move.
Intent intent = new Intent(UPDATE_LOC);
locationManager.requestUpdates(provider, 0, 0, intent);

I should mention that when you run TrivialGPS, it takes a couple of minutes to see the thing start moving. Perhaps when they designed the mock provider they also wanted to simulate a car with engine problems. =)

I hope some of you can find this useful. It took me several hours to figure this stuff out and get it working in my own application, so perhaps this tutorial will be a nice time saver for some of you out there, that way you can get back to your eggnog and Xmas toys.
One of the ideas for improving the Java Programming Language is "type inference" on variable declarations. The idea is to simplify a pattern of code that now appears in programs due to generics:

Map> map = new HashMap>();

surely we shouldn't have to give the same type parameters twice? The simplest proposal to relieve this redundancy allows

map := new HashMap>();

This introduces the new colon-equals token and the declaration-assignment statement. The variable appearing on the left-hand-side of the statement is implicitly defined by this statement, and its type is the type of the expression on the right-hand-side. I don't like this proposal. It both goes too far and not far enough.

It goes too far in that it allows the programmer to elide the type in a variable declaration. The type in a variable declaration is valuable documentation that helps the reader understand the program, and this proposal reduces the readability of programs by allowing it to be elided. Worse, it assigns the wrong type to the variable. Following Effective Java (first edition, item 34), the type of a declared variable should be an interface type. This statement form forces the variable to be of the (likely more specific) type of the right-hand-side. Consequently, the programmer may inadvertently depend on features of the concrete implementation class when using the variable. That would make it more difficult to modify the program later by selecting a different implementation type.

This syntax doesn't go far enough because the verbosity of creating generic classes is worth eliminating in other contexts as well. Programmers today work around the verbosity by providing static factory methods corresponding to constructors:

static HashMap makeHashMap() {
return new HashMap();

This addresses the immediate problem:

Map> map = makeHashMap();

Unfortunately, this idiom replaces one form of boilerplate (in variable initialization) with another: trivial static factories. A generic class is typically created more than once, so adding a single static factory can simplify the code at every creation site. But with language support, we can do better.

I propose a new form of class instance creation expression:

Map> map = new HashMap<>();

Using empty type parameters on a class instance creation expression asks the language/compiler to perform type inference, selecting appropriate type parameters exactly as it would in the invocation of the equivalent trivial static factory.

Type inference today works on the right-hand-side of an assignment. I also propose that we enable this new form to be used in more situations by improving type inference for expressions appearing in other contexts:

* the argument of a method call
* the receiver of a method call
* the argument of a constructor
* the argument of an alternate constructor invocation

This would enable generic methods to be invoked in these contexts without providing explicit type parameters.
Sun: Java SE 5.0 is in its Java Technology End of Life (EOL) transition period. The EOL transition period began April 8th, 2007 and will complete October 8th, 2009, when Java SE 5.0 will have reached its End of Service Life (EOSL). Customers interested in learning more about Sun's Java Technology Support and EOL policy »Read More

Customers interested in continuing to receive critical fixes, are encouraged to consider the following options:

  • Migrate to the latest Java SE release »Read More
  • Migrate to Java SE for Business 5.0 »Read More

During this EOL transition period, the products will continue to be supported per existing customer support agreements.

For developer needs, all products that have completed the EOL transition period will be moved to the Archive area.

I was recently running FindBugs over some Java5 based code and found some places where FindBugs was complaining that two Objects compared with equals() are not of the same type.
Closer inspection showed that this have been Enums in most cases. The IDEs did not warn here and maunal code inspection also does not directly show the issue.
Luckily with enums, you can use == to compare them. And then it gets obvious:

Just a small little change in habits, but it helps a lot.

XML, Cocoa, JavaScript, Java and other stuff.

Fluid 0.8.7 with URL whitelists/blacklists and custom user-agent strings

Fluid 0.8.7 is out, with two major features:

  1. URL Whitelists and Blacklists for allowing/disallowing browsing to matched URL patterns.
  2. Custom User-Agent strings. Choose from popular presets, our provide your own.

The whitelist feature is located in the Preference Window under the “Advanced” pane, while the User-Agent feature is located in each SSB’s Application menu in the main menu.

The whitelist feature is actually really huge for Fluid. This allows so much more flexibility in making SSBs “just work” out of the box, as well as offering the “pro” user tons of power in specifying what webapps she wants her SSB to handle.

How do whitelists work? Fluid SSBs are targeted browsers that only browse the “home website” you provide when you create them. Previously, Fluid would just take a gander at the “Home URL” you provided for your SSB, and try to make educated guesses about what subsequent URLs were part of the same URL domain or broader website/webapp. If you browse to a page that is outside this URL domain or website, Fluid kicks you out to the system default web browser. However, It’s inevitable that Fluid will occasionally be wrong when guessing.

Whitelists allow me to add more special cases out of the box for more websites more easily. But more importantly, the give the end user the power to fix any problem they encounter, and let their SSB know exactly what they consider part of their webapp.


Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. - Gof


Object Creational


The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it is dealing with as long as the concrete prototype extends or implements the prototype interface/class. The concrete prototype object is responsible for cloning itself and returning the cloned object.

The pattern enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at runtime as long as they conform to the abstract prototype.


Java Sample Code

Example 1:

Download Example 1

The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses called Sheep and Chicken. The AnimalCreator class contains references to the two concrete prototypes. During the initialization of the AnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.

The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.

Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.


public Animal clone() {

Animal clonedAnimal = null;

try {

clonedAnimal = (Animal) super.clone();




} catch (CloneNotSupportedException e) {


} // catch

return clonedAnimal;

} // method clone

The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.


public class Sheep extends Animal {

The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.


public class Chicken extends Animal {

The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the "Prototype" pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.


public Animal retrieveAnimal(String kindOfAnimal) {

if ("Chicken".equals(kindOfAnimal)) {

return (Animal) chicken.clone();

} else if ("Sheep".equals(kindOfAnimal)) {

return (Animal) sheep.clone();

} // if

return null;

} // method retrieveAnimal

The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of type Animal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.


AnimalCreator animalCreator = new AnimalCreator();

Animal[] animalFarm = new Animal[8];

animalFarm[0] = animalCreator.retrieveAnimal("Chicken");

animalFarm[1] = animalCreator.retrieveAnimal("Chicken");

animalFarm[2] = animalCreator.retrieveAnimal("Chicken");

animalFarm[3] = animalCreator.retrieveAnimal("Chicken");

animalFarm[4] = animalCreator.retrieveAnimal("Sheep");

animalFarm[5] = animalCreator.retrieveAnimal("Sheep");

animalFarm[6] = animalCreator.retrieveAnimal("Sheep");

animalFarm[7] = animalCreator.retrieveAnimal("Sheep");

for (int i= 0; i<=7; i++) {


} // for

The following is the output of the AnimalClient calling different concrete prototype objects.

Cluck cluck World. I am Chicken1. I have 2 legs.
Cluck cluck World. I am Chicken2. I have 2 legs.
Cluck cluck World. I am Chicken3. I have 2 legs.
Cluck cluck World. I am Chicken4. I have 2 legs.
Meeeeeee World. I am Sheep1. I have 4 legs.
Meeeeeee World. I am Sheep2. I have 4 legs.
Meeeeeee World. I am Sheep3. I have 4 legs.
Meeeeeee World. I am Sheep4. I have 4 legs.

Class Diagram Example


  • Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley, 1995

A few interesting Java/Design related talks

Over the last few days I’ve watched a few nice talks, so even if only for future self-reference, I’ll give a list here:

  • OSGi : The Foundation: Talk by Peter Kriens, who is the lead for OSGi. “His pres shows you why a spec like OSGi is crucial, what it really encompasses, and what the future developments will be.
    ” Very interesting since my knowledge on OSGi is (was) sparse at best.I’ll be taking another look at Eclipse RCP and Equinox.
  • Overview of Desktop Java Techs : Talk by Scott Delap who is the author of Desktop Java Live. “Scott Delap provides an overview of Swing and Eclipse RCP technologies in today’s world of RIA applications”
  • Romain Guy on the state of desktop Java : interview with the co-author of Filthy Rich Clients.
  • Joshua Bloch on Closures, Resource Management, Google : Responsible for the Java Collections framework among others in Java, currently responsible for the Java arch @ Google. Quite the Java guru :-)
  • Chet Haase discusses Java FX, Update N and JDK 7 : the other co-author of Filthy Rich Clients.
  • How to design a good API and why it matters : a classic must-see talk by Joshua Bloch. “In this talk (recorded at Javapolis), Java library designer Joshua
    Bloch teaches how to design good APIs, with many examples of what good
    and bad APIs look like.”
  • Desktop Patterns & Data Binding : actually posted this link to a talk by the JGoodies lead a few days back, which I found to be very useful in explaining the organization of view logic in Java Desktop Apps.

Technorati Tags: , , , , , , , ,