Setting a Conditional on a Breakpoint in Eclipse

Sometimes when you are debugging your program in Eclipse you will be using breakpoints within program loops. What can be really frustrating is when this loop is really large and the particular iteration you are interested is hundreds of iterations away.

Assume we are debugging the following program and we are only interested in stepping through the for loop when i==500.

The two most common naive approaches would be to step through the loop 500 times by pressing the green arrow 500 times, or you could add an if conditional statement directly into the code and shift the breakpoint onto this conditional.

However the first approach will give you repetitive strain injury and the second approach will make a mess of your code.

If you select your breakpoint in the breakpoints view in Eclipse you will see that a panel with options becomes visible for that particular breakpoint. You can select hit count, and add a numerical value into the text field. This means the breakpoint will be ignored this many times before being suspended again.

Another option is to enter in a conditional statement. Below the “Choose a previously entered condition” drop down, you should see a text area (You may need to make the view a bit bigger to see it). This text area is free text so you can enter anything you wish, although the debugger will complain if you enter in variables that don’t exist.

Now when this breakpoint is visited AND this condition is true, the breakpoint will be suspended.

 

 

 

 

 

 

 

Posted in Eclipse | Tagged , , , | Leave a comment

GridBagLayout Tutorial

This tutorial shows you how to construct a complex Java Swing GUI using the GridBagLayout.

Let’s assume you have received a protoype sketch of how an application screen should look like, which you have been assigned to create :

It is a fairly complex user interface screen with a number of different controls, and with different component regions. Let’s sketch some lines to represent grid lines. Our GridBagLayout has gridX and gridY constraints which can be associated with the components we have sketched in our grid.

If we think about it for a while, we can see that not all regions fit into a grid cell, some regions spread into two cells (marked in blue) :

 

We can make the GridBagLayout make these two blue regions cover more than one cell using the gridWidth and gridHeight constraint.

***

So… let’s create a basic first cut of our GUI. The following code sets up the main components in the frame using GridBagLayout. At the moment we don’t have any components in the details panel to the right, so we will add a border on an empty panel to get a visual on where it should be on the frame.

public class GridBagDemo1 extends JFrame {

	public GridBagDemo1(){
		initGUI();
	}

	public void initGUI() {

		setTitle("");

		JPanel panel = new JPanel(new GridBagLayout());
		this.getContentPane().add(panel);

		JTable t = new JTable(null);

		JLabel label = new JLabel("My Things");

		JPanel tableButtonPanel = new JPanel();
		tableButtonPanel.add(new JButton("Add Thing"));
		tableButtonPanel.add(new JButton("Delete Thing"));
		tableButtonPanel.add(new JButton("Modify Thing"));

		JPanel buttonPanel = new JPanel();
		buttonPanel.add(new JButton("Print"));
		buttonPanel.add(new JButton("History"));
		buttonPanel.add(new JButton("Preferences"));
		buttonPanel.add(new JButton("Another Button"));
		buttonPanel.add(new JButton("Add Another"));
		buttonPanel.add(new JButton("Yet Another"));

		JPanel detailsPanel = new JPanel();
		detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

		GridBagConstraints gbc = new GridBagConstraints();

		gbc.gridx = 0;
		gbc.gridy = 0;

		panel.add(label, gbc);

		gbc.gridx = 0;
		gbc.gridy = 1;
		panel.add(new JScrollPane(t), gbc);

		gbc.gridx = 0;
		gbc.gridy = 2;
		panel.add(tableButtonPanel, gbc);

		gbc.gridx = 0;
		gbc.gridy = 3;
		gbc.gridwidth = 2;
		panel.add(buttonPanel, gbc);

		gbc.gridx = 1;
		gbc.gridy = 1;
		gbc.gridwidth = 1;
		gbc.gridheight = 2;
		panel.add(detailsPanel, gbc);

		this.pack();

		this.setVisible(true);
	}

	public static void main(String[] args) {
		GridBagDemo1 frame = new GridBagDemo1();

		frame.pack();
		frame.setVisible(true);
	}
}

Notice how one GridBagConstraint object is being created and being passed in with the component to the main panel? This constraint object holds all the information to how a component should be displayed. In our first cut, we are only interested in X and Y placement, and spans, so we set gridX and gridY on all the first level components we are adding. For our button panel at the bottom we set the gridWidth to 2, indicating that we want it to spread to the right by one more grid cell, and likewise with the details panel we want it to spill over into two cells. It is important to reset any constraint values (such as gridWidth) because we are dealing with only one constraints object.

Now when we run our program we will see this :

Well, it’s a start..

The two rows of buttons are looking good. Per default JPanels have a FlowLayout, laying out components from left to right in a centered fashion. This looks good for what our requirements are. Of course our label at the top needs to be left aligned, and our table would be good if it had some data in it.

We can anchor our label to the left quite easily by adding an anchor constraint.

 gbc.anchor = GridBagConstraints.WEST; 

Lets move on to our details panel on the right. This panel will also use a GridBagLayout, so we will effectively have two nested GridBagLayouts in our application frame. We’ll create this panel in a separate method, and add this panel to where our empty panel with the border was. In this first cut lets just concern ourselves with gridX and gridY constraints :


private JPanel createDetailsPanel() {

		JPanel panel = new JPanel();

		JLabel thingNameLabel = new JLabel("Thing Name");
		JLabel anAttributeLabel = new JLabel("An Attribute");
		JLabel dateFieldLabel = new JLabel("Date Field");
		JLabel anAttLabel = new JLabel("An Att");
		JLabel anotherAttLabel = new JLabel("Another Att");
		JLabel anotherAtt2Label = new JLabel("Another Att");

		JTextField thingNameField = new JTextField("Thing Name");
		JTextField anAttributeField = new JTextField("An Attribute");
		JTextField dateFieldField = new JTextField("Date Field");
		JTextField anAttField = new JTextField("An Att");
		JTextArea anotherAttField = new JTextArea("Another Att");
		JTextField anotherAtt2Field = new JTextField("Another Att");

		JCheckBox checkbox1 = new JCheckBox("A Checkbox");
		JCheckBox checkbox2 = new JCheckBox("A Checkbox");

		panel.setLayout(new GridBagLayout());

		GridBagConstraints gbc = new GridBagConstraints();

		int i=0;

		gbc.gridx = 0;
		gbc.gridy = i;
		panel.add(thingNameLabel,  gbc);

		gbc.gridx = 1;
		gbc.gridy = i;
		panel.add(thingNameField,  gbc);		

		i++;

		gbc.gridx = 1;
		gbc.gridy = i;
		panel.add(checkbox1,  gbc);

		i++;

		gbc.gridx = 0;
		gbc.gridy = i;
		panel.add(anAttributeLabel,  gbc);

		gbc.gridx = 1;
		gbc.gridy = i;
		panel.add(anAttributeField,  gbc);		

		i++;

		gbc.gridx = 0;
		gbc.gridy = i;
		panel.add(dateFieldLabel,  gbc);

		gbc.gridx = 1;
		gbc.gridy = i;
		panel.add(dateFieldField,  gbc);		

		i++;

		gbc.gridx = 0;
		gbc.gridy = i;
		panel.add(anAttLabel,  gbc);

		gbc.gridx = 1;
		gbc.gridy = i;
		panel.add(anAttField,  gbc);		

		i++;

		gbc.gridx = 0;
		gbc.gridy = i;
		panel.add(anotherAttLabel,  gbc);

		gbc.gridx = 1;
		gbc.gridy = i;
		panel.add(anotherAttField,  gbc);

		i++;
		gbc.gridx = 0;
		gbc.gridy = i;
		panel.add(anotherAtt2Label,  gbc);

		gbc.gridx = 1;
		gbc.gridy = i;
		panel.add(anotherAtt2Field,  gbc);

		gbc.gridx = 2;
		gbc.gridy = i;
		panel.add(checkbox2,  gbc);

		return panel;
	}

A useful technique is to use variables for X and Y coordinates. In our details panel, I have used an ‘I’ variable for the Y position. This makes it extremely easy to add extra fields at a later point in time.

Now lets see what we get :

Pretty awful huh..

All the components are in their correct X and Y positions but the width has to be fixed. The checkbox at the bottom is in its own separate column, so we need to stretch the text fields over to the right. We do this by setting the gridWidth property to two for those fields that we want to stretch over.

Set the width like this

gbc.gridwidth = 2;

remembering to set it back when you get to the labels!

gbc.gridwidth = 1;

Remember also that both label and field at the bottom have to have a width of one.

Now if we run it, it still looks terrible, but at least we see that we have three columns with most of the text fields sitting over the last two columns. Our text fields also need to ‘fill’ their space, so let’s add horizontal fill to the text fields, remembering to reset when we come to the labels.

gbc.gridx = 1;
gbc.gridy = i;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL; 
panel.add(thingNameField,  gbc);

i++;
gbc.gridx = 0;
gbc.gridy = i;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;  
panel.add(anAttributeLabel,  gbc);

Lets put our TextArea in a Scrollpane and add some dimensions.

JTextField anAttField = new JTextField("An Att");

JTextArea anotherAttField = new JTextArea(2, 10);
JTextField anotherAtt2Field = new JTextField("Another Att");

The columns dimension in our text area will be overridden by our GridBagLayout, however our rows value (of 2) will not.

Lets also add Insets :

gbc.insets = new Insets(2,2,2,2);

If we set them once at the top, they will flow through to all components.

Now the right side of our frame is starting to look much better :

All out labels should be aligned to the top-right (or NORTHEAST in gridbag speak)

gbc.insets = new Insets(2,2,2,2);
gbc.anchor = GridBagConstraints.NORTHEAST;

We can put this alongside the insets (to affect all components) because our anchor does not affect our text field components, only our labels, since they have no FILL set.

The details panel is also hovering vertically in the center which doesn’t really look that good. We need to anchor the details panel to the NORTH on the outer GridBagLayout.

gbc.gridx = 1;
gbc.gridy = 1;

gbc.gridwidth = 1;
gbc.gridheight = 2;
gbc.anchor = GridBagConstraints.NORTH;
panel.add(createDetailsPanel(), gbc);

Our table should also stretch out in both directions, effectively swallowing up any space that may be available.

gbc.anchor = GridBagConstraints.CENTER;

gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH; 
gbc.weightx = 1.0; 
gbc.weighty = 1.0; 
panel.add(new JScrollPane(table), gbc);

Weight X and weight Y should be set to 1.0 to prevent the table from collapsing upon a resize event.

Refactor out the ScrollPane and give it a preferred size. This gives you a bit of control over the fill of the table and scrollpane.


JTable table = new JTable(data, columnNames);
JScrollPane tableScrollPane = new JScrollPane(table);
tableScrollPane.setPreferredSize(new Dimension(200, 50));

If you find some of the text fields on the right are collapsing, add some column width via the integer parameter when constructing text fields :

JTextField anAttField = new JTextField("");
JTextArea anotherAttField = new JTextArea(3, 1);
JTextField anotherAtt2Field = new JTextField("", 10);

You should end up with something like this :

 

TIPS.

  • Because of all the switching around from one column to the second column. Ie resetting things like fills and anchors, it could be good idea to have 2 GridBagConstraint objects, one for each column
  • Textfields, textareas and tables should never collapse after the frame has called pack(). The collapse happens when the components size switches from preferred to minimum. This can be caused by a number of reasons. If you find textfields collapsing after resize then you should set their mimimum size to its preferred size :
textField.setMinimumSize(textField.getPreferredSize());

source code

Posted in Swing | Tagged , , , , | 5 Comments

java.lang.VerifyError: Illegal target of jump or branch … possible cause!

I got this error the other day. It usually happens when you have crazy methods which are too long. But in my situation that wasn’t the case. I found out through trial and error that I was throwing a RuntimeException which it didn’t like.

All I had in my code was :

        if(true)
        	throw new RuntimeException("TODO implement this"); //TODO

This somehow confused my compiler, probably because it realised that there was unreachable code after throwing this runtime. You need to trick the compiler better by throwing a RuntimeException like this :

        if("string".equals("string"))
        	throw new RuntimeException("TODO implement this"); //TODO

This solved my VerifyError problem in my case anyway…

Posted in Uncategorized | Tagged | Leave a comment

UML Fundamentals Exam. A few tips on passing..

I just recently passed the OMG UML fundamentals exam with 81%.

Here are some tips :

  • Make sure you can decipher a sequence diagram with asynchronous messages that cross over each other (ie. are not parallel to each other). A number of combinations of message sequences are possible (the UML books all use this !p p? r! r? notation), and I came across a few questions asking what sort of combinations are possible. The general rule I use is that the start of the message must come before the end of the message (obvious!), and the events occuring in a lifeline must occur sequentially downwards.
  • Understand what a General Ordering is in sequence diagrams, and how does that restrict combinations of message sequences in sequence diagrams?
  • A particularly mean question came up which was testing knowledge of Use Cases relationships. Easy up to a point, but then you have to know if there is an ‘s’ at the end of the name. ie is it extend or extends, and is it include or includes
  • Some other questions were also a bit mean, where they assumed you understood the textual positioning in symbols. Ie. You should know if the text goes above or below the symbol for things like Use Case, Class symbol, and Actor.
  • Rectangles in activity diagram. Understand what the different rectangles mean. What do they mean when they sit on the boundary of the activity? What do they mean when they sit between two actions? And how does that relate to pins that you sometimes see on actions? Do they mean the same thing?
  • Understand the Metamodels. As boring as it sounds, you really need to have a good idea in your head as to how UML is defined in the metamodels. I think its impossible to memorise all the diagrams, but try and take something away from each diagram. For example how does the Use Case metamodel and the Class metamodels overlap? Why is RedefinableElement in both?

Here are a couple of good links which make a nice adjunct to your Wilkiens/Oestereich certification book :

http://www.uml-diagrams.org/
http://www.zicomi.com/viewDictionaryHome.jsp

Good luck!

Posted in UML | Tagged , , , | Leave a comment

Swing and Design Patterns – Part 3. Command Pattern

Command Pattern.
The command pattern is a commonly used pattern which encapsulates a method call or action-like code into a single class. The advantages of being able to package a method (or methods) into a class become evident when you have multiple invokers for a single action (for example a button and a menu item may perform the same action).

Swing uses the concept of the command pattern through the use of ‘Actions’. In Swing you create your actions by extending Swing AbstractActions. The code implemented in the actinoPerformed method is the code to be executed once the action has been fired. It’s really just a fancy realisation of the ActionListener interface adding some extra functionality such as mnemonics and accelerator keys.

public class SimpleAction extends AbstractAction {

	public SimpleAction(){
		super("This is simple"); //shows up in menu item or on button
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		//do something
	}

}

An instance of SimpleAction can then be assigned to a menu item or a button.

myButton.setAction(new SimpleAction());

Updating the GUI and Method Invocation

In my experience there are two key things that need to passed into the action. The first is a reference to the application’s main frame, which contains references to all other components in the application. (If you don’t understand the concept of a GUI hierarchy, you can visualise the main application frame as the trunk of a tree through which it is possible to get references to any other component further down in the branches).

Having a handle on the main frame allows you to perform any kind of GUI action, for example refreshing a table, updating text in a label, switching indicators on or off. Swing Actions execute their behaviours in the event dispatch thread, so threading issues should not be of concern.

The second thing to pass in is the delegate (or facade), that is, the class or classes which control communication from the application to outside systems. The delegate simply provides the method call that the action is really encapsulated around.

My ideal Action would look something like this :

public class UpdateStockItem extends AbstractAction {

	private ShopDelegate server;
	private MainFrame frame;

	public UpdateStockItem(ShopDelegate delegate, MainFrame frame) {

		super("Update Stock Item");
		this.server = delegate;
		this.frame = frame;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		StockItem item = frame.getStockPanel().getStockItem();

		try {
			server.updateStockItem(item);

		} catch (ServerException e1) {

			JOptionPane.showMessageDialog(frame, "" + e1.getMessage(),
					"Error saving stock item", JOptionPane.ERROR_MESSAGE);
			return;
		}
		frame.updateBackgroundTable();
	}
}

All exceptions should be handled within the action, showing error dialogs when appropriate. The action should encapsulate the method call and all exceptional situations that may arise.

Deviations from the Norm

Of course there are deviations from this. Inside the body of an action you might call multiple delegate calls, or you might even want to “fire and forget” by not having any GUI interaction at the end of the action. There is no concrete definition of what an action is, and what is a collection of actions bundled into one action. For example, do you create a ‘Cancel’ action for a simple dialog? Or should the activity that sits behind the dialog (and all its permutations) reside in its own action?

An swing action can be more broad and can take into consideration a number of actions (or activity). This avoids too many classes, and maps closer to a User Case than with a specific action. For example a Use Case like ‘Manage Settings’ could be handled within one Swing Action class :

public class ManageSettingsAction extends AbstractAction {

	private ShopDelegate delegate;
	private MainFrame frame;

	public ManageSettingsAction(ShopDelegate delegate, MainFrame frame) {

		super("Manage Settings");
		this.delegate = delegate;
		this.frame = frame;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		ManageSettingsDialog dialog = new ManageSettingsDialog(frame, delegate);

		Utils.centerDialogOnFrame(frame, dialog);
		dialog.setModal(true);
		dialog.setVisible(true);

		Color color = dialog.getBackgroundColour();

		long pollingMilliseconds = dialog.getPollingTime();

		long maxUsersAllowed = dialog.getMaxUsersAllowed();

		try {
			delegate.updatePollingTimeOnServer(pollingMilliseconds);

			delegate.setMaxUsersAllowed(maxUsersAllowed);

			if (color == Color.BLACK || color == Color.GRAY)
				throw new RuntimeException(
						"The colours you selected for the background are not nice enough");

			frame.setBackgroundColorScheme(color);

		} catch (ServerException e1) {

			JOptionPane.showMessageDialog(frame, "" + e1.getMessage(),
					"Error updating polling time", JOptionPane.ERROR_MESSAGE);
			return;
		} catch (Exception e1) {

			JOptionPane.showMessageDialog(frame, "" + e1.getMessage(),
					"Error updating polling time", JOptionPane.ERROR_MESSAGE);
			return;
		}

		frame.expandTree();
	}
}

Linking Actions

You can link up actions in Swing. There is nothing profound in how to call the next action. Simply code your action like this, making a call to another action :

	@Override
	public void actionPerformed(ActionEvent e) {

		// do stuff

		// update gui

		new ManageSettingsAction(delegate, frame).actionPerformed(null);

	}

It may seem a bit ugly at first, but it makes sense in most situations. Assuming that you are not interested in the ActionEvent. You are still in the Event Dispatch Thread when you call the second action. The second action does not need to know about the calling action. Of course, you have to make sure that you are not looking at the action events because you are passing in a null.

Posted in Design Pattern | Leave a comment

Swing and Design Patterns – Part 2. Delegate Pattern

Lets look at our diagram again and examine another pattern.

Delegate Pattern (aka Facade)

The delegate or facade pattern should be the backbone of all java Swing application (for that matter, not just Swing, but any desktop application that needs to communicate over a network such SWT, C# apps, etc. should also use this pattern). The pattern aggregates all application calls to the outside world within one class. This has a number of advantages.

  • The delegate pattern presents a clear snapshot of communication from the front end to the backend, or the inside to the outside world, making the system more understandable and maintainable to other developers.
  • It decouples the client side application from other systems. The application does not need to know any details about the externally interfacing server or servers, and does not need to understand the modes of communication.

The delegate pattern should consist of a class that looks something like this :

public class DelegateSimple {

	RemoteInterface remoteInterface;

	private static final DelegateSimple INSTANCE = new DelegateSimple();

	private DelegateSimple() {
		remoteInterface = new RemoteInterface();
	}

	public static DelegateSimple getInstance() {
		return INSTANCE;
	}

	public ArrayList getAllPatients(){
		return remoteInterface.getAllPatients();
	}
	public Patient getPatient(String id){
		return remoteInterface.getPatient(id);
	}
	public void updatePatient(Patient p){
		remoteInterface.updatePatient(p);
	}
	//getPatientRecords()
	//getAllRecords()
	//getDoctors()
	//getNurses()
	//etc..

}

…which can have dozens (if not a hundred plus) other method calls.

The delegate is a thread safe singleton created via a thread-safe static getInstance() method. As Swing applications can have many threads running at the same time, it is important to make this thread-safe.

The remote interface class variable in the previous example is intended to be an abstract placeholder (You would generally have to make a decision on how to implement this remote interface). But generally the remote interface is stub code that communicates with an external system.

RMI Example

Assuming that the delegate hooks up to a single delegating EJB session bean, a simple RMI Example would look something like :

class DelegateRMI {

	private PatientHome patientHome;
	static private Context initialContext;

	private DelegateRMI() {
		try {

			String remoteJNDIName = PatientHome.JNDI_NAME;

			Object objRef = initialContext.lookup(remoteJNDIName);

			Object obj = PortableRemoteObject.narrow(objRef,
					PatientHome.class);

			patientHome = (PatientHome) obj;

		} catch (NamingException e) {
			e.printStackTrace();
			UIManager.getInstance().showErrorDialog(e.getMessage());
		}
	}

	public static DelegateRMI getInstance() {
		return INSTANCE;
	}
	private static final DelegateRMI INSTANCE = new DelegateRMI();

	public Patient getPatient(String id){
		return patientHome.getPatient(id);
	}
//etc..
}

Pretty messy.. huh? What happens if you want to interface to more session beans? What happens if some methods call a web service?

Web Services Example

Web services offers a much cleaner interface in respect to service creation, however it contains a lot of generated code that may not be compatible with the client business code. It is always important not to let these generated artifacts contaminate further past the delegate and into the client code.

public class DelegateWS {

	//generated by the JAX-WS RI.
	ExternalHospitalPort port = null;

	private DelegateWS() {

	    //generated by the JAX-WS RI.
	    ExternalHospitalService service = new ExternalHospitalService();

	    port = service.getExternalHospitalPort();

	}

	public static DelegateWS getInstance() {
		return INSTANCE;
	}
	private static final DelegateWS INSTANCE = new DelegateWS();

	public IPatient getPatient(String id){

	    //generated by the JAX-WS RI.
	    PatientManifest patientManifest = new PatientManifest();
	    patientManifest.setId(id);

	    //generated by the JAX-WS RI.
	    PatientResponse patientResponse = port.getPatient(patientManifest);

	    //need to convert to out own business domain beans
	    IPatient patient = convertToLocalBean(patientResponse);

	    return patient;
	}
	//etc
}

Notice how the generated response (ie. patientResponse) is converted to the local domain code.

Service Locator

If you are dealing with diverse external systems, generally you would want to use a J2EE pattern called a service locater.

This can add another layer of abstraction to your delegate, so make sure you only use the service locater pattern if you need to. If you are just communicating with one session bean on the server side then it is probably not necessary.

Example :

class DelegateWithServiceLocator{

	private DelegateWithServiceLocator()
	{} 

	public static DelegateWithServiceLocator getInstance() {
		return INSTANCE;
	}
	private static final DelegateWithServiceLocator INSTANCE = new DelegateWithServiceLocator();

	public Patient getPatient(String id){

		PatientHome patientHome = ServiceLocator.getPatientInterface();
		return patientHome.getPatient(id);

	}

	public IPatient getExternalPatient(String id){

	    //generated by the JAX-WS RI.
	    PatientManifest patientManifest = new PatientManifest();
	    patientManifest.setId(id);

	    ExternalHospitalPort port = ServiceLocator.getExternalHospitalPort();

	    //generated by the JAX-WS RI.
	    PatientResponse patientResponse = port.getPatient(patientManifest);

	    //need to convert to out own business domain beans
	    IPatient patient = convertToLocalBean(patientResponse);

	    return patient;
	}
	//etc..
}

The service locater uses lazy loading to cache service connections as they are needed. The benefit of the service locator is that the delegate is under the illusion that it is still only communicating with only one external interface.

Exception Handling and Caching

Before polluting the Swing GUI with unexpected behavior, the delegate can cleanly intercept all exceptions and throw out an error dialog in an appropriate manner.

public class Delegate {

	RemoteInterface2 remoteInterface;

	private static final Delegate INSTANCE = new Delegate();

	private Delegate() {
		remoteInterface = new RemoteInterface2();
	}

	public static Delegate getInstance() {
		return INSTANCE;
	}

	public ArrayList getAllPatients() {

		try {           
			return remoteInterface.getAllPatients();
		} catch (RemoteException e) {
			UIManager.getInstance().showErrorDialog(
					"Remote Error getting all patients");
			log(e);
		} catch (Exception e) {
			UIManager.getInstance().showErrorDialog(
					"General Error getting all patients");
			log(e);
		} 
		return null;
	}

	public Patient getPatient(String id) {
		try {
			return remoteInterface.getPatient(id);
		} catch (RemoteException e) {
			UIManager.getInstance().showErrorDialog(
					"Remote Error getting patient " + id);
			log(e);
		} catch (Exception e) {
			UIManager.getInstance().showErrorDialog(
					"General Error getting patient " + id);
			log(e);
		}
		return null;
	}

	public void updatePatient(Patient p) {
		try {
			remoteInterface.updatePatient(p);
		} catch (RemoteException e) {
			UIManager.getInstance().showErrorDialog(
					"Remote Error updating patient " + p.getId());
			log(e);
		} catch (Exception e) {
			UIManager.getInstance().showErrorDialog(
					"General Error updating patient " + p.getId());
			log(e);
		}
	}

	// etc
}

Of course my code here is a simplification. You could have a single catch if you wanted. If you are dealing with transactions on the client side (An example of a GUI transaction would be displaying two lists – or tables or whatever – from two different calls. If either fails, then nothing should be shown), then showing an error dialog should be managed outside of the delegate layer.

The delegate is a good place to place exception handling, and it is also a good place to put any necessary caching. For example

private Map countries = null;

	public Map getCountries(){

		if (countries == null) {
			ExternalCountriesPort port = ServiceLocator.getExternalCountryDataPort();
			countries = port.getCountries();
		}
		return countries;
	}

If caching gets out of control inside your delegate class, then consider abstracting that responsibility into another layer.

Final Points

  • If the delegate needs to communicate with multiple service points, consider a Service Locater pattern
  • Consider making the delegate the point where exceptions will stop, be logged, and converted into a GUI notification.
  • Avoid placing transactional code in the delegate calls. Transactions for data integrity should exist on the servers inside persistence layers and such. Transactions in the GUI (yes transactions can exist in the applications!), should be handled deeper within the GUI code, and not in the delegate class.
  • Put any reasonable caching inside the delegate. If the caching becomes excessive, abstract it into a CacheManager class.
  • At the end of the day the delegate should be clean, cohesive, and present an unambiguous snapshot of what goes in and out of the client.

I hope this article makes sense. Flame me or love me in the comments section.

Posted in Design Pattern | Tagged , , , , , , | Leave a comment

Swing and Design Patterns – Part 1. Decorator Pattern

I am going to talk a little about my experiences with design patterns, specifically when building a Swing application.

Being the visual guy that I am, I decided to put together a little visual schematic showing the four most important (in my opinion) design patterns that should be applied when building your typical Java Swing application :

They are :

  • Mediator Pattern
  • Command Pattern
  • Delegate Pattern
  • Decorator Pattern

In this first part, out of the proposed four part blog, I am going to talk about the decorator pattern.

Decorator Pattern

The decorator pattern can facilitate the rendering of a business model bean in the context of the MVC pattern. The decorator wraps or masks the bean and can present the bean in a certain way for a particular GUI component.

The pattern deals with ‘decorating’ a business model bean with one or more decorators. The decorators can add, remove, enhance or modify properties of the bean they are masking. This reduces work that a renderer (the View) might need to do.

Examples what a decorator might do :

  • Modify the formatting of a date.
  • Derive an extra field. Eg: Age from date of birth
  • Hide unnecessary fields (useful when doing data binding on, for example, a table)

The decorator pattern can also be used to enhance GUI components (in the context of painting over), although I won’t be talking about that here.

The classic approach is to have an interface defined like this :

	interface IPatient{

		public String getId();
		public String getFirstName();
		public String getLastName();
		public Date getDob();
	}

A normal business bean called Patient.java will implement this interface. A decorator class will also implement this interface, such as in the following code :


	class PatientDecoratorTable implements IPatient{

		private IPatient patient;

		public PatientDecoratorTable(IPatient patient) {
			this.patient = patient;
		}
		public String getId() {
			return "#" + patient.getId();
		}
		public String getFirstName() {
			return patient.getFirstName();
		}
		public String getLastName() {
			return patient.getLastName();
		}
		public Date getDob() {
			return patient.getDob();
		}
		public String getFullName() {
			return patient.getFirstName() + " " + patient.getLastName();
		}
		public int getAge() {
			Calendar dob = Calendar.getInstance();
			dob.setTime(patient.getDob());
			Calendar tdy = Calendar.getInstance();
			int age = tdy.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
			if (tdy.get(Calendar.DAY_OF_YEAR) <= dob.get(Calendar.DAY_OF_YEAR))
				age--;
			return age;
		}
	}

tables

The decorator pattern is very useful when used with Swing tables. In the above example the decorator functions as a wrapper. An extra column called ‘Age’ can be added to the table and render this newly derived field, using the appropriate wiring in the table model.

If the derived field requires a lot of processing then it can perform its processing during object construction, storing its value in a new field. This new field can then be accessed just like all the other values. For example:

public int getAge() {
	return calculatedAge;
}

This reduces the work that the cell rendering has to do, which can be intense if a user is often scrolling through a table.

Hiding Fields?

Although the classic approach in using the decorator pattern uses a common interface between the bean and decorator; I find that sometimes that is unnecessary.

It is sometimes sufficient to pass the bean through the constructor. Using the pattern this way allows the hiding of unwanted fields, for example maybe in our table example we don’t care about date of birth, however we want to show the patient’s age.

NOTE: Hiding fields is especially useful using databinding : Especially when databinding uses reflection on all the getter methods.

Decorate your Tree

Decorators can be used when displaying data in JTrees :

	class PatientTreeDecorator implements IPatient{
		IPatient patient;

		public PatientTreeDecorator(IPatient patient) {
			this.patient = patient;
		}

		public String getId() {
			return patient.getId();
		}
		public String getFirstName() {
			return patient.getFirstName();
		}

		public String getLastName() {
			return patient.getLastName();
		}

		public Date getDob() {
			return patient.getDob();
		}

		public DefaultMutableTreeNode getPatientNodeBranch() {

			DefaultMutableTreeNode base = new DefaultMutableTreeNode(this);

			base.add(new DefaultMutableTreeNode(getLastName()));
			base.add(new DefaultMutableTreeNode(getFirstName()));
			base.add(new DefaultMutableTreeNode(getDob()));

			return base;
		}

		public String toString(){
			return patient.getId();
		}

	}

In the above example the decorator is also responsible for organizing representation of its internal bean in the form of a tree branch structure. The method getPatientNodeBranch() can be used when attaching the object to a tree node like this :

	for (IPatient patient : cardiacPatients) {
		cardiacPatientsNode.add(new PatientTreeDecorator(patient).getPatientNodeBranch());
	}

The decorator pattern (using a common interface) allows for the nesting of decorator implementations. You could have a decorator for your table, and have this nested inside your decorator for your tree.

Posted in Design Pattern | Tagged , , , | Leave a comment

UML Tip: XOR in UML

Reading through the UML specifications I came across the XOR constraint (a UML predefined constraint). Thinking this would make a nice UML Tip nugget, I tried to dig deeper into this obscure little creature.

Lets have a look at four diagrams :

XOR (or an exclusive OR) is the only logical operator allowed in the UML, and is used on two or more discriminators (associations). It in effect is saying that only one of the two associations can exist at any one time.

Diagram 1. The first diagram shows how you would apply the XOR constraint to a UML diagram. Place the XOR in curly brackets and then link it up to the associations with dotted lines. The application of the XOR constraint makes sense in this first diagram, because a student can only attend one school at any one time. A particular student exclusively attends one or the other of these two schools. ‘Attends’ is an interesting word, however in my case, it is not saying that the student is physically inside the school grounds when it is attending. ‘Attends’ is a broader concept and does not involve the physicality of the student being somewhere. It is a bit like the word ‘Enrols’.

Diagram 2. The second diagram shows where you wouldn’t use the XOR constraint. In reality a student may apply to more than one university, so the XOR constraint would be wrong here.

Diagram 3. The third diagram shows an alternative to the first diagram. We can remove the two associations to the two schools and have only one association to the super class ‘School’. It is worth thinking about whenever you use a XOR constraint on two or more associations; should a single association with the super class replace the multiple associations? Is the XOR constraint indicative of a missing class?

Diagram 4. The fourth diagram shows a situation where you can’t generalize the associations. I guess, a true example where you would use the XOR constraint. Assuming that someone in this situation can either go to school or work (no after school jobs are allowed).

Posted in UML | Tagged , , | 1 Comment

Why Implements is ‘Evil’

I stumbled across this really old article titled ‘Why Extends Is Evil’ by Allen Holub.
A solid bunch of OO practitioners out there seem to think along the lines of what this article is stating, namely, that using ‘extends’ is bad, and you should rather implement interfaces. The problem I have with this view is that I have come across a lot of software engineers out there who follow this view, but to a degree that they seem to be suffering from a kind of ‘implementitis-syndrome’.

Exhibit A :

The above diagram comes from a project I had the misfortune of working on for a company that will remain nameless. The architecture of the system shocked me so much when I first started on the project that I had to write down the UML diagram, to figure out what the hell was going on. Everything in this diagram is an interface save for about 3 classes that I have coloured blue. There obviously was some ridiculous interface bloat going on, also everything could probably be represented in only two or three interfaces or super classes.

My point is that, had this ball of mud contained an ‘extends chain’ going straight through the middle of this diagram, while still looking pretty awful, it would have started to make a bit more sense.

Extends adds semantic structure. Rather than looking like a tumbleweed, your class diagram would look more like a tree. The classes extending each other act like the tree trunk.

Extends also adds semantic meaning. An extends relationship is a IS A relationship, and implements relationship is a IS LIKE A relationship. Interfaces should end in “-able” (Runnable, Clonable), because they are defining a characterisitic about the object. You wouldn’t have a car implement a vehicle.. that is clearly an IS A relationship.

If you were to define everything as an interface. Everything just becomes vague mush.

Holub talks about a ‘fragile base class problem’. I think you can avoid this problem by making all classes that get extended from abstract. A developer is not going to be as inclined to play around with the internals of an abstract class; the developer knows that classes extend from it. I also think that liberal use of abstract methods prevents the base class from being fragile. In essence really, I think overriding non-abstract methods is the real problem in this story.

At the end of the day you should really try and avoid inheritence, and only use it when things can’t be done with composition. But my tip would be to leave implements out of the picture until you find a proper inheritence structure using extends.

Posted in Uncategorized | Tagged , , , , , | Leave a comment

Advanced Swing Multithreading Tutorial

A lot of Swing tutorials on the internet focus on SwingWorkers and dealing
with a single thread running concurrently to the Event Dispatch Thread (EDT). This tutorial is going
to look at some more tricky techniques and traps that one might encounter
when dealing with numerous threads updating the GUI.

In this tutorial we will assume that we want a table that displays a number
of rows. Behind each of these rows a process should exist which will be updated by
some background thread, and we want to reflect these updates in the table. In
effect we are dealing with x-number of threads running in the background and
updating x-number of cells in a JTable.

screen example :


Part 1. Create the Swing Application First

Firstly lets assume we have some simple bean called Process. This entity will characterise the process that we will be dealing with.

Process.java.

	class Process {

		public Process(String name, int progress, String description) {
			super();
			this.name = name;
			this.progress = progress;
			this.description = description;
		}

		String name;
		int progress;
		String description;
	}

We want this process to have its progress value updated by some
background thread. In our example we want our process updated in random increments to 100.

Now lets create a table model for our JTable, which will display these process entities.

ProcessTableModel.java.

	private ArrayList processList = new ArrayList();

	class ProcessTableModel extends AbstractTableModel {

		private String[] columnNames;

		public ProcessTableModel() {

			columnNames = new String[] {"Process", "Progress", ""};
			for (int i = 0; i < 200; i++) {
				processList.add(new Process("Process " + i, 0, "Description"));
			}
		}

		public Process getProcessAt(int row2) {
			return processList.get(row2);
		}

		public int getColumnCount() {
			return columnNames.length;
		}

		public int getRowCount() {
			return 200;
		}

		public String getColumnName(int col) {
			return columnNames[col];
		}

		public Object getValueAt(int row, int col) {

			Process p = processList.get(row);

			switch (col) {
			case 0:
				return p.name;
			case 1:
				return p.progress;
			case 2:
				return "";
			}
			return "";
		}

		public Class getColumnClass(int c) {
			return getValueAt(0, c).getClass();
		}
	}

There is nothing unusual about this table model. We are creating 200
instances of Process and adding them to the internal arraylist for this table
model. The internal arraylist in this code example is shown as external because we would like to have this table model as an inner class.

Our renderer for the progress column is going to look a bit more interesting.
We are going to use a JProgressBar to render the 0 to 100 value inside each
Process bean. Since table renderers can return JComponents this is a
perfectly acceptable way of rendering a value.

ProcessProgressRenderer.java:

	class ProgressRenderer extends DefaultTableCellRenderer {
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
				boolean hasFocus, int row2, int column) {

			int row = table.convertRowIndexToModel(row2);

			ProcessTableModel mtm = (ProcessTableModel) table.getModel();
			Process p = (Process) mtm.getProcessAt(row);

			JProgressBar bar = new JProgressBar();
			bar.setValue(p.progress);
			return bar;
		}
	}

Lets create a basic GUI where we can put this table into, along with a button
which will fire off all the processes displayed in the table.

ThreadGUITest.java :

	public static void main(String[] args) {
		new ThreadGUITest().initGUI();
	}

	private void initGUI() {

		JPanel panel = new JPanel();

		ProcessTableModel m = new ProcessTableModel();

		table = new JTable(m);
		panel.add(new JScrollPane(table));

		table.getColumnModel().getColumn(1).setCellRenderer(new ProgressRenderer());

		JFrame mainFrame = new JFrame();
		startAllButton.addActionListener(this);
		mainFrame.getContentPane().add(panel, BorderLayout.NORTH);
		mainFrame.getContentPane().add(startAllButton);

		mainFrame.setVisible(true);
		mainFrame.pack();
	}

Part 2. Start Creating the Multithreading Aspect

Now lets get the thread magic happening. After the use clicks the ‘start all’ button,
each process will be fired off. The process itself will not actually be fired off (it is not a thread), however a wrapper class will handle the threading for the process entity. (Note : it is important not to make entities threads. Delegate this responsibility to a facade or proxy)

After the thread is fired off, the progress value will be re calculated.

ProgressUpdator.java

	class ProgressUpdater implements Runnable {

		private int row;

		public ProgressUpdater(int row) {
			this.row = row;
		}

		public void run() {

			final Process pr = processList.get(row);

			Random random = new Random();
			int progress = 0;

			// Initialize progress property.
			pr.progress = 0;

			while (progress < 100) {

				// Sleep for up to one second.
				try {

					Thread.sleep(random.nextInt(1000));

				} catch (InterruptedException ignore) {
				}
				// get random progress number
				progress = progress + random.nextInt(10);

				final int p = progress;

				pr.progress = Math.min(p, 100);

				ProcessTableModel m = (ProcessTableModel) table.getModel();

				m.fireTableCellUpdated(row, 1);
			}
		}
	}

The fireTableCellUpdated(row, 1) method on the table model, notifies the
event dispatch thread to re-render that particular cell in the JTable. It is possible to use the method updateTableModel() from the table model class, which would update every cell in the JTable, however this would be more performance intensive and unnecessary in our case.

Each one of these ProgressUpdaters (threads per se) will access one of the process
elements in the arraylist, hence the reason we are passing a row number into
the constructor. The row number is what links the ProgressUpdater with the Process.

Let’s add an Actionlistener to the button. On clicking the ‘start-all’ button all threads
will be fired off.

public void actionPerformed(ActionEvent evt) {
  startAllButton.setEnabled(false);

  for (ProgressUpdater elem : progressUpdaters) { Thread t = new Thread(elem);
  t.start(); }
}

Run the GUI. Pretty cool huh? But there is something missing. When all the
processes have finished the start all button still remains disabled. We would
like to know when all the processes have finished, so that we can re-enable the button.

We could use
Thread.join()
. The thread join() method joins the calling thread to the main thread, effectively freezing the main thread until all joined threads
have run to completion. We could join all the threads in the
actionPerformed(..) method, and once they have run to completion we could set
the button to enabled again.

A valid assumption would be to change the actionPerformed method like this :

public void actionPerformed(ActionEvent evt) {
  	startAllButton.setEnabled(false);

  	ArrayList<Thread> threads = new ArrayList<Thread>();

  	for (ProgressUpdater elem : progressUpdaters) {
  		Thread t = new Thread(elem);
  		threads.add(t);
  		t.start();
  	}

  	for (Thread elem : threads) {
  		try {
  			elem.join();
  		} catch (InterruptedException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		}
  	}

  	startAllButton.setEnabled(true);

  }

But now when we run our program, everything freezes. Whats going on? Why
can’t we fire off all our threads in the actionPerformed method and have them
all joined within this method? Once the threads have finished running,
why can’t we then update any GUI code?

The reason is that we are blocking the event dispatch thread. Nothing can
happen to the GUI while all the threads are running to completion. They are
not joined to the main thread, rather they are joined to the EDT.

We need to solve this by having all the threads joined on another thread. All
we have to do is take out all the thread code in the actionPerformed(..)
method and fire off that thread, leaving the EDT alone.

Create a thread and put the code in it like this :

	class MainThread extends Thread {

		public void run() {
			ArrayList ts = new ArrayList();

			for (ProgressUpdater pu : progressUpdaters) {

				Thread t = new Thread(pu);
				ts.add(t);
				try {
					t.start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			/**
			 * We need to join the threads after they all have been started.
			 */
			for (Thread pu : ts) {

				try {
					pu.join();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			SwingUtilities.invokeLater(new Runnable() {

				public void run() {
					startAllButton.setEnabled(true);
				}
			});
		}
	}

Now we can fire off this thread in the actionPerformed(..) method. After completion of all the processes the button will be enabled again!

Hope you enjoy and please leave a comment.

Full source code :

package tableWithProgressBar.temp;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

public class ThreadGUITest implements ActionListener {

	private JTable table;

	private JButton startAllButton = new JButton("Start");

	private ArrayList processList = new ArrayList();

	private ArrayList progressUpdaters = new ArrayList();

	public ThreadGUITest() {

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

			ProgressUpdater pu = new ProgressUpdater(i);
			progressUpdaters.add(pu);
		}
	}

	public static void main(String[] args) {
		new ThreadGUITest().initGUI();
	}

	private void initGUI() {

		JPanel panel = new JPanel();

		ProcessTableModel m = new ProcessTableModel();

		table = new JTable(m);
		panel.add(new JScrollPane(table));

		table.getColumnModel().getColumn(1).setCellRenderer(new ProgressRenderer());

		JFrame mainFrame = new JFrame();
		startAllButton.addActionListener(this);
		mainFrame.getContentPane().add(panel, BorderLayout.NORTH);
		mainFrame.getContentPane().add(startAllButton);

		mainFrame.setVisible(true);
		mainFrame.pack();
	}

	/**
	 * Invoked when the user presses the start button.
	 */
	public void actionPerformed(ActionEvent evt) {
		startAllButton.setEnabled(false);

		MainThread mt = new MainThread();
		mt.start();
	}

	class MainThread extends Thread {

		public void run() {
			ArrayList ts = new ArrayList();

			for (ProgressUpdater pu : progressUpdaters) {

				Thread t = new Thread(pu);
				ts.add(t);
				try {
					t.start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			/**
			 * We need to join the threads after they all have been started.
			 */
			for (Thread pu : ts) {

				try {
					pu.join();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			System.out.println("here");
			SwingUtilities.invokeLater(new Runnable() {

				public void run() {
					startAllButton.setEnabled(true);
				}
			});
		}
	}

	/**
	 * The responsibiliey of the progress updater is to update the progress of its process
	 * (linked via the row number).
	 */
	class ProgressUpdater implements Runnable {

		private int row;

		public ProgressUpdater(int row) {
			this.row = row;
		}

		public void run() {

			final Process pr = processList.get(row);

			Random random = new Random();
			int progress = 0;

			// Initialize progress property.
			pr.progress = 0;

			while (progress < 100) {

				// Sleep for up to one second.
				try {

					Thread.sleep(random.nextInt(1000));

				} catch (InterruptedException ignore) {
				}
				// get random progress number
				progress = progress + random.nextInt(10);

				final int p = progress;

				pr.progress = Math.min(p, 100);

				ProcessTableModel m = (ProcessTableModel) table.getModel();

				m.fireTableCellUpdated(row, 1);
			}
		}
	}

	class ProgressRenderer extends DefaultTableCellRenderer {
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
				boolean hasFocus, int row2, int column) {

			int row = table.convertRowIndexToModel(row2);

			ProcessTableModel mtm = (ProcessTableModel) table.getModel();
			Process p = (Process) mtm.getProcessAt(row);

			JProgressBar bar = new JProgressBar();
			bar.setValue(p.progress);
			return bar;
		}
	}

	class Process {

		public Process(String name, int progress, String description) {
			super();
			this.name = name;
			this.progress = progress;
			this.description = description;
		}

		String name;
		int progress;
		String description;
	}

	class ProcessTableModel extends AbstractTableModel {

		private String[] columnNames;

		public ProcessTableModel() {

			columnNames = new String[] {"Process", "Progress", ""};

			for (int i = 0; i < 200; i++) {
				processList.add(new Process("Process " + i, 0, "Description"));
			}
		}

		public Process getProcessAt(int row2) {
			return processList.get(row2);
		}

		public int getColumnCount() {
			return columnNames.length;
		}

		public int getRowCount() {
			return 200;
		}

		public String getColumnName(int col) {
			return columnNames[col];
		}

		public Object getValueAt(int row, int col) {

			Process p = processList.get(row);

			switch (col) {
			case 0:
				return p.name;
			case 1:
				return p.progress;
			case 2:
				return "";
			}
			return "";
		}

		public Class getColumnClass(int c) {
			return getValueAt(0, c).getClass();
		}
	}

}
Posted in Swing | Tagged , , , , , , , , | Leave a comment