Tuesday, October 20, 2009

Chapter 3. General-Purpose and Conditional Actions








 

 










Chapter 3. General-Purpose and Conditional Actions





Topics in This Chapter





  • General-Purpose Actions



  • Conditional Actions



  • Using Conditional and General-Purpose Actions Together



  • Conditional Custom Actions







Some of the most basic tasks that JSP developers perform involve producing output, setting and accessing scoped variables and JavaBean properties, implementing conditional code, and handling exceptions. All of those tasks are discussed in this chapter, which explores the JSTL general-purpose and conditional actions. The general-purpose actions are discussed in "General-Purpose Actions" on page 102, and the conditional actions are discussed in "Conditional Actions" on page 127.



Besides showing you how to use the JSTL general-purpose and conditional actions, this chapter also illustrates how to perform a number of common tasks for JSP-based applications, including:





  • "Setting Attributes for HTML Elements" on page 104



  • "Retaining Values for HTML Text Elements" on page 106



  • "Accessing Bean Properties" on page 108



  • "Setting Bean Properties and Map Entries" on page 112



  • "Retaining Values for HTML Option Elements" on page 129



  • "Implementing If/Else Constructs" on page 133



  • "Implementing Switch Statement Constructs" on page 136





This chapter concludes with a section on implementing conditional custom actions and a section that shows you how to use the general-purpose and conditional actions together in a simple case study.














     

     


    Entering a Single Command









    Entering a Single Command


    Occasionally, you may want to enter a single command, such as a command to start a program or application. A Run option is provided on the start menu, similar to the Run option in Windows, that is a shortcut for entering a single command. When you select the Run option from the menu (Shortcut: <Alt+F2>) a window opens where you can enter a command.


    The dialog box for KDE, shown on the left, provides a text box where you can enter the command and a Run button that executes the command.



    The Run dialog box in Gnome, shown on the right, provides a list of available applications, allowing you to select one instead of typing the name of the application, and a button that allows you to browse for a file to be run by the program or an application that you start. You can, of course, type in a command if you want.



    If you want to execute a command that produces output, you need to check "Run in terminal," an option that opens a window where the output displays. (In KDE, click the Options button to see the "Run in terminal" check box.) For example, the sort command shown in the KDE dialog box above does not reformat the information in the file. Instead, it outputs the information from the file in sorted order. Thus, to see the information in sorted order, you need to check the "Run in terminal" box, which opens a window where the sorted output displays.









      Appendix B. JSPs and Servlets








       

       














      Appendix B. JSPs and Servlets







      This appendix is meant to be a kind of bridge from your skills as a

      system administrator, which probably include a familiarity with a

      variety of scripting languages, to give you some familiarity with the

      Java development side of Tomcat. Since Tomcat specializes in running

      servlets and JSPs, we discuss what these are in a bit more detail.

      First, though, we review a variety of network software architectures,

      so you have a better idea of where servlets and JSPs fit into the big

      picture of network software development.





      Here are four general Java-centric approaches to networked

      application development. Since almost all web applications need

      access to a backend database, we also say a few words about how the

      Java code accesses the database.









      Web application displays an applet, and the applet uses JDBC to connect to a database




      �Slow; browser incompatibilities





      Download application using Java Web Start; application uses JDBC




      �Avoids browser problem; performance can be slow due to lack of

      caching





      Web application sends pure HTML and uses servlets and JSPs




      �Servlets use JDBC; JSPs, if necessary, use the Java Standard

      Template Library (JSTL)





      �Closest to use of mod_perl, PHP, or CGI





      �Good general approach



      Web application uses servlets, and servlets use EJBs to access database




      �Claimed to be a good

      "enterprise"-scale approach

      (J2EE-style)









      Briefly,

      a servlet is a Java program designed to run in a servlet container

      (we hope you didn't catch that circular definition),

      and a JSP is a web page that can call Java code at request time. If

      you're a system administrator or webmaster, you can

      think of JSPs as just another scripting and templating language for

      HTML pages; you can learn to write JSPs that call Java objects much

      as you might have used objects in JavaScript. The difference is that

      the Java runs on the server side, before the web page is sent to the

      browser. It's more like PHP, or even ASP. Writing

      Java classes such as servlets and JSP custom tags, however, is a task

      probably best left to people trained in Java programming.





      More precisely, a servlet is a Java program that uses the

      javax.servlet package, subclasses either the

      javax.servlet.http.HttpServlet or

      javax.servlet.GenericServlet Java class, performs

      some processing (anything the programmer wants that the servlet

      container allows) in response to user input (such as clicking on a

      link or filling in and submitting a web form), and generates some

      kind of output that might be useful on the Web. A servlet can, of

      course, generate an HTML page, but servlets can and have been written

      to generate graphs and charts in GIF, PNG, and JPEG formats; printed

      documents in PDF; or any format the developer can program.

      We've said it before and we'll say

      it again: you do not need to be a Java programmer to use Tomcat, or

      even to use servlets. There are servlets available that you can use

      without writing any code.





      But JSP is one of the neatest features of Tomcat, so we wanted to say

      a few words about it. A JavaServer Page is an HTML page that can call

      Java language functionality, as well as functionality of other

      languages if the JSP implementation integrates with them (Tomcat

      4's JSP doesn't). Again, you

      don't have to write any Java code to write a JSP,

      although many JSPs that you will find today have some Java code

      embedded in them. The design goal of JSPs is to remove

      "raw" Java code from the web page

      markup and to have the Java code isolated into external modules that

      get loaded into the JSP at runtime. Which reminds me, we meant to let

      you in on a little secret: JSPs actually get dynamically compiled

      into servlets the first time a browser invokes them, so they can do

      anything a servlet can do.





      This appendix takes you through the process of writing a simple JSP.

      We then elaborate on it in several ways, including use of prewritten

      JavaBean components and JSP custom tags (also called custom

      actions
      ). But we won't discuss

      writing any Java components such as servlets,

      JavaBeans, or custom tags; that is well beyond the scope of this

      book. O'Reilly has a number of good books on these

      topics; see http://java.oreilly.com for the latest

      catalog. See in particular these O'Reilly books:

      Java Servlet Programming by Jason Hunter,

      JavaServer Pages by Hans Bergsten, and

      Developing Java Beans by Robert Englander.
















         

         


        Cross-Platform Tools










        Cross-Platform Tools


        • 7-Zip File archiver with high compression ratio

        • http://www.7-zip.org/

        • Aqua Data Studio (Java) Slow, but good for data import/exporthttp://aquafold.com/

        • ArgoUML UML design toolhttp://argouml.tigris.org/

        • CruiseControl Framework for a continuous build processhttp://cruisecontrol.sourceforge.net

        • CVS Source configuration managementhttp://www.nongnu.org/cvs/

        • DbVisualizer Database toolhttp://www.minq.se

        • FreeMind Mind-mapping softwarehttp://freemind.sourceforge.net/

        • Gaim Multi-protocol instant messaging (IM) clienthttp://gaim.sourceforge.net/

        • Image Manipulation Program http://gimp.org/

        • JAR Class Finder Eclipse plug-in utility for finding JAR files containing a given classhttp://www.alphaworks.ibm.com/tech/jarclassfinder

        • J text editor (Java) http://armedbear-j.sourceforge.net/

        • KDiff3 Compare/merge two or three text input files or directorieshttp://kdiff3.sourceforge.net/

        • Mozilla Firefox plug-ins Hundreds of useful plug-ins for Firefox browserhttps://addons.mozilla.org/extensions/

        • Netbeans Fully featured Integrated Development Environment (IDE)http://www.netbeans.org/

        • Nvu Web Authoring Systemhttp://nvu.com/

        • OpenOffice Complete office applications, comparable to Microsoft Officehttp://www.openoffice.org/

        • Poseidon (community edition) UML design toolhttp://gentleware.com

        • SQuirreL SQL Client Manage JDBC compliant databaseshttp://squirrel-sql.sourceforge.net/

        • Sun Java Studio Enterprise IDE with integrated UML toolhttp://developers.sun.com/prodtech/javatools/jsenterprise/

        • TkCVS (includes TkDiff) Graphical interface for CVS and Subversion configuration management systemshttp://www.twobarleycorns.net/tkcvs.html

        • Vim GUI text editor mimics Unix 'Vi'http://www.vim.org/

        • vnc2swf Screen recording toolhttp://www.unixuser.org/%7Eeuske/vnc2swf/

        • XEmacs Text editor and application development systemhttp://www.xemacs.org/

        • Yahoo widgets http://widgets.yahoo.com/












        Chapter 24. Refactoring










         < Free Open Study > 







        Chapter 24. Refactoring



        cc2e.com/2436



        Contents



        • Kinds of Software Evolution page 564

        • Introduction to Refactoring page 565

        • Specific Refactorings page 571

        • Refactoring Safely page 579

        • Refactoring Strategies page 582



        Related Topics



        • Tips for fixing defects: Section 23.3

        • Code-tuning approach: Section 25.6

        • Design in construction: Chapter 5

        • Working classes: Chapter 6

        • High-quality routines: Chapter 7

        • Collaborative construction: Chapter 21

        • Developer testing: Chapter 22

        • Areas likely to change: "Identify Areas Likely to Change" in Section 5.3



        Myth: a well-managed software project conducts methodical requirements development and defines a stable list of the program's responsibilities. Design follows requirements, and it is done carefully so that coding can proceed linearly, from start to finish, implying that most of the code can be written once, tested, and forgotten. According to the myth, the only time that the code is significantly modified is during the software-maintenance phase, something that happens only after the initial version of a system has been delivered.







        All successful software gets changed.

        �Fred Brooks



        Reality: code evolves substantially during its initial development. Many of the changes seen during initial coding are at least as dramatic as changes seen during maintenance. Coding, debugging, and unit testing consume between 30 to 65 percent of the effort on a typical project, depending on the project's size. (See Chapter 27, "How Program Size Affects Construction," for details.) If coding and unit testing were straightforward processes, they would consume no more than 20�30 percent of the total effort on a project. Even on well-managed projects, however, requirements change by about one to four percent per month (Jones 2000). Requirements changes invariably cause corresponding code changes�sometimes substantial code changes.




        Another reality: modern development practices increase the potential for code changes during construction. In older life cycles, the focus�successful or not�was on avoiding code changes. More modern approaches move away from coding predictability. Current approaches are more code-centered, and over the life of a project, you can expect code to evolve more than ever.















           < Free Open Study > 



          31.6 Transport Provider Interface (TPI)



          [ Team LiB ]






          31.6 Transport Provider Interface (TPI)


          In Figure 31.3, we showed that TPI is the service interface into the transport layer from above. Both sockets and XTI use this interface in a STREAMS environment. In Figure 31.3, it is a combination of the sockets library and sockmod, along with a combination of the XTI library and timod, that exchange TPI messages with TCP and UDP.


          TPI is a message-based interface. It defines the messages that are exchanged up and down a stream between the application (e.g., the sockets library) and the transport layer: the format of these messages and what operation each message performs. In many instances, the application sends a request to the provider (such as "bind this local address") and the provider sends back a response ("OK" or "error"). Some events occur asynchronously at the provider (the arrival of a connection request for a server), causing a message or a signal to be sent up the stream.


          We are able to bypass both sockets and XTI and use TPI directly. In this section, we will rewrite our simple daytime client using TPI instead of sockets (Figure 1.5). Using programming languages as an analogy, using sockets is like programming in a high-level language such as C or Pascal, while using TPI directly is like programming in assembly language. We are not advocating the use of TPI directly in real applications. But examining how TPI works and developing this example give us a better understanding of how the sockets library works in a STREAMS environment.


          Figure 31.7 is our tpi_daytime.h header.



          Figure 31.7 Our tpi_daytime.h header.

          streams/tpi_daytime.h




          1 #include "unpxti.h"
          2 #include <sys/stream.h>
          3 #include <sys/tihdr.h>

          4 void tpi_bind(int, const void *, size_t);
          5 void tpi_connect(int, const void *, size_t);
          6 ssize_t tpi_read(int, void *, size_t);
          7 void tpi_close(int);


          We need to include one additional STREAMS header along with <sys/tihdr.h>, which contains the definitions of the structures for all TPI messages.


          Figure 31.8 is the main function for our daytime client.



          Figure 31.8 main function for our daytime client written to TPI.

          streams/tpi_daytime.c




          1 #include "tpi_daytime.h"

          2 int
          3 main(int argc, char **argv)
          4 {
          5 int fd, n;
          6 char recvline[MAXLINE + 1];
          7 struct sockaddr_in myaddr, servaddr;

          8 if (argc != 2)
          9 err_quit("usage: tpi_daytime <IPaddress>");

          10 fd = Open(XTI_TCP, O_RDWR, 0);

          11 /* bind any local address */
          12 bzero(&myaddr, sizeof(myaddr));
          13 myaddr.sin_family = AF_INET;
          14 myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
          15 myaddr.sin_port = htons(0);

          16 tpi_bind(fd, &myaddr, sizeof(struct sockaddr_in));

          17 /* fill in server's address */
          18 bzero(&servaddr, sizeof(servaddr));
          19 servaddr.sin_family = AF_INET;
          20 servaddr.sin_port = htons(13); /* daytime server */
          21 Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

          22 tpi_connect(fd, &servaddr, sizeof(struct sockaddr_in));

          23 for ( ; ; ) {
          24 if ( (n = tpi_read(fd, recvline, MAXLINE)) <= 0) {
          25 if (n == 0)
          26 break;
          27 else
          28 err_sys("tpi_read error");
          29 }
          30 recvline[n] = 0; /* null terminate */
          31 fputs(recvline, stdout);
          32 }
          33 tpi_close(fd);
          34 exit(0);
          35 }



          Open transport provider, bind local address


          10�16 We open the device corresponding to the transport provider (normally /dev/tcp). We fill in an Internet socket address structure with INADDR_ANY and a port of 0, telling TCP to bind any local address to our endpoint. We call our own function tpi_bind (shown shortly) to do the bind.




          Fill in server's address, establish connection


          17�22 We fill in another Internet socket address structure with the server's IP address (taken from the command line) and port (13). We call our tpi_connect function to establish the connection.




          Read data from server, copy to standard output


          23�33 As in our other daytime clients, we just copy data from the connection to standard output, stopping when we receive the EOF from the server (e.g., the FIN). We then call our tpi_close function to close our endpoint.


          Our tpi_bind function is shown in Figure 31.9.




          Fill in T_bind_req structure


          16�20 The <sys/tihdr.h> header defines the T_bind_req structure.





          struct T_bind_req {
          t_scalar_t PRIM_type; /* T_BIND_REQ */
          t_scalar_t ADDR_length; /* address length */
          t_scalar_t ADDR_offset; /* address offset */
          t_uscalar_t CONIND_number; /* connect indications requested */
          /* followed by the protocol address for bind */
          };


          All TPI requests are defined as a structure that begins with a long integer type field. We define our own bind_req structure that begins with the T_bind_req structure, followed by a buffer containing the local address to be bound. TPI says nothing about the contents of this buffer; it is defined by the provider. TCP providers expect this buffer to contain a sockaddr_in structure.


          We fill in the T_bind_req structure, setting the ADDR_length member to the size of the address (16 bytes for an Internet socket address structure) and ADDR_offset to the byte offset of the address (it immediately follows the T_bind_req structure). We are not guaranteed that this location is suitably aligned for the sockaddr_in structure that is stored there, so we call memcpy to copy the caller's structure into our bind_req structure. We set CONIND_number to 0 because we are a client, not a server.




          Call putmsg


          21�23 TPI requires the structure that we just built to be passed to the provider as one M_PROTO message. We therefore call putmsg, specifying our bind_req structure as the control information, with no data and with a flag of 0.




          Call getmsg to read high-priority message


          24�30 The response to our T_BIND_REQ request will be either a T_BIND_ACK message or a T_ERROR_ACK message. These acknowledgment messages are sent as high-priority messages (M_PCPROTO) so we read them using getmsg with a flag of RS_HIPRI. Since the reply is a high-priority message, it will bypass any normal-priority messages on the stream.



          Figure 31.9 tpi_bind function: binds a local address to an endpoint.

          streams/tpi_bind.c




          1 #include "tpi_daytime.h"

          2 void
          3 tpi_bind(int fd, const void *addr, size_t addrlen)
          4 {
          5 struct {
          6 struct T_bind_req msg_hdr;
          7 char addr[128];
          8 } bind_req;
          9 struct {
          10 struct T_bind_ack msg_hdr;
          11 char addr[128];
          12 } bind_ack;
          13 struct strbuf ctlbuf;
          14 struct T_error_ack *error_ack;
          15 int flags;

          16 bind_req.msg_hdr.PRIM_type = T_BIND_REQ;
          17 bind_req.msg_hdr.ADDR_length = addrlen;
          18 bind_req.msg_hdr.ADDR_offset = sizeof(struct T_bind_req);
          19 bind_req.msg_hdr.CONIND_number = 0;
          20 memcpy(bind_req.addr, addr, addrlen); /* sockaddr_in{} */

          21 ctlbuf.len = sizeof(struct T_bind_req) + addrlen;
          22 ctlbuf.buf = (char *) &bind_req;
          23 Putmsg(fd, &ctlbuf, NULL, 0);

          24 ctlbuf.maxlen = sizeof(bind_ack);
          25 ctlbuf.len = 0;
          26 ctlbuf.buf = (char *) &bind_ack;
          27 flags = RS_HIPRI;
          28 Getmsg(fd, &ctlbuf, NULL, &flags);

          29 if (ctlbuf.len < (int) sizeof(long))
          30 err_quit("bad length from getmsg");

          31 switch (bind_ack.msg_hdr.PRIM_type) {
          32 case T_BIND_ACK:
          33 return;

          34 case T_ERROR_ACK:
          35 if (ctlbuf.len < (int) sizeof(struct T_error_ack))
          36 err_quit("bad length for T_ERROR_ACK");
          37 error_ack = (struct T_error_ack *) &bind_ack.msg_hdr;
          38 err_quit("T_ERROR_ACK from bind (%d, %d)",
          39 error_ack->TLI_error, error_ack->UNIX_error);

          40 default:
          41 err_quit("unexpected message type: %d", bind_ack.msg_hdr.PRIM_type);
          42 }
          43 }


          These two messages are as follows:





          struct T_bind_ack {
          t_scalar_t PRIM_type; /* T_BIND_ACK */
          t_scalar_t ADDR_length; /* address length */
          t_scalar_t ADDR_offset; /* address offset */
          t_uscalar_t CONIND_number; /* connect ind to be queued */
          /* followed by the bound address */
          };

          struct T_error_ack {
          t_scalar_t PRIM_type; /* T_ERROR_ACK */
          t_scalar_t ERROR_prim /* primitive in error */
          t_scalar_t TLI_error; /* TLI error code */
          t_scalar_t UNIX_error; /* UNIX error code */
          };


          All these messages begin with the type, so we can read the reply assuming it is a T_BIND_ACK message, look at the type, and process the message accordingly. We do not expect any data from the provider, so we specify a null pointer as the third argument to getmsg.


          When we verify that the amount of control information returned is at least the size of a long integer, we must be careful to cast the sizeof value to an integer. The sizeof operator returns an unsigned integer value, but it is possible for the returned len field to be �1. But since the less-than comparison is comparing a signed value on the left to an unsigned value on the right, the compiler casts the signed value to an unsigned value. On a two's-complement architecture, �1, considered as an unsigned value, is very large, causing �1 to be greater than 4 (if we assume a long integer occupies 4 bytes).




          Process reply


          31�33 If the reply is T_BIND_ACK, the bind was successful and we return. The actual address that was bound to the endpoint is returned in the addr member of our bind_ack structure, which we ignore.


          34�39 If the reply is T_ERROR_ACK, we verify that the entire message was received and then print the three return values in the structure. In this simple program, we terminate when an error occurs; we do not return to the caller.


          We can see these errors from the bind request by changing our main function to bind some port other than 0. For example, if we try to bind port 1 (which requires superuser privileges, since it is a port less than 1024), we get





          solaris % tpi_daytime 127.0.0.1
          T_ERROR_ACK from bind (3, 0)


          The error TACCES has the value 3 on this system. If we change the port to a value greater than 1023, but one that is currently in use by another TCP endpoint, we get





          solaris % tpi_daytime 127.0.0.1
          T_ERROR_ACK from bind (23, 0)


          The error TADDRBUSY has the value 23 on this system.


          The next function, shown in Figure 31.10, is tpi_connect, which establishes the connection with the server.




          Fill in request structure and send to provider


          18�26 TPI defines a T_conn_req structure that contains the protocol address and options for the connection.





          struct T_conn_req {
          t_scalar_t PRIM_type; /* T_CONN_REQ */
          t_scalar_t DEST_length; /* destination address length */
          t_scalar_t DEST_offset; /* destination address offset */
          t_scalar_t OPT_length; /* options length */
          t_scalar_t OPT_offset; /* options offset */
          /* followed by the protocol address and options for connection */
          };


          As in our tpi_bind function, we define our own structure named conn_req, which includes a T_conn_req structure along with room for the protocol address. We fill in our conn_req structure, setting the two members dealing with options to 0. We call putmsg with only control information and a flag of 0 to send an M_PROTO message down the stream.



          Figure 31.10 tpi_connect function: establishes connection with server.

          streams/tpi_connect.c




          1 #include "tpi_daytime.h"

          2 void
          3 tpi_connect(int fd, const void *addr, size_t addrlen)
          4 {
          5 struct {
          6 struct T_conn_req msg_hdr;
          7 char addr[128];
          8 } conn_req;
          9 struct {
          10 struct T_conn_con msg_hdr;
          11 char addr[128];
          12 } conn_con;
          13 struct strbuf ctlbuf;
          14 union T_primitives rcvbuf;
          15 struct T_error_ack *error_ack;
          16 struct T_discon_ind *discon_ind;
          17 int flags;

          18 conn_req.msg_hdr.PRIM_type = T_CONN_REQ;
          19 conn_req.msg_hdr.DEST_length = addrlen;
          20 conn_req.msg_hdr.DEST_offset = sizeof(struct T_conn_req);
          21 conn_req.msg_hdr.OPT_length = 0;
          22 conn_req.msg_hdr.OPT_offset = 0;
          23 memcpy(conn_req.addr, addr, addrlen); /* sockaddr_in{} */

          24 ctlbuf.len = sizeof(struct T_conn_req) + addrlen;
          25 ctlbuf.buf = (char *) &conn_req;
          26 Putmsg(fd, &ctlbuf, NULL, 0);

          27 ctlbuf.maxlen = sizeof(union T_primitives);
          28 ctlbuf.len = 0;
          29 ctlbuf.buf = (char *) &rcvbuf;
          30 flags = RS_HIPRI;
          31 Getmsg(fd, &ctlbuf, NULL, &flags);

          32 if (ctlbuf.len < (int) sizeof(long))
          33 err_quit("tpi_connect: bad length from getmsg");

          34 switch (rcvbuf.type) {
          35 case T_OK_ACK:
          36 break;

          37 case T_ERROR_ACK:
          38 if (ctlbuf.len < (int) sizeof(struct T_error_ack))
          39 err_quit("tpi_connect: bad length for T_ERROR_ACK");
          40 error_ack = (struct T_error_ack *) &rcvbuf;
          41 err_quit("tpi_connect: T_ERROR_ACK from conn (%d, %d)",
          42 error_ack->TLI_error, error_ack->UNIX_error);

          43 default:
          44 err_quit("tpi_connect: unexpected message type: %d", rcvbuf.type);
          45 }

          46 ctlbuf.maxlen = sizeof(conn_con);
          47 ctlbuf.len = 0;
          48 ctlbuf.buf = (char *) &conn_con;
          49 flags = 0;
          50 Getmsg(fd, &ctlbuf, NULL, &flags);

          51 if (ctlbuf.len < (int) sizeof(long))
          52 err_quit("tpi_connect2: bad length from getmsg");

          53 switch (conn_con.msg_hdr.PRIM_type) {
          54 case T_CONN_CON:
          55 break;

          56 case T_DISCON_IND:
          57 if (ctlbuf.len < (int) sizeof(struct T_discon_ind))
          58 err_quit("tpi_connect2: bad length for T_DISCON_IND");
          59 discon_ind = (struct T_discon_ind *) &conn_con.msg_hdr;
          60 err_quit("tpi_connect2: T_DISCON_IND from conn (%d)",
          61 discon_ind->DISCON_reason);

          62 default:
          63 err_quit("tpi_connect2: unexpected message type: %d",
          64 conn_con.msg_hdr.PRIM_type);
          65 }
          66 }




          Read response


          27�45 We call getmsg, expecting to receive either a T_OK_ACK message if the connection establishment was started, or a T_ERROR_ACK message (which we showed earlier).





          struct T_ok_ack {
          t_scalar_t PRIM_type; /* T_OK_ACK */
          t_scalar_t CORRECT_prim; /* correct primitive */
          };


          In case of an error, we terminate. Since we do not know what type of message we will receive, a union named T_primitives is defined as the union of all the possible requests and replies, and we allocate one of these that we use as the input buffer for the control information when we call getmsg.




          Wait for connection to be established


          46�65 The successful T_OK_ACK message that was just received only tells us that the connection establishment was started. We must now wait for a T_CONN_CON message to tell us that the other end has confirmed the connection request.





          struct T_conn_con {
          t_scalar_t PRIM_type; /* T_CONN_CON */
          t_scalar_t RES_length; /* responding address length */
          t_scalar_t RES_offset; /* responding address offset */
          t_scalar_t OPT_length; /* option length */
          t_scalar_t OPT_offset; /* option offset */
          /* followed by peer's protocol address and options */
          };


          We call getmsg again, but the expected message is sent as an M_PROTO message, not an M_PCPROTO message, so we set the flags to 0. If we receive the T_CONN_CON message, the connection is established and we return, but if the connection was not established (either the peer process was not running, a timeout occurred, or whatever), a T_DISCON_IND message is sent up the stream instead.





          struct T_discon_ind {
          t_scalar_t PRIM_type; /* T_DISCON_IND */
          t_scalar_t DISCON_reason; /* disconnect reason */
          t_scalar_t SEQ_number; /* sequence number */
          };


          We can see the different errors that are returned by the provider. We first specify the IP address of a host that is not running the daytime server.





          solaris % tpi_daytime 192.168.1.10
          tpi_connect2: T_DISCON_IND from conn (146)


          The error of 146 corresponds to ECONNREFUSED. Next, we specify an IP address that is not connected to the Internet.





          solaris % tpi_daytime 192.3.4.5
          tpi_connect2: T_DISCON_IND from conn (145)


          The error this time is ETIMEDOUT. But if we run our program again, specifying the same IP address, we get a different error.





          solaris % tpi_daytime 192.3.4.5
          tpi_connect2: T_DISCON_IND from conn (148)


          The error this time is EHOSTUNREACH. The difference in the last two results is that the first time, no ICMP "host unreachable" errors were returned, while the next time, this error was returned.


          The next function is tpi_read, shown in Figure 31.11. It reads data from a stream.



          Figure 31.11 tpi_read function: reads data from a stream.

          streams/tpi_read.c




          1 #include "tpi_daytime.h"

          2 ssize_t
          3 tpi_read(int fd, void *buf, size_t len)
          4 {
          5 struct strbuf ctlbuf;
          6 struct strbuf datbuf;
          7 union T_primitives rcvbuf;
          8 int flags;

          9 ctlbuf.maxlen = sizeof(union T_primitives);
          10 ctlbuf.buf = (char *) &rcvbuf;

          11 datbuf.maxlen = len;
          12 datbuf.buf = buf;
          13 datbuf.len = 0;

          14 flags = 0;
          15 Getmsg(fd, &ctlbuf, &datbuf, &flags);

          16 if (ctlbuf.len >= (int) sizeof(long)) {
          17 if (rcvbuf.type == T_DATA_IND)
          18 return (datbuf.len);
          19 else if (rcvbuf.type == T_ORDREL_IND)
          20 return (0);
          21 else
          22 err_quit("tpi_read: unexpected type %d", rcvbuf.type);
          23 } else if (ctlbuf.len == -1)
          24 return (datbuf.len);
          25 else
          26 err_quit("tpi_read: bad length from getmsg");
          27 }




          Read control and data; process reply


          9�26 This time, we call getmsg to read both control information and data. The strbuf structure for the data points to the caller's buffer. Four different scenarios can occur on the stream:


          • The data can arrive as an M_DATA message, which is indicated by the returned control length being set to �1. The data was copied into the caller's buffer by getmsg, and we just return the length of this data as the return value of the function.

          • The data can arrive as a T_DATA_IND message, in which case, the control information will be a T_data_ind structure.




            struct T_data_ind {
            t_scalar_t PRIM_type; /* T_DATA_IND */
            t_scalar_t MORE_flag; /* more data */
            };

            If this message is returned, we ignore the MORE_flag member (it will never be set for a stream protocol such as TCP) and just return the length of the data that was copied into the caller's buffer by getmsg.

          • A T_ORDREL_IND message is returned if all the data has been consumed and the next item is a FIN.




            struct T_ordrel_ind {
            t_scalar_t PRIM_type; /* T_ORDREL_IND */
            };

            This is the orderly release. We just return 0, indicating to the caller that the EOF has been encountered on the connection.

          • A T_DISCON_IND message is returned if a disconnect has been received.


          Our final function is tpi_close, shown in Figure 31.12.



          Figure 31.12 tpi_close function: sends an orderly release to the peer.

          streams/tpi_close.c




          1 #include "tpi_daytime.h"

          2 void
          3 tpi_close(int fd)
          4 {
          5 struct T_ordrel_req ordrel_req;
          6 struct strbuf ctlbuf;

          7 ordrel_req.PRIM_type = T_ORDREL_REQ;

          8 ctlbuf.len = sizeof(struct T_ordrel_req);
          9 ctlbuf.buf = (char *) &ordrel_req;
          10 Putmsg(fd, &ctlbuf, NULL, 0);

          11 Close(fd);
          12 }




          Send orderly release to peer


          7�10 We build a T_ordrel_req structure





          struct T_ordrel_req {
          long PRIM_type; /* T_ORDREL_REQ */
          };


          and send it as an M_PROTO message using putmsg.


          This example has given us a flavor for TPI. The application sends messages down a stream to the provider (requests) and the provider sends messages up the stream (replies). Some exchanges follow a simple request-reply scenario (binding a local address), while others may take a while (establishing a connection), allowing us to do something while we wait for the reply. Our choice of writing a TCP client using TPI was done for simplicity; writing a TCP server and handling connections are much harder.


          We can compare the number of system calls required for the network operations that we have seen in this chapter when using TPI versus a kernel that implements sockets within the kernel. Binding a local address takes two system calls with TPI, but only one with kernel sockets (TCPv2, p. 454). To establish a connection on a blocking descriptor takes three system calls with TPI, but only one with kernel sockets (TCPv2, p. 466).







            [ Team LiB ]



            Section 25.143. History.go( ): revisit a URL










            25.143. History.go( ): revisit a URL


            JavaScript 1.0



            25.143.1. Synopsis



            history.go(relative_position)
            history.go(target_string)




            25.143.1.1. Arguments



            relative_position


            The relative position in the history list of the URL to be visited.




            target_string


            A URL (or URL fragment) to be visited, if a matching URL exists in the history list.






            25.143.2. Description


            The first form of the History.go( ) method takes an integer argument and causes the browser to visit the URL that is the specified number of positions away in the history list maintained by the History object. Positive arguments move the browser forward through the list, and negative arguments move it backward. Thus, calling history.go(-1) is equivalent to calling history.back( ) and produces the same effect as clicking on the Back button. Similarly, history.go(3) revisits the same URL that would be visited by calling history.forward( ) three times.


            The second form of the History.go( ) takes a string argument and causes the browser to revisit the first (i.e., most recently visited) URL that contains the specified string. This form of the method is not well specified and may work differently on different browsers. For example, Microsoft's documentation specifies that the argument must match the URL of a previously specified site exactly, while old Netscape documentation (Netscape created the History object) says that the argument may be a substring of a previously visited URL.













            Section 16.3.&nbsp; Initialization of Bridging Code










            16.3. Initialization of Bridging Code
















            The bridging code can be either built into the kernel or compiled as a module. The initialization and cleanup routines, br_init and br_uninit, respectively, are defined in /net/bridge/br.c.


            Initialization consists of:


            • Initializing the forwarding database by creating a slab cache (a memory area) to use for allocating net_bridge_fdb_entry structures (br_fdb_init).

            • Initializing the function pointer br_ioctl_hook to the routine that will take care of ioctl commands. ioctl commands are described in Chapter 17.

            • Initializing the function pointer br_handle_frame_hook to the routine that will process ingress BPDUs. See the section "Handling Ingress Traffic."

            • Registering a callback with the neTDev_chain notification chain. See the section "netdevice Notification Chain."


            When the kernel is compiled with support for Bridging-Firewalling
            , the option is initialized here with br_netfilter_init. Later, in Figure 16-11 in the section "The Big Picture," you can see where all the Netfilter hooks are located in the core routines used by the bridging code to process ingress and egress traffic.



            Figure 16-6. Relationships between the main data structure types



            Bridging-Firewalling is added to the kernel with the option "Networking support Networking options Network packet filtering (replaces ipchains) Bridged IP/ARP packet filtering". The Ethernel-Bridging-Tables option (i.e., ebtables) is initialized elsewhere (see the section "Data Frames Versus BPDUs").


            The cleanup routine br_deinit simply undoes what was done by br_init.












            16.4 Charting Data with a TableModel




            I l@ve RuBoard










            16.4 Charting Data with a TableModel



            Our last example shows that the table
            machinery isn't just for building tables; you can
            use it to build other kinds of components (like the pie chart in
            Figure 16-6). If you think about it,
            there's no essential difference between a pie chart,
            a bar chart, and many other kinds of data displays; they are all
            different ways of rendering data that's logically
            kept in a table. When that's the case, it is easy to
            use a TableModel to manage the data and build your
            own component for the display.



            With AWT, building a new component was straightforward: you simply
            created a subclass of Component. With Swing,
            it's a little more complex because of the
            distinction between the component itself and the user-interface
            implementation. But it's not terribly hard,
            particularly if you don't want to brave the waters
            of the Pluggable L&F. In this case, there's no
            good reason to make pie charts that look different on different
            platforms, so we'll opt for simplicity.
            We'll call our new component a
            TableChart; it extends
            JComponent. Its big responsibility is keeping the
            data for the component updated; to this end, it listens for
            TableModelEvents from the
            TableModel to determine when changes have been
            made.



            To do the actual drawing, TableChart relies on a
            delegate, PieChartPainter. To keep things
            flexible, PieChartPainter is a subclass of
            ChartPainter, which gives us the option of
            building other kinds of chart painters (bar chart painters, etc.) in
            the future. ChartPainter extends
            ComponentUI, which is the base class for user
            interface delegates. Here's where the
            model-view-controller architecture comes into play. The table model
            contains the actual data, TableChart is a
            controller that tells a delegate what and when to paint, and
            PieChartPainter is the view that paints a
            particular kind of representation on the screen.



            Just to prove that the same TableModel can be used
            with any kind of display, we also display an old-fashioned
            JTable using the same data�which turns out
            to be convenient because we can use the
            JTable's built-in editing
            capabilities to modify the data. If you change any field (including
            the name), the pie chart immediately changes to reflect the new data.



            The TableChart class is particularly interesting
            because it shows the "other side"
            of table model event processing. In the
            PagingModel of the earlier example, we had to
            generate events as the data changed. Here, you see how those events
            might be handled. The TableChart has to register
            itself as a TableModelListener and respond to
            events so that it can redraw itself when you edit the table. The
            TableChart also implements one (perhaps unsightly)
            shortcut: it presents the data by summing and averaging along the
            columns. It would have been more work (but not much more) to present
            the data in any particular column, letting the user choose the column
            to be displayed. (See Figure 16-6.)




            Figure 16-6. A chart component using a TableModel



            Here's the application that produces both the pie
            chart and the table. It includes the TableModel as
            an anonymous inner class. This inner class is very simple, much
            simpler than the models we used earlier in this chapter; it provides
            an array for storing the data, methods to get and set the data, and
            methods to provide other information about the table. Notice that we
            provided an isCellEditable( ) method that always
            returns true (the default method always returns
            false). Because we're allowing
            the user to edit the table, we must also override
            setValueAt( ); our implementation updates the
            data array and calls
            fireTableRowsUpdated( ) to notify any listeners
            that data has changed and they need to redraw. The rest of
            ChartTester just sets up the display; we display
            the pie chart as a pop up.



            // ChartTester.java
            //
            import java.awt.*;
            import java.awt.event.*;
            import javax.swing.*;
            import javax.swing.table.*;

            public class ChartTester extends JFrame {

            public ChartTester( ) {
            super("Simple JTable Test");
            setSize(300, 200);
            setDefaultCloseOperation(EXIT_ON_CLOSE);


            TableModel tm = new AbstractTableModel( ) {
            String data[][] = {
            {"Ron", "0.00", "68.68", "77.34", "78.02"},
            {"Ravi", "0.00", "70.89", "64.17", "75.00"},
            {"Maria", "76.52", "71.12", "75.68", "74.14"},
            {"James", "70.00", "15.72", "26.40", "38.32"},
            {"Ellen", "80.32", "78.16", "83.80", "85.72"}
            };
            String headers[] = { "", "Q1", "Q2", "Q3", "Q4" };
            public int getColumnCount( ) { return headers.length; }
            public int getRowCount( ) { return data.length; }
            public String getColumnName(int col) { return headers[col]; }
            public Class getColumnClass(int col) {
            return (col == 0) ? String.class : Number.class;
            }

            public boolean isCellEditable(int row, int col) { return true; }
            public Object getValueAt(int row, int col) { return data[row][col]; }
            public void setValueAt(Object value, int row, int col) {
            data[row][col] = (String)value;
            fireTableRowsUpdated(row,row);
            }
            };

            JTable jt = new JTable(tm);
            JScrollPane jsp = new JScrollPane(jt);
            getContentPane( ).add(jsp, BorderLayout.CENTER);

            final TableChartPopup tcp = new TableChartPopup(tm);
            JButton button = new JButton("Show me a chart of this table");
            button.addActionListener(new ActionListener( ) {
            public void actionPerformed(ActionEvent ae) {
            tcp.setVisible(true);
            }
            } );
            getContentPane( ).add(button, BorderLayout.SOUTH);
            }

            public static void main(String args[]) {
            ChartTester ct = new ChartTester( );
            ct.setVisible(true);
            }
            }


            The TableChart object is actually made of three
            pieces. The TableChart class extends
            JComponent, which provides all the machinery for
            getting a new component on the screen. It implements
            TableModelListener because it has to register and
            respond to TableModelEvents.



            // TableChart.java
            // A chart-generating class that uses the TableModel interface to get
            // its data
            //
            import java.awt.*;
            import java.awt.event.*;
            import javax.swing.*;
            import javax.swing.event.*;
            import javax.swing.table.*;

            public class TableChart extends JComponent implements TableModelListener {

            protected TableModel model;
            protected ChartPainter cp;
            protected double[] percentages; // Pie slices
            protected String[] labels; // Labels for slices
            protected String[] tips; // Tooltips for slices

            protected java.text.NumberFormat formatter =
            java.text.NumberFormat.getPercentInstance( );

            public TableChart(TableModel tm) {
            setUI(cp = new PieChartPainter( ));
            setModel(tm);
            }

            public void setTextFont(Font f) { cp.setTextFont(f); }
            public Font getTextFont( ) { return cp.getTextFont( ); }

            public void setTextColor(Color c) { cp.setTextColor(c); }
            public Color getTextColor( ) { return cp.getTextColor( ); }

            public void setColor(Color[] clist) { cp.setColor(clist); }
            public Color[] getColor( ) { return cp.getColor( ); }

            public void setColor(int index, Color c) { cp.setColor(index, c); }
            public Color getColor(int index) { return cp.getColor(index); }

            public String getToolTipText(MouseEvent me) {
            if (tips != null) {
            int whichTip = cp.indexOfEntryAt(me);
            if (whichTip != -1) {
            return tips[whichTip];
            }
            }
            return null;
            }

            public void tableChanged(TableModelEvent tme) {
            // Rebuild the arrays only if the structure changed.
            updateLocalValues(tme.getType( ) != TableModelEvent.UPDATE);
            }

            public void setModel(TableModel tm) {
            // Get listener code correct.
            if (tm != model) {
            if (model != null) {
            model.removeTableModelListener(this);
            }
            model = tm;
            model.addTableModelListener(this);
            updateLocalValues(true);
            }
            }

            public TableModel getModel( ) { return model; }

            // Run through the model and count every cell (except the very first column,
            // which we assume is the slice label column).
            protected void calculatePercentages( ) {
            double runningTotal = 0.0;
            for (int i = model.getRowCount( ) - 1; i >= 0; i--) {
            percentages[i] = 0.0;
            for (int j = model.getColumnCount( ) - 1; j >=0; j--) {

            // First, try the cell as a Number object.
            Object val = model.getValueAt(i,j);
            if (val instanceof Number) {
            percentages[i] += ((Number)val).doubleValue( );
            }
            else if (val instanceof String) {
            // Oops, it wasn't numeric, so try it as a string.
            try {
            percentages[i]+=Double.valueOf(val.toString( )).doubleValue( );
            }
            catch(Exception e) {
            // Not a numeric string. Give up.
            }
            }
            }
            runningTotal += percentages[i];
            }

            // Make each entry a percentage of the total.
            for (int i = model.getRowCount( ) - 1; i >= 0; i--) {
            percentages[i] /= runningTotal;
            }
            }

            // This method just takes the percentages and formats them as tooltips.
            protected void createLabelsAndTips( ) {
            for (int i = model.getRowCount( ) - 1; i >= 0; i--) {
            labels[i] = (String)model.getValueAt(i, 0);
            tips[i] = formatter.format(percentages[i]);
            }
            }

            // Call this method to update the chart. We try to be more efficient here by
            // allocating new storage arrays only if the new table has a different number of
            // rows.
            protected void updateLocalValues(boolean freshStart) {
            if (freshStart) {
            int count = model.getRowCount( );
            if ((tips == null) || (count != tips.length)) {
            percentages = new double[count];
            labels = new String[count];
            tips = new String[count];
            }
            }
            calculatePercentages( );
            createLabelsAndTips( );

            // Now that everything's up-to-date, reset the chart painter with the new
            // values.
            cp.setValues(percentages);
            cp.setLabels(labels);

            // Finally, repaint the chart.
            repaint( );
            }
            }


            The constructor for TableChart sets the user
            interface for this class to be the PieChartPainter
            (which we discuss shortly). It also saves the
            TableModel for the component by calling our
            setModel( ) method; providing a separate
            setModel( ) (rather than saving the model in the
            constructor) lets us change the model at a later time�a nice
            feature for a real component, though we don't take
            advantage of it in this example. We also override
            getToolTipText( ), which is called with a
            MouseEvent as an argument. This method calls the
            ChartPainter's
            indexOfEntryAt( ) method to figure out which of
            the model's entries corresponds to the current mouse
            position, looks up the appropriate tooltip, and returns it.



            tableChanged( ) listens for
            TableModelEvents. It delegates the call to another
            method, updateLocalValues( ), with an argument of
            true if the table's structure has
            changed (e.g., rows added or deleted), and false
            if only the values have changed. The rest of
            TableChart updates the data when the change
            occurs. The focal point of this work is updateLocalValues( ); calculatePercentages( ) and
            createLabelsAndTips( ) are helper methods that
            keep the work modular. If updateLocalValues( ) is
            called with its argument set to true, it finds out
            the new number of rows for the table and creates new arrays to hold
            the component's view of the data. It calculates
            percentages, retrieves labels, makes up tooltips, and calls the
            ChartPainter (the user interface object) to give
            it the new information. It ends by calling repaint( ) to redraw the screen with updated data.



            ChartPainter is
            the actual user-interface class. It is abstract; we subclass it to
            implement specific kinds of charts. It extends the
            ComponentUI class, which makes it sound rather
            complex, but it isn't. We've made
            one simplifying assumption: the chart looks the same in any L&F.
            (The component in which the chart is embedded changes its appearance,
            but that's another issue�and one we
            don't have to worry about.) All our
            ComponentUI has to do is implement paint( ), which we leave abstract, forcing the subclass to
            implement it. Our other abstract method, indexOfEntryAt( ), is required by TableChart.



            // ChartPainter.java
            // A simple, chart-drawing UI base class. This class tracks the basic fonts and
            // colors for various types of charts, including pie and bar. The paint( ) method is
            // abstract and must be implemented by subclasses for each type.
            //
            import java.awt.*;
            import java.awt.event.*;
            import javax.swing.*;
            import javax.swing.plaf.*;

            public abstract class ChartPainter extends ComponentUI {

            protected Font textFont = new Font("Serif", Font.PLAIN, 12);
            protected Color textColor = Color.black;
            protected Color colors[] = new Color[] {
            Color.red, Color.blue, Color.yellow, Color.black, Color.green,
            Color.white, Color.gray, Color.cyan, Color.magenta, Color.darkGray
            };
            protected double values[] = new double[0];
            protected String labels[] = new String[0];

            public void setTextFont(Font f) { textFont = f; }
            public Font getTextFont( ) { return textFont; }

            public void setColor(Color[] clist) { colors = clist; }
            public Color[] getColor( ) { return colors; }

            public void setColor(int index, Color c) { colors[index] = c; }
            public Color getColor(int index) { return colors[index]; }

            public void setTextColor(Color c) { textColor = c; }
            public Color getTextColor( ) { return textColor; }

            public void setLabels(String[] l) { labels = l; }
            public void setValues(double[] v) { values = v; }

            public abstract int indexOfEntryAt(MouseEvent me);
            public abstract void paint(Graphics g, JComponent c);
            }


            There's not much mystery here. Except for the two
            abstract methods, these methods just maintain various simple
            properties of ChartPainter: the colors used for
            painting, the font, and the labels and values for the chart.



            The real work takes place in the PieChartPainter
            class, which implements the indexOfEntryAt( ) and
            paint( ) methods. The indexOfEntryAt( ) method allows our TableChart class to
            figure out which tooltip to show. The paint( )
            method allows us to draw a pie chart of our data.



            // PieChartPainter.java
            // A pie chart implementation of the ChartPainter class
            //
            import java.awt.*;
            import java.awt.event.*;
            import javax.swing.*;
            import javax.swing.plaf.*;

            public class PieChartPainter extends ChartPainter {

            protected static PieChartPainter chartUI = new PieChartPainter( );
            protected int originX, originY;
            protected int radius;

            private static double piby2 = Math.PI / 2.0;
            private static double twopi = Math.PI * 2.0;
            private static double d2r = Math.PI / 180.0; // Degrees to radians
            private static int xGap = 5;
            private static int inset = 40;

            public int indexOfEntryAt(MouseEvent me) {
            int x = me.getX( ) - originX;
            int y = originY - me.getY( ); // Upside-down coordinate system

            // Is (x,y) in the circle?
            if (Math.sqrt(x*x + y*y) > radius) { return -1; }

            double percent = Math.atan2(Math.abs(y), Math.abs(x));
            if (x >= 0) {
            if (y <= 0) { // (IV)
            percent = (piby2 - percent) + 3 * piby2; // (IV)
            }
            }
            else {
            if (y >= 0) { // (II)
            percent = Math.PI - percent;
            }
            else { // (III)
            percent = Math.PI + percent;
            }
            }
            percent /= twopi;
            double t = 0.0;
            if (values != null) {
            for (int i = 0; i < values.length; i++) {
            if (t + values[i] > percent) {
            return i;
            }
            t += values[i];
            }
            }
            return -1;
            }

            public void paint(Graphics g, JComponent c) {
            Dimension size = c.getSize( );
            originX = size.width / 2;
            originY = size.height / 2;
            int diameter = (originX < originY ? size.width - inset
            : size.height - inset);
            radius = (diameter / 2) + 1;
            int cornerX = (originX - (diameter / 2));
            int cornerY = (originY - (diameter / 2));

            int startAngle = 0;
            int arcAngle = 0;
            for (int i = 0; i < values.length; i++) {
            arcAngle = (int)(i < values.length - 1 ?
            Math.round(values[i] * 360) :
            360 - startAngle);
            g.setColor(colors[i % colors.length]);
            g.fillArc(cornerX, cornerY, diameter, diameter,
            startAngle, arcAngle);
            drawLabel(g, labels[i], startAngle + (arcAngle / 2));
            startAngle += arcAngle;
            }
            g.setColor(Color.black);
            g.drawOval(cornerX, cornerY, diameter, diameter); // Cap the circle.
            }

            public void drawLabel(Graphics g, String text, double angle) {
            g.setFont(textFont);
            g.setColor(textColor);
            double radians = angle * d2r;
            int x = (int) ((radius + xGap) * Math.cos(radians));
            int y = (int) ((radius + xGap) * Math.sin(radians));
            if (x < 0) {
            x -= SwingUtilities.computeStringWidth(g.getFontMetrics( ), text);
            }
            if (y < 0) {
            y -= g.getFontMetrics( ).getHeight( );
            }
            g.drawString(text, x + originX, originY - y);
            }

            public static ComponentUI createUI(JComponent c) {
            return chartUI;
            }
            }


            There's nothing really complex here;
            it's just a lot of trigonometry and a little bit of
            simple AWT drawing. paint( ) is called with a
            graphics context and a JComponent as arguments;
            the JComponent allows you to figure out the size
            of the area we have to work with.



            Here's the code for the pop up containing the chart:



            // TableChartPopup.java
            //
            import java.awt.*;
            import java.awt.event.*;
            import javax.swing.*;
            import javax.swing.table.*;

            public class TableChartPopup extends JFrame {

            public TableChartPopup(TableModel tm) {
            super("Table Chart");
            setSize(300,200);
            TableChart tc = new TableChart(tm);
            getContentPane( ).add(tc, BorderLayout.CENTER);
            // Use the following line to turn on tooltips:
            ToolTipManager.sharedInstance( ).registerComponent(tc);
            }
            }


            As you can see, the TableChart component can be
            used on its own without a JTable. We just need a
            model to base it on. You could expand this example to chart only
            selected rows or columns, but we'll leave that as an
            exercise that you can do on your own.











              I l@ve RuBoard



              Modeling Out Loud



              [ Team LiB ]





              Modeling Out Loud


              The detachment of speech from other forms of communication is a particularly great loss because we humans have a genius for spoken language. Unfortunately, when people speak, they usually don't use the language of the domain model.


              That statement may not ring true for you initially, and indeed there are exceptions. But the next time you attend a requirements or design discussion, really listen. You'll hear descriptions of features in business jargon or layman's versions of the jargon. You'll hear talk about technical artifacts and concrete functionality. Sure, you'll hear terms from the domain model; obvious nouns in the common language from the business jargon will typically be coded as objects, and so those terms will tend to be mentioned. But do you hear phrases that could even remotely be described in terms of relationships and interactions in your current domain model?


              One of the best ways to refine a model is to explore with speech, trying out loud various constructs from possible model variations. Rough edges are easy to hear.


              "If we give the Routing Service an origin, destination, and arrival time, it can look up the stops the cargo will have to make and, well . . . stick them in the database." (vague and technical)

              "The origin, destination, and so on . . . it all feeds into the Routing Service, and we get back an Itinerary that has everything we need in it." (more complete, but verbose)

              "A Routing Service finds an Itinerary that satisfies a Route Specification." (concise)


              It is vital that we play around with words and phrases, harnessing our linguistic abilities to the modeling effort, just as it is vital to engage our visual/spatial reasoning by sketching diagrams. Just as we employ our analytical abilities with methodical analysis and design, and that mysterious "feel" of the code. These ways of thinking complement each other, and it takes all of them to find useful models and designs. Of all of these, experimenting with language is most often overlooked. (Part III of this book will delve into this discovery process and show this interplay in several dialogs.)


              In fact, our brains seem to be somewhat specialized for dealing with complexity in spoken language (one good treatment for laymen, like myself, is The Language Instinct, by Steven Pinker [Pinker 1994]). For example, when people of different language backgrounds come together for commerce, if they don't have a common language they invent one, called a pidgin. The pidgin is not as comprehensive as the speakers' original languages, but it is suited to the task at hand. When people are talking, they naturally discover differences in interpretation and the meaning of their words, and they naturally resolve those differences. They find rough spots in the language and smooth them out.


              Once I took an intensive Spanish class in college. The rule in the classroom was that not a word of English could be spoken. At first, it was frustrating. It felt very unnatural, and required a lot of self-discipline. But eventually my classmates and I broke through to a level of fluency that we could never have reached through exercises on paper.


              As we use the UBIQUITOUS LANGUAGE of the domain model in discussions�especially discussions in which developers and domain experts hash out scenarios and requirements�we become more fluent in the language and teach each other its nuances. We naturally come to share the language that we speak in a way that never happens with diagrams and documents.


              Bringing about a UBIQUITOUS LANGUAGE on a software project is easier said than done, and we have to fully employ our natural talents to pull it off. Just as humans' visual and spatial capabilities let us convey and process information rapidly in graphical overviews, we can exploit our innate talent for grammatical, meaningful language to drive model development.


              Therefore, as an addendum to the UBIQUITOUS LANGUAGE pattern:


              Play with the model as you talk about the system. Describe scenarios out loud using the elements and interactions of the model, combining concepts in ways allowed by the model. Find easier ways to say what you need to say, and then take those new ideas back down to the diagrams and code.





                [ Team LiB ]



                Section 3.6. Autoboxing and Unboxing







                3.6. Autoboxing and Unboxing

                Autoboxing and unboxing are typically used for collections of primitives. Autoboxing involves the dynamic allocation of memory and initialization of an object for each primitive. Note that the overhead can often exceed the execution time of the desired operation. Unboxing involves the production of a primitive for each object.

                Computationally intensive tasks using primitives, e.g., iterating through primitives in a container, should be done using arrays of primitives in preference to collections of wrapper objects.

                3.6.1. Autoboxing

                Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes. In this example, the prizefighter's weight of 147 is automatically converted to its corresponding wrapper class because collections store references, not primitive values.

                	// Create hash map of weight groups
                HashMap<String, Integer> weightGroups
                = new HashMap<String, Integer> ( );
                weightGroups.put("welterweight", 147);
                weightGroups.put("middleweight", 160);
                weightGroups.put("cruiserweight", 200);


                The following example shows an acceptable but not recommended use of Autoboxing:

                	// Establish weight allowance
                Integer weightAllowanceW = 5; //improper


                For these examples, wrapper class variables end with a capital W. This is not the convention.


                As there is no reason to force autoboxing, the above statement should be written as follows:

                	Integer weightAllowanceW = new Integer (5);


                3.6.2. Unboxing

                Unboxing is the automatic conversion of the wrapper classes to their corresponding primitive types. In this example, a reference type is retrieved from the hash map. It is automatically unboxed so that it can fit into the primitive type.

                	// Get the stored weight limit
                int weightLimitP = weightGroups.get(middleweight);


                For these examples, primitive variables end with a capital P. This is not the convention.


                The following example shows an acceptable but not recommended use of unboxing:

                	// Establish the weight allowance
                weightLimitP = weightLimitP + weightAllowanceW;


                This expression can also be equivalently written with the intValue( ) method, as shown here:

                	weightLimitP = weightLimitP + weightAllowanceW.intValue(
                );









                Escape from the Dungeon











                 < Day Day Up > 











                Escape from the Dungeon



                As we have mentioned, game systems are like open source "operating systems." Player-designers interact with data and write their own software, creating programs (rulesets) that manipulate or transform the organization of game system data. New games result, which can then be manipulated and transformed again. The operating system of the Icehouse Set is nothing more than the collection of 60 colored pyramids and the mathematical and physical rules structuring their space of possibility. A simple and elegant OS kernel, the Icehouse Set is nonetheless capable of a huge variety of expression.


                Perhaps not surprisingly, game systems find a natural home when we turn our attention to digital games. Starcraft, Pac-Man, EverQuest, Pong: each is a game, and each is a piece of software (literally). Digital games have always had a naturally affinity with an open source software model: the very first computer game, Spacewar!, was an open source game whose code underwent modification and distribution by players from the moment of its conception. Without open source thinking, Spacewar! might never have come into being. Digital games have always been ready candidates for an open source paradigm; it is within digital games, in fact, that the model of player-as-producer has found the most significant and transformative voices to date.


                One such voice is Elemental, a player-produced mod for the fantasy role-playing game Dungeon Siege, created by Gas Powered Games. Elemental is what is known as a "total conversion" mod: rather than simply inventing a new character skin, game level, or in-game object, the mod transforms Dungeon Siege into a completely different game. The result is a game that utilizes elements of Dungeon Siege's core game system within a radically altered context of expression. As Zendo to Icehouse, Elemental recasts Dungeon Siege within an altogether different space of play.


                The possibility for a mod such as Elemental only exists because of software developers that work from an open source model. Gas Powered Games recognized open source as an ideology that could effectively enhance and extend the life of their games. As a result, they released Dungeon Siege with a robust suite of editing and game development tools that players could use to modify the game in an infinite variety of ways. The proprietary Siege Editor, for example, gives players the freedom to rework nearly every aspect of the game, making Dungeon Siege not only a game, but also a role-playing platform for those who want to create their own characters, spells, and dun-geons—or even entire worlds. Players can publish these user-created files to the web, making them available for anyone to download and explore or play as a multiplayer game.[7]


                Team Elemental, the development team of (mostly amateur) programmers, artists, game designers, level designers, GUI and concept artists living and working in various countries across the globe, took these tools and began to mod. Impressed by the robust Dungeon Siege engine, they quickly realized that the limits of what could be done with the game lay only in their imaginations. They decided to depart from the Tolkienesque world of the original game to invent something with a radically different setting, storyline, and game play mechanic. The resulting experience of play would be very different than what the original game offered. Affectionately described as "biblepunk" (players are former slaves seeking retribution in the ancient city of Jericho), it remains to be seen if the Dungeon Siege community will embrace the new world by modding it in turn.






                Dungeon Seige editor

                One of the unique features of Elemental's creation was the collaborative environment nurtured by Dungeon Siege's developers. Although many open source games make their code available for modification by players, and often provide toolsets to help them do so, Gas Powered Games assumed an active role in assisting Team Elemental. Programmers coding the mod worked in direct contact with engineers from the original game, who offered hints and advice for working with the intricacies of the code. Clearly, Gas Powered Games embraced the player-as-producer paradigm in constructing and nurturing an active player community. As Chris Taylor, president and game designer of Gas Powered Games, noted in an interview, the drive to support the mod community came out of their experience with a previous game:



                Most of this drive comes from our experience working on Total Annihilation. We learned that a great community could propel a game to new levels of fun and turn it into more than anyone thought it could be. We found this idea to be very exciting, and in many ways, feel it is the way of the future. Imagine, people all over the world working together on teams to create fantastic new adventures, stories, characters.The possibilities are endless, and this is just the beginning![8]



                Taylor's investment in supporting player community and creativity has clearly paid off. Elemental is just one example how far players will go when a game's design invests in them a desire to extend and reinvent play by playing with the rules of the game. The culturally transformative play that emerges from player production feeds back into the open source model out of which the game developed, growing the possibilities of the community's space of play exponentially.


                Both Icehouse and Dungeon Siege exhibit three essential qualities of open source games: the games are open systems that can be modified by a community of players, rather than a single developer; the games are freely shared among players and developers; and the source code is made available. In the case of Dungeon Siege, not just the source code, but also development tools were made available to players, increasing the ease and depth of possible modifications.







                [7]<http://dungeonseige.com>





                [8]Tricia "Kazi Wren" Harris,"Mod World: Part 12." Gamespy.com. August 22, 2002 <www.gamespy.com/modworld/august02/modworld12/ >.



















                 < Day Day Up > 



                5.1 Strategy



                [ Team LiB ]










                5.1 Strategy


                The Strategy pattern is an example of delegation, the general object-oriented idiom that was mentioned in the last chapter. Before starting, we should mention that in discussing implementations of patterns such as the Strategy pattern it will be helpful to use obvious, illustrative class names like Context
                and Strategy, as in Figure 5.2. But of course when you use the software patterns in your own code you can call your classes anything you like.



                Figure 5.2. The Strategy pattern





                The problem addressed by the Strategy pattern is when we have a range of objects, all members of the same class called, let's say, Context, and we want to be able to change the behavior of the behave method of a Context
                object without having to change the class the object belongs to.


                The solution is to create a Strategy
                class that holds a behavealgorithm method. The Context
                class will have a Strategy *_pstrategy member, and a Context::behave(){_pstrategy->behavealgorithm(this)}.


                The reason you need to pass the 'this' to the behavealgorithm is so that the method can use the Context
                mutators and accessors to view and to alter the data of the Context
                object. Possibly behavealgorithm may call some other Context
                methods as well.


                If you find it useful, you can use the same name for the Context::behave() and Strategy::behavealgorithm methods.


                The Strategy pattern plays a role similar to the role of function pointers in old-style C programming. One of the motivations for using the Strategy pattern is to avoid having a combinatorial explosion of classes. Rather than having to derive off new subclasses for new kinds of behavior, we use the Strategy pattern to let classes 'plug-in' whatever behavior they need.


                In the Pop Framework, the cCritter::feellistener()
                method calls a cListener::lis
                ten(cCritter *pcritter)
                method. In particular, we give each cCritter
                a cListener *_plis
                tener. The cCritter::feellistener()
                calls _plistener->listen(this).


                The cListener::listen(cCritter *pcritter)
                method takes input from the mouse or keyboard and affects the owner critter in different ways.


                The fact that a Strategy
                object can be dynamically changed means that when you are running the Pop program, for instance, you can use the Player menu to select different kinds of controllers for the player. When you are doing this, you change the player's listening strategy.






                  [ Team LiB ]



                  Useful Server Variables








                  Useful Server Variables


                  There's a special superglobal array, $_SERVER, that contains a great deal of information about what's going on with your web application. For example, $_SERVER['PHP_SELF'] holds the name of the current script, $_SERVER['REQUEST_METHOD'] holds the request method that was used ("GET", "POST", and so on), $_SERVER['HTTP_USER_AGENT'] holds the type of the user's browser, and so on. You can see a sampling of the most useful server variables available in $_SERVER in Table 6-1.


                  Table 6-1. The General Server Variables

                  Server variable

                  Description

                  'AUTH_TYPE'

                  When running under Apache as module doing HTTP authentication, this variable holds the authentication type.

                  'DOCUMENT_ROOT'

                  The document root directory under which the script is executing, as defined in the server's configuration file.

                  'GATEWAY_INTERFACE'

                  The revision of the CGI specification that the server is using, such as 'CGI/1.1'.

                  'PATH_TRANSLATED'

                  File systembased path to the current script.

                  'PHP_AUTH_PW'

                  When running under Apache as module doing HTTP authentication, this variable holds the password provided by the user.

                  'PHP_AUTH_USER'

                  When running under Apache as module doing HTTP authentication, this variable holds the username provided by the user.

                  'PHP_SELF'

                  The filename of the currently executing script, relative to the document root.

                  'QUERY_STRING'

                  The query string, if any, with which the page was accessed.

                  'REMOTE_ADDR'

                  The IP address from which the user is viewing the current page.

                  'REMOTE_HOST'

                  The Host name from which the user is viewing the current page.

                  'REMOTE_PORT'

                  The port being used on the user's machine to communicate with the web server.

                  'REQUEST_METHOD'

                  Specifies which request method was used to access the page; such as 'GET', 'HEAD', 'POST', 'PUT'.

                  'REQUEST_URI'

                  The URI that was given in order to access this page, such as '/index.html'.

                  'SCRIPT_FILENAME'

                  The absolute pathname of the currently executing script.

                  'SCRIPT_NAME'

                  Contains the current script's path. This is useful for pages that need to point to themselves.

                  'SERVER_ADMIN'

                  The value given to the SERVER_ADMIN directive (for Apache) in the web server configuration file.

                  'SERVER_NAME'

                  The name of the server host under which the script is executing.

                  'SERVER_PORT'

                  The port on the server machine being used by the web server for communication. By default setups, this is '80'.

                  'SERVER_PROTOCOL'

                  Name and revision of the information protocol through which the page was requested; such as 'HTTP/1.0'.

                  'SERVER_SIGNATURE'

                  String containing the server version and virtual host name, which are added to server-generated pages.

                  'SERVER_SOFTWARE'

                  The server identification string.



                  NOTE



                  The $HTTP_SERVER_VARS array contains the same information as shown in Tables 6-1 and 6-2 but is not a superglobal.


                  Table 6-2. The HTTP Server Variables

                  HTTP variable

                  Description

                  'HTTP_ACCEPT'

                  Text in the Accept: header from the current request, if there is one.

                  'HTTP_ACCEPT_CHARSET'

                  Text in the Accept-Charset: header from the current request, if there is one, such as: '*, utf-8'.

                  'HTTP_ACCEPT_ENCODING'

                  Text in the Accept-Encoding: header from the current request, if there is one, such as: 'zip'.

                  'HTTP_ACCEPT_LANGUAGE'

                  Text in the Accept-Language: header from the current request, if there is one, such as 'en' for English.

                  'HTTP_CONNECTION'

                  Text in the Connection: header from the current request, if there is one, such as: 'Keep-Alive'.

                  'HTTP_HOST'

                  Text in the Host: header from the current request, if there is one.

                  'HTTP_REFERER'

                  The address of the page (if any) that referred the user agent to the current page. The browser sets this.

                  'HTTP_USER_AGENT'

                  Text in the User-Agent: header from the current request, if there is one. This is a string denoting the browser that is accessing the page.




                  These server variables are great because they give you a little more informationsuch as the name of the script that's running in this example, phpidentifier.php:



                  <HTML>
                  <HEAD><TITLE>The Self Identifier Script</TITLE></HEAD>
                  <BODY>
                  <H1>The Self Identifier Script</H1>
                  <?php
                  echo "Welcome to ", $_SERVER["PHP_SELF"];
                  ?>
                  </BODY>
                  </HTML>


                  Here's what you see when you run this script:



                  Welcome to /phpindentifier.php