cookie
NN2 NN3 NN4 NN6 IE3 J1 IE3 J2 IE4 IE5 IE5.5 Compatibility The cookie mechanism in a Web browser lets you store small pieces of information on the client computer in a reasonably secure manner. In other words, when you need some tidbit of information to persist at the client level while either loading diverse HTML documents or moving from one session to another, the cookie mechanism saves the day. You can find Netscape's technical documentation much of which is written from the perspective of a...
Displaying data sets with HtmlDataTable
All of the components we've covered so far are relatively simple they output a string, collect data, allow the user to select an item from a list, or submit a form. If there's one complex requisite standard component for any UI framework, it's a data grid. For desktop applications, you'll find several variations on this theme, regardless of whether you're developing in Swing, .NET, or Delphi. The same is 1 You may be wondering why the hidden field's value is set in the event handler instead of...
Listing The Main Program mapgamehtm
lt HEAD gt lt TITLE gt Map Game lt TITLE gt Most of the positionable elements have their CSS properties established in the lt STYLE gt tag at the top of the document. Positionable elements whose styles are defined here include a text label for each state, a map for each state, and a congratulatory message. Notice that the names of the label and state map objects begin with a two-letter abbreviation of the state. This labeling comes in handy in the scripts when synchronizing the selected map...
The Inbox page
The first thing most ProjectTrack users will see is the Inbox. Upper Managers will see the Show All page instead, and won't be able to access this page at all. The Inbox is the page that shows all of the projects waiting for processing, and it's the one that users will typically interact with the most. Users can view details, approve, or reject any projects on this page. A mock-up is depicted in figure 9.3. As you can see in figure 9.3, this view has a page header and a panel that contains the...
Listing The desired search for names that begin with the substring entered by
import javax.microedition.lcdui.Command import import javax.microedition.lcdui.Display import javax.microedition.lcdui.Displayable import javax.microedition.lcdui.Form import javax.microedition.lcdui.TextField import import This class implements the screen that enables the user to search for one or more particular records in the address book. The user enters a name or prefix that represents the name of one or more records in the address book. public class SearchScreen extends Form implements...
AIBased Problem Solving
To conclude this book, we will examine a topic from an interesting discipline of programming artificial intelligence AI . As explained earlier, the goal of this book is to show the richness and power of the Java language. Perhaps nothing demonstrates that better than its application to the demanding realm of artificial intelligence. Java's powerful string-handling capabilities and Stack class streamline many types of AI-based code. Java's object model keeps the code clean, as does its garbage...
Implementing Email Delivery Functionality
Once we have set up a JavaMail session as described in the previous section, implementing the email delivery functionality is fairly simple. The process is illustrated in the following code example package net.ensode.glassfishbook import javax.annotation.Resource import javax.mail.Message import javax.mail.MessagingException import javax.mail.Session import javax.mail.Transport import javax.mail.internet.AddressException import javax.mail.internet.InternetAddress import...
CountDownLatch
This is used to synchronize one or more tasks by forcing them to wait for the completion of a set of operations being performed by other tasks. You give an initial count to a CountDownLatch object, and any task that calls await on that object will block until the count reaches zero. Other tasks may call countDown on the object to reduce the count, presumably when a task finishes its job. A CountDownLatch is designed to be used in a one-shot fashion the count cannot be reset. If you need a...
Selecting and deregistering JDBC drivers
During the course of your application you may need to select or remove specific drivers from the DriverManager list. These methods are useful if, for example, you implement a Factory design pattern to support multiple databases. Within your Factory class you could use DriverManager to pre-register the JDBC drivers you need for connecting to the supported databases. When a request for a Connection object occurs, your factory selects the proper driver from DriverManager and then creates the...
JTabbedPane
JTabbedPane is simply a stack of components in selectable layers. Each layer can contain one component which is normally a container. Tab extensions are used to move a given layer to the front of the tabbed pane view. These tab extensions are similar to labels in that they can have assigned text, an icon as well as a disabled icon , background and foreground colors, and a tooltip. To add a component to a tabbed pane, you use one of its overloaded add methods. This creates a new selectable tab...
Listing Scanner in a Web container
public static Class scan ServletContext context String root ClassScanner scanner new ClassScanner new File root we pick a specific directory final File testsDir new File root, com foo tests scanner.setFilter new FileFilter public boolean accept File pathname check that the file is anywhere inside of test root return Class classes scanner.getClasses return classes In Listing 4-3, context is an instance of ServletContext, obtained from the invoking servlet or JSP page. For performance reasons,...
Defining Constants
Any variable declared final in Java is a constant--its value must be specified with an initializer when it is declared, and that value may never be changed. The Java equivalent of a C define'ed constant is a static final variable declared within a class definition. If the compiler can compute the value of such a static final variable at compile-time, it uses the computed value to pre-compute other compile-time constants that refer to the value. The variable java.lang.Math.PI is an example of...
preventDefault
While NN6 continues to honor the original way of preventing default action for an event handler that is, having the last statement of the event handler evaluate to return false , the NN6 event model provides a method that lets the cancellation of default action take place entirely within a function invoked by an event handler. For example, consider a text box that is supposed to allow only numbers be typed in it. The onKeyPress event handler can invoke a function that inspects each typed...
Unicode and Character Escapes
Java characters, strings, and identifiers e.g., variable, method, and class names are composed of 16-bit Unicode characters. This makes Java programs relatively easy to internationalize for non-English-speaking users. It also makes the language easier to work with for non-English-speaking programmers-- a Thai programmer could use the Thai alphabet for class and method names in her Java code. If two-byte characters seem confusing or intimidating to you, fear not. The Unicode character set is...
contentEditable
Compatibility WinIE5.5 , MacIE-, NN-, Moz-, Safari 1.2 IE5.5 introduced the concept of editable HTML content on a page. Element tags can include a contenteditable attribute whose value is echoed via the contentEditable property of the element. The default value for this property is inherit, which means that the property inherits whatever setting this property has in the hierarchy of HTML containers outward to the body. If you set the contentEditable property to true, that element and all nested...
Aligning the Items with Layout
You can align your items with the layout attribute. The layout attribute defines how the affected item should be aligned and laid out. Possible layout values are, for example, left, right, and center. All layout values of the MIDP 2.0 standard can be used, as shown in Table 12-9. If you want to use the complete available width and center the item horizontally, you can specify layout center expand , for example. You can use several signs for separating the layout values use the , , or, or and...
EL Operators
The EL operations are necessary to handle data manipulations. All of the standard and common operators are available. Functionality is included in the EL for relational, arithmetic, and logical operators. These operators include , , lt , gt , lt , gt , eq, ne, lt, gt, le, and ge. The last six operators are made available to avoid having to use entity references in XML syntax. Entity references are sometimes required because, if you place a character like lt inside an XML element, the parser...
How It Works 20
The first line in the script block at the top of the page defines a variable with page-level scope. This is an array that contains your list of image sources. var mylmages new Next you have the changelmg function, which will be connected to the onclick event handler of an lt IMG gt tag surrounding each of your images. You are using the same function for both images' onclick event handlers and indeed can connect one function to as many event handlers as you like. You pass this function one...
SPHEREMAP mode
The SPHERE_MAP mode is very different from the OBJECT_LINEAR or EYE_LINEAR modes in that it always generates 2D s,t texture coordinates irrespective of any mapping planes passed to the TexCoordGeneration constructor. The SPHERE_MAP mode calculates texture coordinates based on the vector passing from the origin in world coordinates to a vertex. It creates a mapping that essentially paints an environment map onto the face of an object. Imagine that the object was a reflective sphere positioned in...
The NCBI QBLAST Package
NCBI provides a standardized API called URLAPI to formulate and dispatch direct HTTP-encoded requests to the NCBI QBlast system. The URLAPI provides a URL and a mechanism to set parameters that allows users to send sequences for BLAST searches. 1. The user provides BLAST parameters through a URL using the HTTP POST method 2. The QBlast service returns a Request Identifier RID and a Request Time of Execution RTOE, measured in seconds for the search, which provide respectively, a unique...
Example
import javax.swing. import javax.swing.event. import java.beans. import j ava.awt. import java.io. public class BakedBean extends JComponent implements Externalizable Property names only needed for bound or constrained properties public static final String BEAN_VALUE Value public static final String BEAN_COLOR Color private Font m_beanFont simple private Dimension m_beanDimension simple private int m_beanValue bound private Color m_beanColor constrained private String m_beanString change...
Concurrent Serial Port Usage
If we connect more than one thing to a serial port, we'll run into many PortInUseExceptions. We want to avoid that, otherwise our programs will be exiting when we don't want them to. See Table 2-2. Table 2-2. Pros and Cons of Concurrent Usage Create serial port inside each dependent object. Create serial port outside of consuming objects. Create single class that has control of all required actions of serial port. Use a singleton of serial port inside each dependent object. Use a singleton of...
Other GUI technologies
By themselves, or as the foundation of an RCP application, Swing and SWT are not the only available base technologies for GUI development. This section reviews other GUI technologies that are related to Java, both open source and commercial. The list is partial and by no means complete. 13. Available at http www.3plus4.de swt Table 11.5 GUI technologies related to Java Table 11.5 GUI technologies related to Java Exports the graphic display of a Java SWT application running on one host on a...
Limit the Number of Objects a Thread Touches
The next tip in using threads is almost an emergent tip. If you use containers to mediate thread communication, use background threads to perform resource allocation and cleanup tasks, and carefully limit the number of objects that serialization will visit, you'll notice something else happening. Each thread will only ever visit a small number of objects. There's a slight exception to this. Since RMI reuses the same thread across multiple client requests, that thread may eventually wind up...
Example XML for XMLRPC request
User-Agent Tomcat Web Server 3.1 Beta Sun Solaris 2.6 Host newInstance.com Content-Type text xml Content-length 234 lt xml version 1.0 gt lt methodCall gt lt params gt lt param gt lt param gt lt params gt lt methodCall gt The XML-RPC libraries on the server receive this and decode it, matching it with a handler method if one is available that matches . The requested Java method is then invoked, and the server encodes the result back into XML, as shown in Example 11-11.
Garbage Collection Techniques
Garbage Collection designates a set of techniques used by Java VM for automatic memory reclamation those familiar with these techniques can skip this section. Garbage Collection generally consists of three steps 1 mark, 2 collect, and 3 clean-up. The mark step finds the objects that need to be retained. The collect step removes unused objects. The clean-up step returns the reclaimed memory to the pool of free memory i.e., return to a usable state . The OracleJVM memory manager uses a set of GC...
Methods Across the Wire
Though convenient, automatically generating marshalling and demarshalling code is mostly a side effect produced in the service of a much more important goal. In a nutshell RMI is designed to make communication between two Java programs, running in separate JVMs, as much like making a method call inside a single process as possible. This is an ambitious goal. How does RMI achieve it Recall that in order to communicate with the printer server, we wrote an object, ClientNetworkWrapper, which did...
Timers
If you want to execute tasks that take different amounts of time during sprite movement and collision detection, the simplest way is to use the java.util.Timer class. The Timer class makes it easy for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it hogs the timer's task execution thread....
Database Administration
MySQL is a comprehensive relational database management system and must be managed to achieve optimal functionality. Some of the issues that you need to understand include how to add users and set up permissions, how to import large amounts of data into various tables, when and how to make backups, and how to replicate data, among other functions. This chapter provides you with a guide to database administration in a development or staging environment. For a production-level system, we...
Building HTML Forms
Struts includes a page construction tag library to build HTML forms. In our sample application, page construction tags are prefixed with html. Here is the Struts code to render the input elements for a person's first and last names Download lt label for firstName class desc gt First Name lt label gt lt html errors property firstName gt lt html text property firstName styleId firstName styleClass text medium gt lt label for lastName class desc gt Last Name lt label gt lt html errors property...
Java Map and Ruby Hash
Java has several implementations of Maps, which are collections that manage key value pairs. One such collection is the environment variables. Here, then, is a simple program that enumerates the environment variables Download code java_xt src PrintEnv.java public static void main String args Map map System.getenv for Iterator it map.entrySet .iterator it.hasNext Map.Entry e Map.Entry it.next s, e.getKey , e.getValue Download irb main 032 0 gt ENV.each k,v puts k v TERM_PROGRAM Apple_Terminal...
The Grid and Events
It looks easy enough. You click a grid row, the row highlights, and you extract the search term from the list. But where do you start Is the grid a table Do the cells have IDs Luckily, you don't have to piece together the cigar name by screen-scraping. Remember that grids have a model. The model has all the unprocessed data in it. If you could just get the clicked row and map it to an item in the model, you could easily get the value you need. Fortunately, the Grid widget provides hooks for you...
Entities and entity beans
EJB 3 entities and EJB 2.x entity beans are different beasts from the other kinds of Enterprise JavaBeans, session beans, and message-driven beans. Entities represent data and operations related to finding entities by various criteria, modifying the data represented by a given entity bean instance, and creating and deleting data in other words, persistent objects. The majority of entity beans written by corporate developers have traditionally had no functionality beyond what's generated by the...
The Structure of SOAP
We will first examine a simple example of SOAP being used with HTTP. This example transmits a GetCurrentTemperature SOAP request to a CurrentTemperature service see Listing 13.2 . The request takes a string parameter, city code, which represents the city for which you wish to retrieve the temperature. The SOAP server that receives this request will return a floating point number that corresponds to the current temperature in the requested city. Now we will examine the request and response in...
OpenCms Architecture
OpenCms has a modular architecture centered on a VFS. The file system is considered virtual as it resides inside a database and not on a hard disk. The VFS is similar to a real file system that supports folders, file types, and permissions. Access permission masks on the files and folders, and controls access that users and groups have to the files. The OpenCms VFS also provides a feature very similar to symbolic links in a Unix file system. A link is a directory entry that contains...
Dictionary
While the Dictionary object is very helpful to VBScript authors, JavaScript already provides the equivalent functionality natively. A Dictionary object behaves very much like a JavaScript array that has string index values similar to a Java hash table , although numeric index values are also acceptable in the Dictionary. Indexes are called keys in this environment. VBScript arrays do not have this facility natively, so the Dictionary object supplements the language for the sake of convenience....
Listing Letting ejbPostCreate create a Timer
public void setEntityContext EntityContext ctx this.ctx ctx public void ejbPostCreate String username, String password ctx.getTimerService .createTimer BunchOfConstants.TWO_MONTHS, password expired We know the UserBean class should be abstract, implement the javax.ejb.Enti-tyBean interface, and so forth, in order to be a valid entity bean implementation, according to the EJB 2.1 specification. Consider writing some contract tests for checking such things for our entity beans. Leaving that...
Example An AsyncHandier Implementation
225 private static class RequestOrderCallbackHandler 230 public void handleResponse Response lt RequestOrderResponse gt response 232 long elapsed new Date .getTime - startTime 235 JAXBContext jc Boolean.TRUE Callback and Dynamic Service waiting time for Web service response 243 System.out.println elapsed milliseconds. Message 249 RequestOrderResponse orderResponse response.get 250 m.marshal orderResponse, System.out 252 catch ExecutionException e 253 Throwable t e.getCause 254 if t instanceof...
Thread Local Variables
public Object calculate Object param HashMap hm results.get Object o hm.get param if o null return o o doLocalCalculate param hm.put param, o return o protected abstract Object doLocalCalculate Object param Thread local objects are declared static so that the object itself that is, the results variable in this example is shared among all threads. When the get method of the thread local variable is called, the internal mechanism of the thread local class returns the specific object assigned to...
Add a Data Provider
Using an object array data provider will make the types contained in Result-Element visible through the IDE. This, in turn, will make component binding easy. 1. Select Design in the editing toolbar to return to the design view. 2. Expand the Data Providers node in the Components palette. 3. From the Data Providers Components palette, select Object Array Data Provider and drop it on the design view.You'll see component obj ectArray-DataProviderl in the Page1 Outline view. 4. In the Properties...
A Browser History Count
lt title gt History Object lt title gt lt script type text javascript gt function showCount var histCount window.history.length if histCount gt 5 alert My, my, you 've been busy. You have visited histCount pages so far. else alert You have been to histCount Web pages this session. lt script gt lt head gt lt body gt lt form gt lt input type button name activity value My Activity onclick showCount gt lt form gt lt body gt lt html gt
Defining the Listener Class
You define a listener class as an implementation of a listener interface. Table 113 lists the events that can be monitored and the corresponding interface that must be implemented. When a listener method is invoked, it is passed an event that contains information appropriate to the event. For example, the methods in the HttpSessionListener interface are passed an HttpSessionEvent, which contains an HttpSession. Table 11-3 Servlet Life-Cycle Events Table 11-3 Servlet Life-Cycle Events...
Gathering Information Using MetaDataControl
MetaDataControl provides a simple way for Player instances to expose the meta information about media data. This meta information can be exposed with a set of predefined keys, such as Author, Title, Date, and Copyright, or the media may contain its own proprietary keys with associated values . As with StopTimeControl, not all media exposes this control. WAV and MP3 in sampled audio and MPEG in video are the most likely candidates that will provide meta information such as this. This doesn't...
One Task to Bind Them All
Now that we have proper scripts in all the modules with appropriate tasks, it would be nice if we could call them all in just one task execution. The preceding list of commands seems to be a lot of work. You need to go into each directory and execute the appropriate task with Rake. For now, we have only three modules, but just imagine a project with ten or twenty modules A simple build could require quite a lot of typing. We're going to create a real rakefile in the project root directory...
Example Creating an instance of MBeanInfo
public class Queue extends Basic implements DynamicMBean . . . private MBeanInfo _MBeanInfo . . . public static final String NOTIF_STALLED_FULL public static final String NOTIF_STALLED_EMPTY sample.Queue.stalled.empty . . . public Queue int queueSize . . . Attributes attributeInfo 0 new MBeanAttributeInfo QueueSize, Integer.TYPE.getName , Maximum number of items the queue may contain at one time., true, true, false attributeInfo 1 new MBeanAttributeInfo NumberOfConsumers, Integer.TYPE.getName ,...
Listing Creating the Dispatch Lookup Table
Begin validation dispatching mechanism function dispatcher validationFunc this.doValidate validationFunc new dispatcher isNotEmpty new dispatcher isPositivelnteger new dispatcher isDollarsOnly8 dispatchLookup isUSState new dispatcher isUSState dispatchLookup isZip new dispatcher isZip new dispatcher isExpandedZip dispatchLookup isPhone new dispatcher isPhone dispatchLookup isConfirmed new dispatcher isConfirmed dispatchLookup isNY new dispatcher isNY dispatchLookup isNum16 new dispatcher...
CallStaticMethodV
lt NativeType gt CallStatic lt Type gt MethodV JNIEnv env, jclass clazz, jmethodID methodID, va_1ist args This family of functions consists of ten members. This family of functions consists of ten members. Description Invokes a static method, specified using a method ID, on a class. The method must be accessible in clazz, although it may be defined in one of the superclasses of clazz. Programmers should place all arguments to the method in an args argument of type va_1ist that immediately...
Integrating Source Code ThirdParty APIs
When a third-party API is available in source code, you can integrate it by modifying the sourceDir attribute of the lt build gt element in the build.xml file. Consider the case where your normal application code is in the source src directory and the source code of the third-party API is in the source thirdparty folder. You can now add the third-party API with the lt sources gt element, as shown in Listing 7-35. As most other elements, you can use if and unless conditions for your sources....
Reviews with dojoxhrGet
Justa has a great opportunity. The magazine Cigars Unlimited now offers its world-renowned cigar reviews via a web service. Justa pays a small fee each time the service is called, but it will make up that money easily by selling more cigars. The company wants an icon added to the grid, which the user will click to fire the request and put the reviews in a list. It would be nice to connect Dojo and JavaScript directly to the Cigars Unlimited web service. But there are two issues Cigars...
The Browse Application
So much for the framework. Let's spec out an application. We're going to build an application that retrieves and displays WSOs as provided by some service. We'll name the application OBE, which stands for object browser and editor. As shown in Figure 18.1, on page 478, OBE contains a main menu bar at the top, a status bar at the bottom, and a workspace that occupies all the remaining space available in the browser window. The workspace is further divided by a splitter bar into two panes a...











