1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional Java JDK 6 Edition 2007 phần 8 docx

77 269 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

if ( (removeitem != null) && (removeitem.length > 0) ) { for (int i=0; i < removeitem.length; i++) { try { System.out.println(“removing oid, name= “ + oid + “, “ + removeitem[i]); owners = ownersSession.removeOwnersDraftPicks(oid, removeitem[i]); } catch(Exception e) { e.printStackTrace(); } } } String userSubmit = request.getParameter(“submit”); if ( (userSubmit != null && userSubmit.equals(“Add Draft Pick”)) && (!name.equals(“”)) ) { try { System.out.println(“adding oid, name= “ + oid + “, “ + name); owners = ownersSession.addOwnersDraftPicks(oid, name); } catch(Exception e) { e.printStackTrace(); out.println(e.toString()); } } List allDraftPicks = null; try { allDraftPicks = ownersSession.findAllDraftPicks(); } catch(Exception e) { e.printStackTrace(); out.println(e.toString()); } Checks are used here in the JSP to ensure that the allDraftPicks list is populated with draft pick selec- tions by the owner. If player items are discovered, they will be added to the drop-down list display com- ponent. Note that both the draft pick name and position are concatenated with a pipe ( |) delimiter so both player attributes can be parsed above by the application for visual presentation in the owners list: %> <form method=”post” action=”/baseball/editOwner.jsp”> <table border=”1”> <% if ( (allDraftPicks == null) || (allDraftPicks.size() == 0)) { %> <tr> <td colspan=”2”>No draft picks found.</td> </tr> <% } else { %> <tr> 515 Chapter 10: EJB 3 and the Java Persistence API 15_777106 ch10.qxp 11/28/06 11:47 PM Page 515 <td> <select name=”draftpicks”> <% for (int i = 0; i < allDraftPicks.size(); i++) { DraftPicks draftPicks = (DraftPicks)allDraftPicks.get(i); %> <option value=”<%=draftPicks.getName()%>|<%=draftPicks.getPosition()%>”> <%=draftPicks.getName()%> </option> <% } %> </select> </td> </tr> <% } %> <tr> <td colspan=”2” align=”center”> <input type=”submit” name=”submit” value=”Add Draft Pick”> <input type=”hidden” name=”oid” value=”<%=oid%>”> </td> </tr> </table> </form> Lastly, in this segment of the JSP component, the owners draft pick list is rendered along with check- boxes that allow selections to be removed if warranted. The owners draft pick list is obtained from the owner reference procured from the ownersSession.searchForOwners lookup query: <form method=”post” action=”/baseball/editOwner.jsp”> <table> <tr bgcolor=”#cccccc”><td colspan=”3” align=”center”>ID:<%=oid%>’s List</td></tr> <tr bgcolor=”#cccccc”> <td>Name</td> <td>Position</td> <td><input type=”submit” name=”remove” value=”Remove?”></td> <input type=”hidden” name=”oid” value=”<%=oid%>”> <input type=”hidden” name=”draftpicks” value=”<%=draftpicks%>”> </tr> <% if (owners != null) { List ownersList = owners.getDraftpicksList(); if ( (ownersList != null) && (ownersList.size() > 0) ) { for (int i=0; i < ownersList.size(); i++) { DraftPicks draftPicks = (DraftPicks)ownersList.get(i); 516 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 15_777106 ch10.qxp 11/28/06 11:47 PM Page 516 %> <tr> <td><%=draftPicks.getName()%></td> <td align=”center”><%=draftPicks.getPosition()%></td> <td align=”center”><input type=”checkbox” name=”removeitem” value=”<%=draftPicks.getName()%>”></td> </tr> <% } } }%> </table> </form> <% } else out.println(“No owner found with ID = “ + oid); %> <hr> [<a href=”/baseball/index.html”>HOME</a>] </center> </body> </html> This scenario tried to address many complex features that have been provided by the new EJB 3 persis- tence model libraries to perform transactions with enterprise-tier components from a web-tier JSP. The confluence of EJB libraries and their annotations in source code development is a daunting modeling task to undertake, but hopefully the code in this scenario will prove beneficial for readers in their devel- opment and deployment endeavors. Summary It should be noted that modifications in the EJB 3 and Java Persistence API specifications were devel- oped so users would have to craft fewer classes in their implementations because more work is now per- formed by EJB/web containers that reside in application servers. EJB artifacts have shed the need for home and object interfaces that have been required in the past, resulting in the need for only a business interface. Annotation markings are now declared in EJB components forgoing previous release require- ments that required deployment descriptor configurations which now allow the container to manage transactions. Lastly, the introduction of annotations in POJOs has allowed developers to map Java objects to relational data stores making O/R mapping much simpler for development and maintenance. Developers who have developed enterprise bean components from previous releases should recognize how the new EJB 3 and persistence model libraries have streamlined deployment descriptor require- ments with the introduction of annotations to generate artifacts, document code, and provide services for operations. These annotations now allow developers to define Web Services, map Java methods to operations and components to XML and database persistence mechanisms, as well as specify external dependencies to EJB applications in a more efficient manner than ever before. 517 Chapter 10: EJB 3 and the Java Persistence API 15_777106 ch10.qxp 11/28/06 11:47 PM Page 517 15_777106 ch10.qxp 11/28/06 11:47 PM Page 518 Communicating between Java Components and Components of Other Platforms Java is an ideal platform for server-side development. Many of the ongoing professional and open source Java development projects are for various server-side applications. Java EE (Enterprise Edition) dominates this Java server space, providing a strong open platform for many different types of server applications. One of the core principles and architectural themes in Java EE is the ability to segregate and distribute various components of the same software system to different machines. Remote communication between Java objects and components to other Java objects and components is at the heart of Java EE. Because Java EE is an open platform, it also defines how external objects and components in other applications (and other programming languages) com- municate with Java EE components. In today’s heterogeneous Internet-centric computing world, this cross-platform communication is absolutely essential. Component is an ambiguous term that can mean many different things to many differ- ent developers. In the context of this chapter, component refers to any software object or collection of objects that are network-aware, either sending information to other components or receiving it from the latter. For a high-level example, a web server could be considered a component. Web browsers and other client applications need to communicate with this component. More granular examples include Enterprise JavaBeans (EJBs; see Chapter 10 ), and Web Services. 16_777106 ch11.qxp 11/28/06 10:48 PM Page 519 In this chapter, you investigate the general high-level design of component-to-component communica- tion as well as some concrete examples for coding the actual communication. The java.net package is looked at first for its sockets support, because sockets are the basic building block for all other communi- cation technologies. Understanding protocols follows and an example partial implementation of HTTP is demonstrated. A brief discussion of Remote Method Invocation (RMI) and the Common Object Request Broker Architecture (CORBA) comes next. Concluding the chapter is information on how best to utilize the newest addition to JDK 6, Web Services. The information regarding sockets and protocols will be trivial for the advanced developer but crucial for a developer with no distributed programming experience. If you are an advanced developer familiar with sockets, protocols, and understand the basic premises of RMI and CORBA, feel free to skip ahead to the “Web Services” section — you will probably find them too basic. Web Services are now a first-class citizen in the JDK and are rapidly becoming the cross-platform component technology of choice for new software projects. Component Communication Scenarios A few examples of where component-to-component communication takes place will aid the understand- ing of where sockets, CORBA, RMI, and Web Services fit into a given application’s architecture. In each of the scenarios shown, almost any of these technologies could be used. Being equipped with more in- depth knowledge of these technologies later on in the chapter will allow software developers to weigh the pros and cons of each in their particular situation and pick the right technology for the job. News Reader: Automated Web Browsing Little software utilities can often eliminate tedious tasks such as constantly watching and monitoring par- ticular web sites. Software can be developed to automate these tasks as much as possible. Developing an application for monitoring web sites would involve communicating with the remote web server to check various news sites for new stories and information on topics of interest every ten minutes. Whenever a new story popped up, fitting your criteria, the user would be notified, eliminating the need to constantly check and refresh certain web sites. Writing client components that monitor data sources for new informa- tion is a common task in distributed computing. A Bank Application: An EJB/Java EE Client Because of Java EE’s component-based nature, existing systems can often be extended by simply adding new software components, without destroying their existing infrastructure. Suppose a bank wants to modernize the client software that its tellers use to access the banking infrastructure. The terminals the bank tellers use daily are all running Microsoft Windows 2000 and the application must run on this existing infrastructure. The bank already has a Java EE-based back-end to keep track of all banking data, and the application merely needs to interface with it. This Java EE system exposes a web front-end, which is good for personal use over the Internet by various members of the bank, but not for the heavy daily use necessary for tellers. A thick client is needed. The EJB components on the server will need to be accessed by the client. Writing client applications that access EJBs (or other Java EE components) is typi- cal in professional Java development. 520 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_777106 ch11.qxp 11/28/06 10:48 PM Page 520 A Portal: Integrating Heterogeneous Data Sources and Services Many web portals, such as Yahoo!, integrate various pieces of data such as stock tickers, sports scores, and news headlines. The software design of such a portal must be flexible enough to integrate many of these different pieces of data, oftentimes from many different locations. Many larger corporations have their own internal intranet portal. These portals need to access information from a variety of sources. Component-to-component communication is crucial to access the databases, files, and information from other software applications necessary for the functionality of the portal. Overview of Interprocess Communication and Basic Network Architecture In the development of these distributed software applications, it is often necessary for components run- ning in one process to communicate with components running in another process. For instance, a database runs in one process on a server, and the client application that reads and writes information from and to this database runs in a separate process (and possibly on a different machine). There must be some mechanism through which these two processes communicate. Often, these other processes that your Java application must communicate with are not written in Java and are not running inside a vir- tual machine. Whether or not another process is running in a Java Virtual Machine, any communication between two processes must follow some sort of protocol. Protocols are the language two disparate com- ponents use to speak to one another. Your web browser speaks the HyperText Transfer Protocol (HTTP) to web servers to retrieve web content to your local machine. Your instant messaging client speaks a cer- tain protocol back to its server and potentially to other users of an instant messaging service. Peer-to- peer file-sharing services speak protocols to allow the searching and sharing of files. (Gnutella is one popular example of a common protocol allowing many different file-sharing clients to communicate with each other.) All of the applications and protocols mentioned can communicate over a network. They can also com- municate to another process on the same machine. This is because these protocols have been abstracted from their transport. They could run locally, or over a TCP/IP network. In communicating between Java components and components of other platforms, you must always consider possible network transports. The Open Systems Interconnection (OSI) network architecture gives a high-level abstraction of some of the layers in any form of interprocess network communication. For the discussion in this chapter, you can think of an even higher-level architecture (derived from the OSI architecture) for understanding component-to-component communication. Figure 11-1 shows the derived architecture with three main layers: the application layer, the protocol layer, and the transport layer. Two disparate components communicate by sending data through each of the layers as shown. The appli- cation layer represents high-level protocols such as HTTP or FTP. The protocol layer represents lower- level transport protocols such as TCP or UDP running over IP. The transport layer represents the actual physical transport, such as Ethernet, as its corresponding mechanisms for sending and retrieving data. For distributed components to communicate, they must speak the same protocol at the application level. 521 Chapter 11: Communicating between Java Components and Other Platforms 16_777106 ch11.qxp 11/28/06 10:48 PM Page 521 Figure 11-1 This chapter focuses on the application level; the lower-level hardware transport is out of the scope of this book. For most distributed application development, the application layer is most important to soft- ware developers. In web applications, for example, HTTP is the application-level protocol that dictates many of the application’s design decisions. HTTP does not support stateful connections, and therefore the state of any user’s session must be simulated by the use of session cookies or session identification parameters. Designing any network-aware application, or in other words, any application that must communicate between separate components, Java or non-Java, locally or remote, requires the knowledge of the limitations and features of the various application-level and transport-level protocols available to facilitate such communication. Threads are a critical aspect of designing any good I/O-intensive application, especially I/O over a net- work and between two disparate processes. Sockets Sockets are the basic mechanism for interprocess communication provided by the operating system. In most development projects, they will probably not have to be used explicitly, because they are fairly low- level. However, any type of interprocess communication is built on top of sockets, and in any type of network communication, sockets are used implicitly. Therefore, it would be prudent to understand just some simple background as to how they work. This section of the chapter provides a broad overview of sockets for the purposes of better understanding RMI, CORBA, and Web Services. Transport Layer (Ethernet) Protocol Layer (TCP/IP) Application Layer (HTTP) Transport Layer (Ethernet) Protocol Layer (TCP/IP) Application Layer (HTTP) Network 522 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_777106 ch11.qxp 11/28/06 10:48 PM Page 522 A socket is essentially a defined endpoint for communication between two processes. It provides a full duplex channel to two different parties (potentially more if it is multicasting) involved in communication— there are two separate data streams, one going in and one going out. There are two types of sockets: ❑ User Datagram Protocol (UDP). Sockets using UDP provide a datagram service. They receive and send discrete packets of data. UDP is a connectionless protocol, meaning that there is no connection setup time as there is in TCP. However, UDP is unreliable —packets are not guaran- teed to be sent or received in the right order. UDP is mainly used for applications such as multi- media streaming and online gaming, where not all data is necessary, for which the UDP’s best-effort service model is well suited. ❑ Transmission Control Protocol (TCP). Sockets using TCP provide a reliable byte-stream service. TCP guarantees delivery of all packets sent and the reception of them in the correct order. TCP is a connection-oriented protocol, which allows it to provide the byte-stream service. TCP is best suited for applications that cannot allow data transmitted to be lost, such as for file transfer, web browsing, or Telnet. This section only considers using TCP sockets, because UDP is more for advanced network applications that require the development of their own low-level protocols or multimedia streaming algorithms, which are out of the scope of this book. For the purposes of this text, sockets simply allow you an input and output stream to another process, either running locally or remotely. The Java Socket API The Java Socket API is the core Java interface to network programming. As such, all of the core socket classes are found in the java.net package. Java implements the two types of sockets: TCP sockets, which communicate using the Transmission Control Protocol, and UDP sockets, which communicate via the Universal Datagram Protocol. In addition to the normal UDP socket implementation, Java also provides a UDP multicast socket implementation, which is a socket that sends data to multiple clients simultaneously. Because Java was built from the ground up as an object-oriented language, you will find that the socket library interacts heavily with the Java I/O libraries (both java.io and java.nio). If you need a refresher on some of the aspects of Java I/O and serialization, see Chapter 5. This section concentrates on TCP sockets throughout, because they are far more prevalent than UDP sockets in most client/server or distributed systems. Key Classes The following table shows the four major classes used for socket communication in Java. The Socket and DatagramSocket classes implement TCP and UDP, respectively. Both TCP and UDP use an IP address and port number as the demultiplexing key, or address, to another process. InetSocketAddress repre- sents this address. Both Socket and DatagramSocket use an InetSocketAddress to locate the machine and process that should be the recipient of any data sent. Class (From java.net) Function Socket Class used to represent a client socket endpoint for sending and receiv- ing data over TCP connections. DatagramSocket Both client and server class for sending and receiving data sent via UDP. Table continued on following page 523 Chapter 11: Communicating between Java Components and Other Platforms 16_777106 ch11.qxp 11/28/06 10:48 PM Page 523 Class (From java.net) Function ServerSocket Class used for TCP servers. Once a client connects, this class returns a Socket class to actually send and receive data. InetSocketAddress Represents an IP address (or hostname) along with a port number. For example, InetSocketAddress could represent www.example .com:8080 . Client Programming The Socket and InetSocketAddress classes are used by a client to connect to a server running in another process (whether remote or local). Once a connection is set up, all communication takes place utilizing normal Java I/O classes. There is a stream of data coming in, and a stream of data going out. To set up a connection, first create the address object that defines which server and port to connect: InetSocketAddress address = new InetSocketAddress(“www.example.com”, 80); InetSocketAddress objects can also be created with an IP address: InetSocketAddress address = new InetSocketAddress(“127.0.0.1”, 80); Once the address of the remote endpoint has been defined, a connection can be attempted. Be sure to catch java.io.IOException, because this exception will be thrown if there are any problems connect- ing (such as the network is down, the server is busy, the server cannot be located, and so on). In network programming, it is important to pay extra attention to error-handling details, because communication problems aren’t just a possibility —they are pretty much guaranteed to happen at some point. Now that you have defined an address, you can create a new Socket class to attempt a connection: Socket socket = new Socket(); socket.connect(address); If the connection succeeds, either Java I/O classes or NIO (java.nio) classes can be used to send and receive data. In these examples, you will use normal Java I/O because it is often easier to understand and provides better code readability. Once the socket is connected, both InputStream and OutputStream objects from the java.io package can be retrieved and communication can begin: InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); These objects are often wrapped around other higher-level and easier-to-use I/O classes just as they are in normal Java I/O programming. Suppose, for example, that all the communication you are going to send and receive over the socket is textual data. Java provides the BufferedReader and PrintWriter objects that can be wrapped around the input and output stream objects: PrintWriter writer = new PrintWriter(out); BufferedReader br = new BufferedReader(new InputStreamReader(in)); writer.println(“Hello, remote computer”); writer.flush(); String serverResponse = br.readLine(); 524 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_777106 ch11.qxp 11/28/06 10:48 PM Page 524 [...]... import import import import import import import import import import import import java. io.BufferedReader; java. io.File; java. io.FileOutputStream; java. io.IOException; java. io.InputStream; java. io.InputStreamReader; java. io.PrintWriter; java. net.InetSocketAddress; java. net.MalformedURLException; java. net.Socket; java. net.URL; java. util.StringTokenizer; public class HttpGetter { public static void main(String[]... full listing of the code for SocketEcho is as follows: package book; import import import import import java. io.BufferedReader; java. io.IOException; java. io.InputStreamReader; java. io.PrintWriter; java. net.ServerSocket; 527 Part II: A Broad Understanding of Java APIs, Tools, and Techniques import java. net.Socket; public class SocketEcho implements Runnable { private Socket socket; public SocketEcho(Socket... of its location and platform independence Java is most prevalent in server-side applications and middleware because of the foundation it provides for building stable and reliable software systems 5 46 Chapter 11: Communicating between Java Components and Other Platforms The Java Enterprise Edition (Java EE) platform uses RMI as one of its core technologies Java EE provides reliable messaging, rock-solid... port 80 79 TCPMon will relay any connection made to port 80 79 on the local machine to www.google.com, port 80 (the default HTTP port) Once the Add button is clicked, TCPMon will set up the relay Figure 11-5 Now that the relay is running, HttpGetter can be tested by running this: java book.HttpGetter http://localhost :80 79/ tester.html HttpGetter connects to TCPMon, which in turn, connects it to java. net... HttpGetter connects to TCPMon, which in turn, connects it to java. net Going to the “Port 80 79” tab on TCPMon yields a list of all connection attempts made to java. net in this session Figure 11 -6 shows each request and response in detail 539 Part II: A Broad Understanding of Java APIs, Tools, and Techniques Figure 11 -6 Debugging a protocol implementation is far easier with a utility such as Apache TCPMon,... case of a successful HTTP GET) The response you receive from your request in the previous example looks like this: HTTP/1.1 200 OK Date: Sun, 06 Aug 20 06 03:40:21 GMT Server: Apache Vary: Host Content-Type: text/html; charset=ISO -88 59-1 X-Cache: MISS from www .java. net Connection: close (more html follows) The first line... methods) ❑ 5 48 Operations (like Java methods) Exceptions Chapter 11: Communicating between Java Components and Other Platforms Java Class «interface» IDL Interface C# Class Figure 11-11 A CORBA interface for each distributed object allows IDL compilers to compile IDL to stub classes in an existing language For instance, the JDK provides tools that map CORBA IDL types to Java types, and generate stub... application that requires HTTP client support The JDK provides limited support for HTTP via the java. net.URL class It is good for simple HTTP operations, but sometimes more control over how HTTP is used is necessary For example, to view and set HTTP headers, an HTTP client library that exposes more HTTP details than the java. net.URL class found in the JDK would be required The HTTP Client project in... an implementation) For instance, the Java Development Kit (JDK) includes an implementation of the CORBA 2.3.1 specification That means that, out of the box, Java supports CORBA implementations up to and including the 2.3.1 specification (the latest CORBA specification at the time of this writing is 3.02) Though there has been industry criticism for the age of the JDK s support for CORBA, 2.3.1 includes... similar to Java s concept of an interface — an interface allows for multiple implementations CORBA interfaces though, can be implemented by any language that supports CORBA Figure 11-11 shows a class diagram of a CORBA being implemented both in Java and C# Three things can be declared in CORBA interfaces: ❑ ❑ Attributes (like JavaBean properties, implemented by getXXX and setXXX methods) ❑ 5 48 Operations . the Java Persistence API 15_7771 06 ch10.qxp 11/ 28/ 06 11:47 PM Page 517 15_7771 06 ch10.qxp 11/ 28/ 06 11:47 PM Page 5 18 Communicating between Java Components and Components of Other Platforms Java. (or other Java EE components) is typi- cal in professional Java development. 520 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_ 7771 06 ch11.qxp 11/ 28/ 06 10: 48 PM Page 520 A. connection if (c == ‘?’) break; out.print(c); 5 26 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_ 7771 06 ch11.qxp 11/ 28/ 06 10: 48 PM Page 5 26 out.flush(); } } catch (IOException ioe)

Ngày đăng: 12/08/2014, 23:23

TỪ KHÓA LIÊN QUAN