Archive for September, 2006

Developing Java Beans { lowThreshold = low; }

Friday, September 29th, 2006

Developing Java Beans We could assume that if an event generator didn’t want to be interrupted for long periods of time, it would be implemented to protect itself from this possibility. But another approach is to use an event adapter that queues events and forwards them to the target object on another thread. This type of asynchronous delivery allows the thread that originally fired the event to continue doing whatever it wants, because the method call it made when firing the event returns almost immediately. Let’s create an example to illustrate how to build this type of adapter. We have a worker object that runs a thread every 200 milliseconds in order to update a counter. This object will be called a Poller. On every third update it generates a PollEvent to a listening object that implements the PollerListener interface, and it also prints the string “Value: x,” where x represents the value of the counter. Here’s the code. import java.util.*; class PollEvent extends EventObject { // the event valueprotected int value; // constructor takes source and value PollEvent(Object source, int value) { // pass the source to the superclass super(source); // save the value this.value = value; } // return the event value public int getValue() { return value; } } interface PollerListener { public abstract void pollSent(PollEvent e); } class Poller extends Thread { // a counter protected int cnt = 0; // the listener protected PollerListener listener = null; // the constructor public Poller() { // start my thread start(); } // add the listener public void addPollerListener(PollerListener l) throws TooManyListenersException { if (listener != null) { page 45
Note: If you are looking for cheap and reliable provider to host and run your servlet application check Vision servlet hosting services

Developing Java Beans { lowThreshold = low; }

Friday, September 29th, 2006

Developing Java Beans { lowThreshold = low; } public double getLowThreshold() { return lowThreshold; } public void setHighThreshold(double high) { highThreshold = high; } public double getHighThreshold() { return highThreshold; } Now we need to modify the code that does event notifications to perform the filtering. Before we even look up the method that is associated with the source of the event, we compare the new temperature to our threshold values. We only forward the event if the new temperature falls below the low or above the high threshold. The modified code for the tempChanged() method is shown below: // implement the listener methodpublic void tempChanged(TempChangedEvent evt) { // compare the new temperature against the threshold if (evt.getTemperature() < lowThreshold || evt.getTemperature() > highThreshold) { try { // invoke the registered method on the target Method mthd = (Method)mappingTable.get(evt.getSource()); Object params[] = { evt }; mthd.invoke(theTarget, params); } catch (IllegalAccessException e) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } } } 3.5 Event Queuing So far, everything we’ve done assumes that events are being generated synchronously. We’ve also assumed that this wouldn’t create a problem for the object that generates the events. Remember that events are fired on the caller’s thread. In some cases, this thread may have other work to do. If we write event-handler methods that do a great deal of work before returning to the caller, we may hold up the caller’s thread longer than is safe. Holding up the caller’s thread could also be a problem if it is important that all event listeners be notified quickly. Since the delivery order of events is generally undefined, it would be unfair (or worse) to hold up the delivery of an event to one listener because another is slow to respond. page 44
Note: If you are looking for cheap and reliable provider to host and run your servlet application check Vision servlet hosting services

Developing Java Beans Let’s create a generic adapter

Friday, September 29th, 2006

Developing Java Beans System.out.println(”handleB1 called for button ” + b.getLabel()); } public void handleB2(ActionEvent e) { Button b = (Button)e.getSource(); System.out.println(”handleB2 called for button ” + b.getLabel()); } public void handleB#(ActionEvent e) { Button b = (Button)e.getSource(); System.out.println(”handleB3 called for button ” + b.getLabel()); } } When you run this applet, it appears as shown in Figure 3.5. Figure 3.5. An applet using a generic adapter If you were to press the buttons on the applet consecutively, the following output would be printed to your console window: handleB1 called for button Button 1 handleB2 called for button Button 2 handleB3 called for button Button 3 3.4 Event Filtering Adapters can be used for filtering out events that don’t meet certain criteria. The adapter would analyze the information contained in the event and decide whether to forward it to the target object. This could be useful when the event source generates many events and only a small number of them are interesting to the listener. For example, let’s say that we were going to monitor the temperature in our simulator with a special listener that is interested only in temperature changes above or below certain values. We could create an adapter that filters out all temperature change events where the new temperature is between a low and a high threshold value. The GenericTemperatureAdapter can be easily modified to perform this task. The new adapter might be called a GenericTemperatureThresholdAdapter. We add data members to store the threshold temperatures and assign them default values as follows: protected double lowThreshold = 0.0; protected double highThreshold = 100.0; Now we need a way to assign the threshold values. For our example, we create methods for getting and setting these values. You’ll see in Chapter 4, that these values represent properties of the adapter. The new methods of the GenericTemperatureThresholdAdapter look like this: public void setLowThreshold (double low) page 43
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

Developing Java Beans Let’s create a generic adapter

Friday, September 29th, 2006

Developing Java Beans } catch (IllegalAccessException e) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } } } Now let’s create a simple applet that makes use of the adapter. The applet contains three buttons, labeled Button 1 through Button 3. The applet also has three handler methods that, when invoked, print a message to the console that contains the name of the message handler and the label of the button that was pressed. The applet is trivial, but it illustrates how the adapter is used. The code for the applet is shown below: import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; import BeansBook.util.*; public class ExampleApplet2 extends Applet { // the buttonsprotected Button b1 = new Button(”Button 1″); protected Button b2 = new Button(”Button 2″); protected Button b3 = new Button(”Button 3″); // the adapter protected GenericButtonAdapter adapter; // the applet initialization public void init() { // add the buttons to the applet add(b1); add(b2); add(b3); try { adapter = new GenericButtonAdapter(this); adapter.registerActionEventHandler(b1, “handleB1″); adapter.registerActionEventHandler(b2, “handleB2″); adapter.registerActionEventHandler(b3, “handleB3″); } catch (ClassNotFoundException e) { System.out.println(e); } catch (NoSuchMethodException e) { System.out.println(e); } } public void handleB1(ActionEvent e) { Button b = (Button)e.getSource(); page 42
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

Developing Java Beans Let’s create a generic adapter

Friday, September 29th, 2006

Developing Java Beans 3.3.1 A Generic Button Adapter It’s common for a dialog box or other window to contain multiple Button objects a perfect place to make use of an intelligent adapter. The GenericTemperatureAdapter class shown earlier can be easily modified for this purpose. Let’s create an adapter that will handle the ActionListener interface for multiple buttons, and will forward the ActionEvent to a method on the target object. Here’s the code for the GenericButtonAdapter class: package BeansBook.util; import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; import java.util.*; public class GenericButtonAdapterimplements ActionListener // the adapter receives the events { // the target objectprotected Object theTarget; // the class of the target object protected Class theTargetClass; // the class array for the parameters used for // the target method protected final static Class paramClasses[] = { java.awt.event.ActionEvent.class }; // the mapping of source objects to callback methods protected Hashtable mappingTable = new Hashtable(); // constructor public GenericButtonAdapter(Object target) throws ClassNotFoundException { theTarget = target; theTargetClass = target.getClass(); } // add an action object to listen for, along with the // method to call on the target when the action event // is received public void registerActionEventHandler(Button btn, String methodName) throws NoSuchMethodException { Method mthd = theTargetClass.getMethod(methodName, paramClasses); btn.addActionListener(this); mappingTable.put(btn, mthd); } // implement the listener method public void actionPerformed(ActionEvent evt) { try { // invoke the registered method on the target Method mthd = (Method)mappingTable.get(evt.getSource()); Object params[] = { evt }; mthd.invoke(theTarget, params); page 41
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

Developing Java Beans Let’s create a generic adapter

Friday, September 29th, 2006

Developing Java Beans { theTarget = target; theTargetClass = target.getClass(); } // add an event source, along with the name of the method to call // on the target when the event is received public void registerEventHandler(Temperature tmp, String methodName) throws NoSuchMethodException { Method mthd = theTargetClass.getMethod(methodName, paramClasses); tmp.addTempChangeListener(this); mappingTable.put(tmp, mthd); } // implement the listener method public void tempChanged(TempChangedEvent evt) { try { // invoke the registered method on the target Method mthd = (Method)mappingTable.get(evt.getSource()); Object params[] = { evt }; mthd.invoke(theTarget, params); } catch (IllegalAccessException e) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } } Now that we’ve got an adapter, let’s rewrite the Thermometer class to use it. This is pretty straightforward stuff. We can get rid of the inner class adapters, and use one instance of GenericTemperatureAdapter instead. In the earlier example, the methods temperature1Changed() and temperature2Changed() took an instance of double as the parameter. This was because the inner class adapters pulled the new temperature from the event object before the methods were called. The new adapter, GenericTemperatureAdapter, just passes the event object to the target method, so we need to change the parameter type for these methods from double to TempChangedEvent. package BeansBook.Simulator; public class Thermometer { // references to the two temperature objects that we are monitoringprotected Temperature theTemperature1; protected Temperature theTemperature2; // the temperature change adapter protected GenericTemperatureAdapter tempAdapter; // constructor Thermometer(Temperature temperature1, Temperature temperature2) { // save references to the temperature objects theTemperature1 = temperature1; theTemperature2 = temperature2; page 39
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

Developing Java Beans Let’s create a generic adapter

Friday, September 29th, 2006

Developing Java Beans // create the adapter tempAdapter = new GenericTemperatureAdapter(this); // register the handler methods try { tempAdapter.registerEventHandler(theTemperature1, “temperature1Changed”); tempAdapter.registerEventHandler(theTemperature2, “temperature2Changed”); } catch (NoSuchMethodException e) { System.out.println(e); } // handle changes to Temperature object 1 public void temperature1Changed(TempChangedEvent evt) { } // handle changes to Temperature object 2public void temperature2Changed(TempChangedEvent evt); {} } 3.3 Event Adapters in the AWT Package The java.awt.event package provides adapters for various event-listener types. These adapters are nothing more than empty shells that implement the methods in the various listener interfaces. These adapters don’t provide much added value, but you can subclass them to build basic demultiplexing adapters. They relieve you from having to implement every interface method yourself, although the burden is quite small. Let’s look at an example. The following chunk of code is the listing for the java.awt.event.FocusAdapter class: public class FocusAdapter implements FocusListener { public FocusAdapter() { } public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { } } So, as you can see, these adapters aren’t all that helpful. You’ll find an adapter class in java.awt.event for every event-listener interface that has more than one method in it. I think the fact that these adapters are provided at all is an indication that the technique is expected to be widely used. But I expect that more complex adapters will find more use than these. page 40
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

Developing Java Beans Let’s create a generic adapter

Friday, September 29th, 2006

Developing Java Beans Let’s create a generic adapter object that adapts the TempChangedListener interface to any arbitrary target object, and that can handle multiple Temperature objects as event sources. The only requirement for the target object is that the signature of the methods that the adapter will forward events to looks as follows: public void (BeansBook.Simulator.TempChangeEvent evt); The only new method needed for the GenericTemperatureAdapter class is registerEventHandler(); it takes a Temperature object and a method name as parameters. This method is used to associate the event-handling method on the target object with a specific Temperature event source. When the adapter receives a tempChanged event, it will forward it to the method on the target with the name passed into this parameter. The adapter uses a hash table to store these mappings. When the event is received, the source object is retrieved from the TempChangedEvent. This object is then used to look up the associated event-handling method object in the hash table. The code for this adapter is shown here. package BeansBook.Simulator; import java.lang.reflect.*; import java.util.*; public class GenericTemperatureAdapter implements TempChangeListener // the adapter receives the events { // the target objectprotected Object theTarget; // the class of the target object protected Class theTargetClass; // the class array for the parameters used for // the target method protected final static Class paramClasses[] = { BeansBook.Simulator.TempChangedEvent.class }; // the mapping of source objects to callback methods protected Hashtable mappingTable = new Hashtable(); // constructor public GenericTemperatureAdapter(Object target) page 38
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

Developing Java Beans Each adapter receives a temperature

Thursday, September 28th, 2006

Developing Java Beans java.lang.Class for each parameter in the method signature. If there are no parameters in the method you are reflecting, you can pass null in place of the array. Finally, the java.lang.reflect.Method class has a method named invoke(), which is used to invoke the method. It takes the target Object as the first parameter, and an Object array as the second parameter. This array is used to pass the parameters to the method being invoked. But not all parameters will be a subclass of Object. What if you have parameters that are one of the primitive Java types, such as int or float? In those cases you’ll have to use the static object representation of that type. As you know, each primitive data type has a corresponding object type; for instance the type float has a corresponding class called Float. Each of the object versions of the primitives contain a static field named TYPE that is used to represent its primitive counterpart as an object. For example, the object representation of float would be java.lang.Float.TYPE. The following code shows how we could find the setLabel() method of the java.awt.Button class, and then invoke it. try { // get the button classjava.awt.Button theButton = new java.awt.Button(”Sample”); Class theClass = theButton.getClass(); // get the string parameter class java.lang.Class paramClasses[] = { java.lang.String.class }; // find the method java.lang.reflect.Method mthd = theClass.getMethod(”setLabel” paramClasses); // now invoke it, changing the label to “Did It” Object param[] = { new String(”Did It”) }; mthd.invoke(theButton, param); } catch (java.lang.IllegalAccessException e) {} catch (java.lang.ClassNotFoundException e) {} catch (java.lang.NoSuchMethodException e) {} catch (java.lang.InvocationTargetException e) { } 3.2.2 Single Instance Adapters This technique allows us to create an adapter that uses reflection to find the method that handles events. But we will still need an instance of this adapter for every event source. It would be nice to build the generic adapter so that we only need one instance of it to handle events from multiple event sources, and forward those events to different methods on a single target. Figure 3.4 shows this. Figure 3.4. Using a single adapter with several sources and targets page 37
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services

Developing Java Beans Each adapter receives a temperature

Thursday, September 28th, 2006

Developing Java Beans conforms to a specific signature, and this method would be called by the adapter to forward the event. But in Java we don’t have that option. We have only objects and interfaces at our disposal. Or do we? 3.2.1 Using Java Reflection The Java reflection API is designed for analyzing Java objects and classes at run-time. Amongst other things, the reflection mechanism allows you to discover methods at run-time. The methods are represented by an instance of the class java.lang.reflect.Method. We’ll be able to associate an instance of this class to an instance of an adapter. The methods that will be invoked by the adapter must conform to a specific signature, and you’ll see shortly how we ensure that they do. 3.2.1.1 Finding the class The java.lang.Class class contains a static method called forName(). This method takes a string parameter containing the fully qualified class name and returns an instance of java.lang.Class. If the class does not exist, the exception java.lang.ClassNotFoundException will be thrown. The following example shows how to get the Class object for the java.awt.Button class: try{ Class theClass = Class.forName(”java.awt.Button”); } catch (java.lang.ClassNotFoundException e) { } You can also obtain the Class object associated with any Java object that is already instantiated. The Object class provides a method called getClass(), which returns the associated instance of java.lang.Class. Using getClass() allows for the possibility that the class wasn’t loaded by the default class loader. If we already had an instance of java.awt.Button, we could get its Class object as follows: java.awt.Button theButton = new java.awt.Button(”Sample”); try{ Class theClass = theButton.getClass(); } catch (java.lang.ClassNotFoundException e) { } Probably the easiest technique for getting a Class object is to assign it the static definition of the class you are looking for. You can specify the static class definition by appending .class to the class name. Here’s an example: Class theClass = java.awt.Button.class; 3.2.1.2 Finding the method Once we have determined the Class object, we can get an instance of java.lang.reflect.Method for any of the methods implemented by the object. The java.lang.Class class contains a method named getMethod(), which takes the name of the method as a String as one parameter, and an array of Class objects as the other parameter. This array contains the instances of page 36
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services