Getting To The Java Roots of XPages – Part 8

Anybody who already knows java probably took a look at the java class that I created in the previous parts and saw all kinds of mistakes. This was done on purpose. If I had of shown a bigger java class then the people who are scared of java would have said that they just don’t understand it and would have given up reading these blog posts.

In this and the next few parts I’m going to tidy that class up a bit to make it much more robust. This also demonstrates another key advantage of using java, especially when we get to the stage in the series where we make the java available to all nsf’s.

Taking the getMyInternetAddress method we have now let us imagine that 3 years from now you need to pull the internet address from LDAP rather then from the Domino addressbook. If this java class was shared with all applications on the server it would mean that you just need to update the class to make the ldap connection and retrieve the value. As long as the method name stays the same there would be no need to update a single NSF on the Domino server. That is pretty powerful stuff and a great reason to separate all your business logic from the actual applications.

In terms of tidying up that class the first thing I’m going to do is RECYCLE, RECYCLE, RECYCLE. Even though we are working in Java whenever we get a Domino related object it it really using a C API to get the object, this creates what is known as a handle which is like a bucket dedicated to that Domino object. When I’m finished working with the object I need to tell it I’m finished so that it can release the handle so it can be used by something else. There are only so many of these buckets.

In Lotusscript you didn’t have to worry about this. When the script ended all the objects that you had opened would be automatically told to close and the handles would be released. In both java and ssjs, however, the object handles are not released immediately, this is especially evident in a loop scenario, loop too many documents without releasing the handle each time and the server runs out of handles and crashes. Too many server crashes and your admin will not be very happy.

So one of the first things you need to know about optimizing your java code is that Domino objects should always be recycled as soon as your done with them.

The second thing you need to know is that this only applies to Domino objects. There is no recycle method on non-domino objects. You can, if you want, set non-domino objects to null when your finished with them but java will know when there is nothing using a java object any more and  will take care of things.

To add the recycling to my class I could add the following just after where I get the result

nabDoc.recycle();
nabView.recycle();
nabDB.recycle();
thisDB.recycle();
session.recycle();

But that is not going to work 100% of the time. If something triggered an error, for example the user doesn’t have access the to nab, then the code would jump to the try block and those recycles would never run leaving a session and thisDB object hanging around.

Instead I’m going to use a nice little helper method given to me by Nathan Freeman that is designed to recycle any domino object passed into it. I’m going to add the following method to my AboutMe class :

public static void recycleDominoObjects(Object... args) {
	for (Object o : args) {
		if (o != null) {
			if (o instanceof Base) {
				try {
					((Base) o).recycle();
				} catch (Throwable t) {
					// who cares?
				}
                        }
                }
         }
}

Eeeek! More scary looking java code.

Well public means that this method can be seen from outside the class, static means there only ever needs to be one of these objects so the compiler knows how to optimize itself, void means that it returns nothing. recycleDominoObjects is the name of the methods and here is the interesting one (Object… args) tells it that it can accept any number of object parameters so it doesn’t care if you pass it one parameter or 10 parameters.

The code itself just loops through each object parameter, if the object is not already null it then checks to see what type of object it is using the instanceOf command. Base comes from a package called lotus.domino.Base and all Domino objects are instances of Base. So when it find a Domino object passed into it it will then call the recycle() method on that object.

To call that method from my getMyInternetAddress method I’m going to use a ‘Finally’ block. You have seen the try/catch block, finally is another part of that same pattern and looks like this

try{
    // Do Something here
} catch(Exception e) {
    // Do the error handling here
} finally {
    // Do the cleanup here
}

The finally block runs immediately after both the try block ( if there were no errors ) and the catch block ( if there were errors ) so if always runs regardless and is the perfect place to get rid of those Domino Objects. Here is my new version of the getMyInternetAddress method

public String getMyInternetAddress() {
		System.out.print("AboutMe getMyInternetAddress Called");
		String result = null;

		Session session =null;
		Database thisDB =null;
		Database nabDB =null;
		View nabView =null;
		Document nabDoc =null;

		try {
			session = ExtLibUtil.getCurrentSession();
			thisDB = session.getCurrentDatabase();
			nabDB = session.getDatabase(thisDB.getServer(),
					"names.nsf", false);
			nabView = nabDB.getView("($Users)");
			nabDoc = nabView.getDocumentByKey(session
					.getEffectiveUserName());
			result = nabDoc.getItemValueString("InternetAddress"
		} catch (NotesException e) {
			System.out.print(e);
			result = "No NAB Doc";
		} finally {
			recycleDominoObjects(nabDoc,nabView,nabDB,thisDB,session);
		}
		return result;
	}

You can see the finally block passing in all the possible domino objects into the recycleDominoObjects method. Even if one or more of those objects is null because an error happened before they were created I’m still able to recycle the other Domino objects. You will also notice that I’m declaring the domino objects outside the try/catch/finally block. This is because declaring them inside the try block would mean that they are only available to the try block and would not be accessible to the finally block.

In the next part I’m going to optimize that code even more because it still has some serious issues.

Tagged with: ,
Posted in None

Getting To The Java Roots of XPages – Part 7

In the last part we setup our bean as an unmanaged bean by creating a DataContext and creating the bean in there. To make things even easier you can create what is known as a managed bean. Basically you setup the bean at an application level. You give it a name and scope and tell it what class it is using. Then at the page level you can just reference the bean in EL without having to do anything special.

The setup of the managed bean is done in a properties file called faces-config. In DDE 8.x you can access this file by using the package explorer and looking in the WebContentWEB-INF folder in the nsf. In DDE 9 there is an option in the preferences to show the file in the Application Configuration section of the nsf and I’d recommend that you enable the option.

I’ve added my managed bean as follows


  
    myManagedBean
    scary.java.demo.AboutMe
    view
  
  
  

I only added the <managed-bean> section. The rest was already in the faces-config and whatever you do don’t remove or edit the lines starting with <!–AUTOGEN

Now that the managed bean is setup I can change my link to reference it by name. Here is the XML for the entire xpage I’m using for my demo


	This is an example of a managed bean
	
	
	

When the XPage renderer first hits the Expression Language for myManagedbean it will call the empty constructor and then call the method getMyInternetAddress() to return a value.

So really a managed bean is just a way to pre-define the name and scope for a bean and a bean is just a java class with a few special bits for serialization.

This is not as scary as it seems any more but you have to admit, that java class I wrote is a bit useless so in the next few parts I’ll work on making it a little better and add a few extra methods.

Tagged with: ,
Posted in None

Getting To The Java Roots of XPages – Part 6

So we now have a java class that can be used as a bean. From a java point of view it is still just a java class, the bean bit comes into play over on the xpage side of things.

You may have heard of both managed and unmanaged beans when it comes to XPages. While there are some differences at the end of the day they both point to a java class and do pretty much the same thing. A Managed bean is basically a bean that has been given a name and scope before your xpage runs and is available from any page whereas an unmanaged bean is given it’s name and scope on a specific xpage. I’m over simplifying it for now but eventually I’ll go into more details on that.

Lets use this bean as an unmanaged bean for the moment beans need a scope to be stored in, In ssjs you know these as applicationScope, sessionScope, viewScope and requestScope. For beans there is one more scope called ‘none’ as in no scope, it is not stored and will be discarded after each use.

A quick and dirty way to setup your unmanaged bean is to add a DataContext on your Xpage, here is an example of how to do that


This is not the best way to add a bean to an xpage, it is just being used as a quick and dirty example.

Now for my link i don’t need to use ssjs. I can now use Expression Language. I just reference the unmanaged bean’s name and the method that needs to be called on it.


One thing to note is that the method in the java class is called getMyInternetAddress while the expression language version just uses myInternetAddress. It automatically adds the get and capitalizes the first letter. There is a very valid reason for this that I’ll talk about later.

In the next part, however, we will look at how to setup the java class as a managed bean instead.

Tagged with: ,
Posted in None

Getting To The Java Roots of XPages – Part 5

So in the last part we looked at how to call our new java class from ssjs but that still introduces a tiny bit of overhead as the ssjs interpreter is called to kick off the java code. To avoid using SSJS totally we need to look at something called Expression Language and Beans.

Lets not worry about Expression Language just yet, all you need to know is that you need a bean to make use of it for our purposes.

If you have been doing any XPage development you may have already heard the terms Java Beans and Managed Beans and already think that they are scary things that only the experts know about but you would be wrong. A java bean is just another name for a Class that sits in a package, in fact we have already written one in the previous parts, we just need to make a few small changes to it to become a proper bean.

The first thing you need to know about Beans is that they have to be serializable. What this means is that the xpage processor needs to be able to save state of the bean to either memory or disk and then restore it back whenever needed. So we need to tell our java class that we know about serializing things by using a special keywork on the class called implements.

public class AboutMe implements Serializable {

When you add this to the class the editor will prompt you for two things. First you need to import the package that Serializable exists in

import java.io.Serializable;

and in the class itself you need to declare a variable called serialversionID. The editor will help you with this automatically and this is what it looks like…

private static final long serialVersionUID = 1L;

Eeek! Scary Java Alert! What does all that mean?

Private means that this variable can only be seen by this class. It is not visible outside the class.

Static means that is variable will only exist once in memory. If you have multiple beans pointing to this java class then this particular variable will only exist in memory once.

Final means that this value will never change once assigned ( which we do after the = sign ). This allows the java compiler to better optimize it’s code because it now know that the value will never change.

Long is just the data type ( like int, String etc ).

and 1L is the value we are assigning. The L is shorthand for Long. Without the L it would try assign an int of 1 to the variable.

See that’s not so scary.

Next we need what is called an empty constructor. Every java class that needs to be uses as a bean needs one. When the bean is first called the constructor is automatically called with no parameters, thus the name Empty Constructor.

Inside the your class you need to add

public AboutMe() {
	// Constructor Code Here	
}

Now the name Empty Constructor seems to imply that it can’t have any code in it but that is not 100% correct. You could put some code in here, it just can’t accept any parameters and it doesn’t return any values.

Do we have a bean yet? Not really, we have a java class that can be used as a bean. In the next part we will show how to use this java class as a bean in the xpage environment.

Tagged with: ,
Posted in None
Archives