| |||||||||||||||
Tuesday, October 27, 2009
Chapter 11. ICMP: Internet Control Message Protocol
6.9. Scrapbook Pages
< Day Day Up > |
6.9. Scrapbook PagesA scrapbook page is a way to create and test snippets of code without all the trappings of normal Java code. In some ways, it's like working in a scripting language, but you have the full expressiveness of Java in addition to being able to make calls into any of your code or any of the system libraries. To create a scrapbook page, select File New Other… Java Java Run/Debug Scrapbook Page. Enter the name of the page�for example, test�and click Finish (or just press Enter). A new editor page will open for test.jpage. In the blank scrapbook page, try typing in an expression like 123/456, press Ctrl+A to select the expression, and press Ctrl+Shift+D (Run Display) to run it and display the result. (The answer in this case is (int) 0 because both numbers are integers and the result was truncated.) Note that the result is selected, so you can copy it quickly (or press Backspace to remove it from the page). Next, try entering Math.PI and displaying its result. This works because the scrapbook page already has all the system libraries imported, including the Math class. If you need a particular import, you can bring up the context menu and select Set Imports…. Let's try something a little more complicated. Type in this snippet of code:
Now select the snippet and press Ctrl+U (Run Execute) to execute it. The output will appear in the Console window. Execute is exactly like Display except that Execute doesn't show the return value (if any). You can execute loops or even call methods in your regular programs from the scrapbook page. This is useful for trying out new ideas or just for simple debugging. |
< Day Day Up > |
3.2 J2EE Applications
< Day Day Up > |
3.2 J2EE ApplicationsA J2EE application, an enterprise application that conforms to the J2EE specification, is structured as shown in Figure 3.2 and consists of the following:
Figure 3.2. Contents of a J2EE ApplicationA J2EE application is represented by, and packaged in, an Enterprise Archive (EAR) file. The modules that comprise the EAR file are themselves packaged in archive files specific to their types. For example, a Web module is packaged in a Web Archive (WAR) file, and an EJB module, containing one or more enterprise beans, is packaged in a JAR file. WAR files can exist as independent deployment units from EAR files. EAR files also contain a deployment descriptor file�an XML document describing the contents of the application and containing instructions for the deployment of the application. In particular, the deployment descriptor specifies the security settings to be enforced by the runtime environment. Each WAR file packaging a Web module, JAR file packaging enterprise beans, or JAR file packaging an application client module contains its own deployment descriptor as well. 3.2.1 EJB ModulesAn enterprise bean is a Java component that can be combined with other resources to create distributed client/server applications. Instantiated enterprise beans reside in enterprise bean containers, or EJB containers. An EJB container provides an interface between the enterprise beans and the application server on which the enterprise beans reside. An enterprise bean is typically accessed using Java RMI-IIOP. An ORB manages the interaction between clients and enterprise beans, using IIOP. ORBs enable clients to make requests and receive responses from servers in distributed computing environments. Alternatively, enterprise beans are accessible through JMS. It is also possible to invoke an enterprise bean as a Web service via SOAP, as explained in Chapter 14 on page 497. There are three types of enterprise beans: entity beans, session beans, and message-driven beans. Entity beans store persistent data and typically use database connections. Entity beans are of two types: CMP entity beans and BMP entity beans.
Session beans do not require database access, although they can obtain it indirectly, as needed, by accessing entity beans. Session beans can also obtain direct access to databases and other resources through the use of resource references, which include the use of JDBC. Session beans can be either stateless or stateful.
Message-driven beans are enterprise beans accessible asynchronously via JMS rather than synchronously through such protocols as RMI-IIOP. The EJB V2.1 specification expands the scope of message-driven beans beyond JMS to support any messaging system. An EJB module is one or more enterprise beans assembled into a single deployable unit. As we have observed, an EJB module is stored in a standard JAR file, commonly referred to as ejb-jar. This file contains
Specifically, an EJB module's deployment descriptor file declares the contents of the module, specifies the structure and external dependencies of the enterprise beans in the module, explains how the enterprise beans are to be used at runtime, and defines the security policies applicable to the enterprise beans within the module. The format of the security policy is defined by the EJB specification (see Chapter 5 on page 157). 3.2.2 Web ModulesA Web module represents a Web application�an application that can be accessed over the Web using HTTP. A Web module is used to assemble servlets and JSP files, as well as static content, such as HTML pages, into a single deployable unit. As we said earlier, Web modules are stored in WAR files, which are enhanced JAR files with a .war file extension, and contain
The deployment descriptor file, web.xml, declares the contents of the Web module. This file contains information about the structure and external dependencies of the components in the Web module and describes the components' runtime use. In addition, the deployment description file is used to declare the security policies applicable to the universal resource identifiers (URIs) that are mapped to the resources within the Web module. These security policies include both the authorization policy and the login configuration information. The format of the security policy is defined by the Java Servlet specification. Servlets are Java programs running on a WAS and extend the Web server's capabilities. For example, servlets support generation of dynamic Web page content, provide database access, concurrently serve multiple clients, and filter data by MIME type. Servlets use the Java Servlet API. By analogy, servlets are the server-side equivalent of client-side browser applets. JSP files enable the separation of the HTML coding from the business logic in Web pages, allowing HTML programmers and Java programmers to more easily collaborate in creating and maintaining pages. This process is described in greater detail in Section 4.1.2 on page 104. 3.2.3 Application Client ModulesApplication clients are first-tier Java-based client programs. Even though it is a regular Java application, an application client depends on an application client container to provide system services. An application client module packages application client code in a JAR file. This JAR file includes a deployment descriptor XML file, which specifies the enterprise beans and external resources referenced by the application. The security configuration of an application client determines how the application will access enterprise beans and Web resources. If the J2EE components that the client application accesses are secured, the client will be authenticated accordingly. In order for an application client to retrieve authentication data from an end user, configuration information must be specified in a deployment descriptor XML file, application-client.xml, associated with the client application. Application clients typically run in an environment that has a Java 2 security manager installed and the security policies enforced based on the J2SE security policy framework (see Chapter 8 on page 253). |
< Day Day Up > |
17.2 The PickNPop implementation
[ Team LiB ] |
17.2 The PickNPop implementationA lot of the work of designing software goes into improving the way that the program looks onscreen. Software engineering is a little like theater, or like stage-magic. Your goal is to give the user the illusion that your program is a very solid, tangible kind of thing. Getting everything in place requires solid design and a lot of tweaking. One thing differentiating PickNPop from Spacewar and Airhockey is that we chose to make the _border of the world have a non-zero z size so that the shapes can pass above and below each other when we show the game in the OpenGL 3D mode. Making the score come out evenThough not all games must have a numerical score, if you have one, then it should be easy to understand. On the one hand you might require that your game events have simple, round-number score values assigned to them. On the other hand you might require that your maximum possible game score total be a round easy number like 100, 1000, or even 1,000,000. If you are able to control the number of things that can happen in your game, then you can satisfy both conditions. If not, then you have to settle for one of the conditions: round-number values or round-number maximum score. In PickNPop, we allow for varying sizes of worlds, and, since the game might still be developed further, we allow for recompiling the program with different values of JEWEL_PERCENT. So it's not possible both to have round-number values and to have a round-number max score. Our decision here was to go for the round-number maximum score. In the CPopDoc::seedBubbles(int gametype, int count) method we figure out how many jewels and peanuts to make, and then we figure out how much they should be worth, and finally we calculate a _scorecorrection In cGamePickNPop::seedCritters()
The world rectanglesIn PickNPop we want to try and fit our game as nicely as possible into our window. We give the CDocument Converting a critterOne of the parts of the code the author initially had trouble with was in the cCritterJewel
The delete_me makes a service request to the _pownerbiota cBiota |
[ Team LiB ] |
Section 24.6. Date/Time
24.6. Date/TimeOur globalization Consider the following issues related to date/time:
24.6.1. Timestamp DatatypesUntil Oracle9i Database, working with dates and times was fairly straightforward. You had the DATE type and the TO_DATE function. The limited functionality of the DATE type made application development of global applications somewhat tedious, though. All time zone adjustments involved manual calculations. Sadly, if your application is to work with Oracle8i Database or earlier versions, I'm afraid you are still stuck with this as your only option. Those of us working with Oracle9i Database and higher, however, benefit greatly from the TIMESTAMP and INTERVAL datatypes Lets take a look at an example of the TIMESTAMP, TIMESTAMP WITH TIME ZONE, AND TIMESTAMP WITH LOCAL TIME ZONE datatypes in action:
The following dates and times are returned:
TIMEZONE and TIMEZONE WITH LOCAL TIMESTAMP are identical because the database time is in the same locale as my session. The value for TIMESTAMP WITH TIMEZONE shows that I am in the Mountain time zone. If I were in accessing my Colorado database via a session in California, the result would be slightly different.
The value for TIMESTAMP WITH LOCAL TIMEZONE used the time zone of my session, which is now Pacific, or -08:00, and automatically converted the value. 24.6.2. Date/Time FormattingOne localization challenge we face is related to date and time formatting A common way to handle this situation is to include a list of format masks in a locale table that maps to the user. When the user logs in, his assigned locale maps to the correct date/time format for his region. The g11n schema has a USERS table and a LOCALE table, joined by a locale_id. Let's take a look at some examples using date/time functions (discussed in detail inChapter 10), and the format masks provided in the g11n.locale table. The registration_date column in the table uses the TIMESTAMP WITH TIME ZONE datatype. Using the TO_CHAR function and passing the format mask for each user's locale displays the date in the correct format.
To execute it, do the following:
This prints the following result set:
The three locales have different date format masks assigned. Using this method allows each user to see an appropriate date format for his locale based on his profile. If we now add NLS_DATE_FORMAT, the dates and times will use the appropriate locale language. We have this mapped in our tables to ensure that each locale is displayed correctly.
Execute the function as follows:
This prints the following:
The same data is stored in the USERS table, but the time is displayed in locale-specific format. You can modify the function in the same way to use the time zone and timestamp functions to distinguish between time zones for various locales. NLS_DATE_LANGUAGE is customized for each territory, so AM is in Japanese for the Japanese locale, and the month for the German locale is displayed in German. We can extend our function to include the session time zone either by converting the value to the TIMESTAMP WITH TIME ZONE datatype, or by converting the value to our session's local time zone with TIMESTAMP WITH LOCAL TIME ZONE. We do this with the CAST function (described inChapter 7), which will change the datatype of the value stored in our table.
The function is executed by doing the following:
The registration dates are returned as follows:
There is a lot going on here:
Many of our examples thus far have shown the time zone as a UTC offset. This is not necessarily the easiest display for a user to understand. Oracle maintains a list of region names and abbreviations that can be substituted by modifying the format mask. In fact, the three records we have been working with were inserted using these region names rather than the UTC offset. For a complete list of time zones, query the V$TIMEZONE_NAMES view. Examine the INSERT statements into the USERS table in the g11n schema for more examples using region names. I want to discuss one more NLS parameter related to date/time. Our times are inserted into the table using the Gregorian calendar, which is the value for NLS_CALENDAR on our test system. Not all locales use the same calendar, however, and no amount of formatting will adjust the base calendar. With NLS_CALENDAR, we can change our default calendar from Gregorian to a number of other seeded calendarsJapanese Imperial for example. A simple SELECT of SYSDATE after setting the session results in the following:
After altering the session, run the following SELECT:
The SELECT shows the modified SYSDATE:
|
16.3 Using the Query Cache
< Day Day Up > |
16.3 Using the Query CacheMySQL supports a query cache that greatly increases performance if the server's query mix includes SELECT statements that are processed repeatedly and return the same results each time. If you enable the query cache, the server uses it as follows:
The query cache is global, so a query result placed in the cache can be returned to any client. Using the query cache can result in a tremendous performance boost and reduction in server load, especially for disk- or processor-intensive queries. Three system variables control query cache operation:
The default value of query_cache_type is ON (caching allowed). However, the cache is not operational unless its size is set larger than the default value of zero. To enable the query cache, set the value of query_cache_size to a nonzero size in bytes to indicate how much memory to allocate to it. You may optionally set the query_cache_limit variable as well. It places an upper bound on how large an individual query result can be and still be eligible for caching. The default limit is 1MB. Typically, you set the query cache variables in an option file where you list the server's startup options. For example, to allocate 10MB of memory to the query cache and allow individual query results up to 2MB to be cached, put the following lines in the option file and restart the server:
If you have the SUPER privilege, you can change these variables for a running server without restarting it by using the following statements:
If you set the variables that way, the changes will be lost at the next server restart, so SET is useful primarily for testing cache settings. When you find suitable values, record them in the option file. The server provides information about the operation of the query cache by means of a set of status variables. To view these variables, use the following statement:
Qcache_inserts is the total number of queries that have been put in the cache. Qcache_queries_in_cache indicates the number of queries currently registered in the cache. The difference between the two values indicates how many cached queries were displaced to make room for newer queries. Qcache_hits indicates how many times a query did not have to be executed because its result could be served from the cache. |
< Day Day Up > |
UML Package Diagram
UML Package DiagramFor our sample application, Time Expression, we will use the prefix com.visualpatterns.timex for our package name. If you have worked with Java already, you probably know that the first part of the package name is typically tied to an organization's domain name, just used backwards. For example, com.visualpatterns is the reverse for visualpatterns.com, which happens to be my website. The timex portion of our package name is derived from the name of our sample application. The remainder, the suffixes, for our package names are shown in Figure 3.6, a rudimentary UML package diagram. Figure 3.6. UML package diagram for Time Expression.[View full size image] Note I have chosen very basic Java packages names to match our MVC pattern-based design. For example, we could have called our model package something like domain, but I prefer to match things upfor example, matching the package names with the architecture or application flow map. That way, someone new taking over my code can easily follow its organization. So, a fully qualified package name for the model package would be com.visualpatterns.timex.model. As you might guess, the controller package will have controller-related classes in it. The job package will contain our email reminder job. The util package contains common and/or utility code. Last but not least, the test package will contain our unit test code. Although I have chosen to place our test classes in a separate package, many developers prefer keeping the test classes in the same directory as the implementation code they are testing. This is a matter of preference, but in my opinion, having a separate package/directory for the test classes keeps things nice and clean in the actual implementation package directories. |
Lab 9.2 Exercise Answers
[ Team LiB ] |
Lab 9.2 Exercise Answers9.2.1 Answers
9.2.2 Answers
|
[ Team LiB ] |
14.5 Eliminating Duplicates from a Query Result
I l@ve RuBoard |
14.5 Eliminating Duplicates from a Query Result14.5.1 ProblemYou want to select 14.5.2 SolutionUse SELECT DISTINCT. 14.5.3 DiscussionRows in query results sometimes mysql> SELECT last_name, first_name With DISTINCT, the duplicates are eliminated: mysql> SELECT DISTINCT last_name, first_name An alternative to DISTINCT is to add a mysql> SELECT last_name, first_name FROM cat_mailing 14.5.4 See AlsoSELECT DISTINCT is discussed |
I l@ve RuBoard |
4.1 Creating a JavaScript Variable
[ Team LiB ] |
4.1 Creating a JavaScript VariableNN 2, IE 3 4.1.1 ProblemYou 4.1.2 SolutionUse the var keyword to define the first instance of var myVar = someValue; All script statements on the page, including those inside functions, When you define a variable with var inside a function myFunction( ) { Statements outside of the function cannot reach the value of a 4.1.3 DiscussionA JavaScript variable has no inherent limit to the amount of data it Variable parent.content.myVar You don't have to worry about the same global Where you must exercise care is in defining a new variable inside a Although some programming languages distinguish between the tasks of Speaking of good programming practice, it is generally advisable to var myVar; If you have multiple variables that you'd like to var myVar, counter, fred, i, j; You may even combine declarations and initializations in a var myVar, counter = 0, fred, i, j; In examples throughout this book, you typically find variables being var i, j; This is merely my style preference. But in any case, this situation As for selecting the names for your variables, there are some
Conventions among programmers with respect to devising names for The main idea behind a variable name is to help you identify what var teamMember = "George"; Apply these rules and concepts to the identifiers you assign to Variable JavaScript assigns data to a variable both "by var elem = document.getElementById("myTable"); But if the data is a simple value (string, number, Boolean), the elem.cellPadding = "10"; If an object's property value is itself another var elem = document.getElementById("myTable"); Exercise care with DOM objects assigned to variables. It may seem as 4.1.4 See AlsoChapter 1, Chapter 2, |
[ Team LiB ] |
Chapter 7: Control Visual Basic
Chapter 7: Control Visual Basic
Chapter at a Glance
In this chapter, you will learn to:
Use conditional statements.
Create loops using three different blocks.
Retrieve the names of files in a folder.
Create breakpoints to debug long loops.
Show progress while a macro executes a loop.
The first successful underwater tunnel ever built was begun in 1825. It is the Thames Tunnel. It was a financial disaster at the time, but amazingly it is still in use as part of the London Underground system. The genius behind the the tunnel’s engineering was a man named Marc Brunel. Twenty years before launching the Thames Tunnel, Brunel made a name for himself by devising a way of inexpensively producing the pulley blocks needed to build ships for the British shipping industry. Brunel’s technique later came to be known as an “assembly line,” and Henry Ford turned the invention into an industry, supplying America with Model T cars that cost only $3,500 in today’s dollars.
Repetition can have a dramatic effect on efficiency. Computer programs-including macros that you write-become more powerful when you add a multiplier effect. In this chapter, you’ll learn how to add loops to your macros. And to make those loops more effective, you’ll learn how to create conditional expressions that let the macro make decisions.
On The CD-Important | Before you complete this chapter, you need to install the practice files from the book’s companion CD to their default locations. See “Using the Book’s CD” on page xv for more information.
|
Section 8.4. Bringing It All Together
8.4. Bringing It All TogetherNow that we have a skeletal device driver, we can load it and exercise it. Listing 8-11 is a simple user space application that exercises our device driver. We've already seen how to load the driver. Simply compile it and issue the make modules_install command to place it on your file system, as previously described. Listing 8-11. Exercising Our Device Driver
This simple file, compiled on an ARM XScale system, demonstrates the binding of application to device driver, through the device node. Like the device driver, it doesn't do any useful work, but it does demonstrate the concepts as it exercises some of the methods we introduced in the device driver of Listing 8-10. First we issue an open() system call [7] on our device node created earlier. If the open succeeds, we indicate that with a message to the console. Next we issue a read() command and again print a message to the console on success. Notice that a read of 0 bytes is perfectly acceptable as far as the kernel is concerned and, in actual practice, indicates an end-of-file or out-of-data condition. Your device driver defines that special condition. When complete, we simply close the file and exit. Listing 8-12 captures the output of running this example application on an ARM XScale target:
Listing 8-12. Using the Example Driver
|
Section 13.6. Predefined Object Types
13.6. Predefined Object TypesStarting with Oracle9i Database Release 1, Oracle provides a collection of useful, predefined
The following subsections discuss these predefined object types in more detail. 13.6.1. The XMLType TypeOracle9i Database Release 1 introduced a native object type called XMLType. You can use XMLType to define database columns and PL/SQL variables containing XML documents. Methods defined on XMLType enable you to instantiate new XMLType values, to extract portions of an XML document, and to otherwise manipulate the contents of an XML document in various ways.
Using XMLType, you can easily create a table to hold XML data:
The fall column in this table is of XMLType Use the following INSERT statements to create three XML documents in the falls table:
You can query XML data in the table using various XMLType methods. The existsNode method
Both of the following statements produce the same output:
You can, of course, also work with XML data from within PL/SQL. In the following example, we retrieve the fall column for Munising Falls into a PL/SQL variable that is also of XMLType. Thus, we retrieve the entire XML document into our PL/SQL program, where we can work further with it. After retrieving the document, we extract and print the text from the /fall/url node.
We'd like to call your attention to the following two lines:
In our example, we apply the getStringVal method to the XML document returned by the extract method, thus retrieving the text for the Munising Fall's URL. The extract method returns the contents of the <url> node as a XMLType object, and getStringVal then returns that content as a text string that we can display. You can even index XMLType columns to allow for efficient retrieval of XML documents based on their content. You do this by creating a function-based index, for which you need the QUERY REWRITE privilege. The following example creates a function-based index on the first 80 characters of each falls name:
We had to use the SUBSTR function in the creation of this index. The getStringVal method returns a string that is too long to index, resulting in an ORA-01450: maximum key length (3166) exceeded error. Thus, when creating an index like this, you need to use SUBSTR to restrict the results to some reasonable length. If you decide to use XMLType in any of your applications, be sure to consult Oracle's documentation for more complete and current information. The XML DB Developer's Guide for Oracle Database 10g Release 2 is an important, if not critical, reference for developers working with XML. The SQL Reference also has some useful information on XMLType and on the built-in SQL functions that support XML. 13.6.2. The URI TypesThe URI types
To facilitate your work with URIs, Oracle also provides a UriFactory The URI types are created by the script named dbmsuri.sql $ORACLE_HOME/rdbms/admin. All the types and subtypes are owned by the user SYS. In Oracle9i Database Release 1, you must use the "SYS." prefix to reference the URI types. From Oracle9i Database Release 2 onwards, you do not need to use the "SYS." prefix. The following code example demonstrates the use of HttpUriType:
The output from this code example will be:
For more information on the use of the UriType family, see Chapter 9, Accessing Data Through URIs, of the XML DB Developer's Guide for Oracle Database 10g Release 2. 13.6.3. The Any TypesBeginning with Oracle9i Database Release 1, a family of types known as the Any types
The following predefined types belong to this family:
The Any types are created by a script named dbmsany.sql found in $ORACLE_HOME/rdbms/admin, and are owned by the user SYS. As with the URI types, in Oracle9i Database Release 1 you must use a "SYS." prefix to reference the Any types, but this is no longer necessary beginning in Oracle 9i Database Release 2). In addition to creating the Any types, the dbmsany.sql script also creates a package named DBMS_TYPES
The following example creates two user-defined types representing two kinds of geographic features. The subsequent PL/SQL block then uses SYS.AnyType to define a heterogeneous array of features (i.e., each array element can be of a different datatype). First, you'll need to create the following two types:
Next, execute the following PL/SQL code block:
Finally, your output should appear as follows:
Let's look at this code one piece at a time. The features are stored in a VARRAY, which is initialized as follows:
Working from the inside out and focusing on Grand Sable Falls, you can interpret this code as follows:
VARRAYs were discussed in Chapter 12, and you can read about object types in more detail in Chapter 25. The next significant part of the code is the FOR loop in which each object in the features array is examined. A call to:
returns the fully qualified type name of the current features object. For user-defined objects, the type name is prefixed with the schema name of the user who created the object. We had to include this schema name in our WHEN clauses; for example:
If you're running this example on your own system, be sure to replace the schema we used (GENNICK) with the one that is valid for you.
Once we determined which datatype we were dealing with, we retrieved the specific object using the following call:
In our example, we ignored the return code. There are two possible return code values:
Once we had the object in a variable, it was an easy enough task to write a DBMS_OUTPUT statement specific to that object type. For example, to print information about waterfalls, we used:
For more information on the "Any" family of types:
|