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

Professional Java JDK 6 Edition 2007 phần 9 ppsx

77 301 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

Thông tin cơ bản

Định dạng
Số trang 77
Dung lượng 1,21 MB

Nội dung

cancelMI.setEnabled(false); } } }); // initially disable the cancel menu item, since there is no active request cancelMI.setEnabled(false); menu.add(new MenuItem(“-”)); menu.add(new MenuItem(“Configure Zipcode”)).addActionListener( new ActionListener() { (retrieve user input for zipcode field) }); menu.add(new MenuItem(“Exit”)).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.exit(0); } }); this.icon = new TrayIcon(wImage, “Weather Watcher”, menu); sysTray.add(this.icon); } The actionPerformed() method of the WeatherWatcher class is where weather Web Services requests are started. Because WeatherGetter.getWeatherAsync() is called, the request is non-blocking and starts up in a background thread. When the request terminates (either successfully or fails with an excep- tion), the anonymous AsyncHandler<GetWeatherResponse>’s handleResponse() method is called: // called when user clicks “Get Weather” context menu item // initiates asynchronous web service call public void actionPerformed(ActionEvent evt) { this.getWeatherMI.setEnabled(false); cancelMI.setEnabled(true); future = weatherGetter.getWeatherAsync(zipcode, new AsyncHandler<GetWeatherResponse>() { // note that this reponse method is on another thread, // so we have to get back on the GUI thread to do any // updates to our GUI components public void handleResponse(Response<GetWeatherResponse> resp) { try { final Weather w; if (!resp.isCancelled() && resp.isDone()) { // if there was an exception during the web service processing, // it will be thrown here GetWeatherResponse gwr = resp.get(); w = gwr.getWeather(); } else { 592 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_777106 ch11.qxp 11/28/06 10:48 PM Page 592 // user cancelled the request, re-enable menus and return try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { cancelMI.setEnabled(false); getWeatherMI.setEnabled(true); } }); } catch (Exception ex) { ex.printStackTrace(); } return; } All execution in handleResponse() occurs on a different thread. This is extremely important — it means whenever you want to update your GUI components you have to get back on the GUI thread. Remember that the javax.swing.SwingUtilites class facilitates doing just that. Use its invokeAndWait() method to execute code back on the GUI thread. Even if you did not utilize the JAX-WS asynchronous invocation model, you would still have to do this whenever you execute GUI code on a thread other than the GUI thread. If you did not use the asynchronous model for the client, whenever a request was active, the system tray icon would be unresponsive, and there would be no way to see what the previous forecast was, or cancel the current request — basically the application would be held hostage and user interaction denied until the web request completed. Using the asynchronous invocation model avoids this problem. The following code either displays the result of the successful Web Service call to the user, or displays an error message if the Web Service request terminated with an exception: try { // display the weather forecast received to the user, // and set the tooltip so the user can view it later SwingUtilities.invokeAndWait(new Runnable() { public void run() { cancelMI.setEnabled(false); getWeatherMI.setEnabled(true); StringBuffer msg = new StringBuffer(); msg.append(“Zipcode: “ + zipcode + “\n\n”); msg.append(w.getGeneralDescription() + “\n”); msg.append(w.getBarometer() + “ : “ + w.getBarometerDescription() + “\n”); msg.append(w.getLowTemperature() + “ / “ + w.getHighTemperature()); icon.displayMessage(“Weather Report”, msg.toString(), TrayIcon.MessageType.INFO); icon.setToolTip(msg.toString()); 593 Chapter 11: Communicating between Java Components and Other Platforms 16_777106 ch11.qxp 11/28/06 10:48 PM Page 593 } }); } catch (Exception e) { e.printStackTrace(); } } catch (final Exception ex) { // there was an error during our web service request, display // the error to the user try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { cancelMI.setEnabled(false); getWeatherMI.setEnabled(true); icon.displayMessage(“Error Getting Weather”, ex .getMessage(), TrayIcon.MessageType.ERROR); } }); } catch (Exception ie) { ie.printStackTrace(); } } } }); } (main method) } The result of a successful Web Service request is shown in Figure 11-18. Web Services provide a powerful mechanism to expose data normally retrieved by a standard browser-based web application to a variety of clients, and the Web Service import tools provided with JAX-WS make it quick and easy to incorporate Web Services into your clients. Figure 11-18 Using TCPMon to Simulate a Slow Connection During the development of distributed systems, many developers will often run both the client and the server on their machine. This has the effect of making many network communications seem much faster 594 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_777106 ch11.qxp 11/28/06 10:48 PM Page 594 than they actually will be in production, and never really gives them worst-case scenarios, such as server machines being unavailable (with potentially long waits for connection timeouts), or network congestion and server load, effectively slowing down communications. Just in the Weather Watcher example from the previous section, you ran both the client weather system tray app and the Tomcat server on the same machine. The side effect here was that the weather request happened so fast you were unable to test the Cancel functionality — which allows the user to cancel an outbound request. Apache TCPMon provides a method for simulating slow connections, which allows you to test your application more thoroughly. In the weather watcher case, it allows you to test the Cancel functionality because the request to the server will take enough time that you’d have an opportunity to test canceling before it successfully returned. It’s also a good idea to do this type of testing because it will really highlight parts of your client app that maybe did not have a Web Service request threaded (and as such will freeze your app for a while), or show you different user interaction patterns that could only happen while a request was outbound. Configuring TCPMon for simulating a slow connection is straightforward. As you can see in Figure 11-19, you can set the number of bytes to send before a connection pause. The settings shown in the figure make your Web Service request take about six to eight seconds, providing ample time to test the Cancel request functionality of your application. Figure 11-19 Note how in Figure 11-19 you start a listener on port 8080 and forward all requests to port 8081. Doing so means that if Tomcat is running on port 8081 instead of its default port of 8080, TCPMon will be entirely transparent to your client app — your weather application still connects to http://local host:8080/weather/weather . To configure Tomcat to run on port 8081, modify the TOMCAT_HOME/ conf/server.xml file as shown here: <! Define a non-SSL HTTP/1.1 Connector on port 8080 > <Connector port=”8081” maxHttpHeaderSize=”8192” maxThreads=”150” minSpareThreads=”25” maxSpareThreads=”75” 595 Chapter 11: Communicating between Java Components and Other Platforms 16_777106 ch11.qxp 11/28/06 10:48 PM Page 595 enableLookups=”false” redirectPort=”8443” acceptCount=”100” connectionTimeout=”20000” disableUploadTimeout=”true” /> Other Client-Side Possibilities Web Services give client applications language and platform freedom. They can be thick or thin clients, and can use the information in your services in a variety of ways. Information-centric applications could integrate a variety of Web Services. Applications could query for map information, for traffic informa- tion, and weather forecasts, and overlay it all on one view. Customized applications could be written to display information from your various online accounts, such as car insurance information, bills you need to pay, your various bank account and retirement plans, and tie the information all together in an automated way. Once more and more public web sites begin to offer Web Services, these possibilities will continue to balloon. If you are deploying a service for a particular customer, if you Web Service enable it, they can find uses for it and integrate with other services you do not even know about. Web Services enable the current generation of dynamic web sites to share their data with potentially any application, not simply web browsers and users manually retrieving their data. Web Services Interoperability Technologies Project (WSIT) The Web Services Interoperability Technologies Project (WSIT) is a Sun-sponsored project on java.net to implement many extensions for JAX-WS. Many standards from OASIS are in the process of being implemented and tested for interoperability with the Microsoft .NET platform. WS-Security and the many other WS-* standards are being implemented, focusing on security, messaging, metadata, and quality of service. The WSIT project is a large undertaking and one of its goals is transparency to the end user. It will integrate with the JAX-WS model for client Web Service connectivity, and wsimport will automatically generate classes that will handle WS-Security, reliable messaging, and so on. To the client Web Services programmer, the goal is transparency. Deploying Web Services is where you will have to be not only aware of these technologies, but pick the ones appropriate for your server, or for different service points in your SOA. The WS-* set of standards will eventually make Web Services into a reliable platform for mission-critical applications. It will then have all of the benefits of CORBA, but be more platform independent, and have its simpler XML-based protocol for communications. To follow the WSIT project (also called project Tango), see the following URL: https://wsit.dev.java.net/ The set of standards from OASIS can be found here: http://www.oasis-open.org/committees/tc_cat.php?cat=ws These technologies are still maturing, and at the time of this writing, project Tango (which has only released its first milestone release), only interoperates with Microsoft technology preview of its exten- sions to its Web Service stack. Now that JAX-WS is a core part of the Java platform, it should not be too much longer for these technologies to mature. In the meantime though, by beginning to move your existing Web Services to JAX-WS (and creating new ones using JAX-WS), you will be in a good position to adopt these technologies when they mature. Interoperability should always be the number one goal when developing and deploying Web Services — because the whole point is cross-platform communication. 596 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_777106 ch11.qxp 11/28/06 10:48 PM Page 596 Summary In this chapter, you have learned some possible ways to enable Java components in your application to communicate with external components in other applications or systems that could have been written in a variety of languages. Sockets provide the building blocks for all other technologies discussed in this chapter. With TCP/IP, they provide a reliable byte stream over a network that any language with a socket API can use. This is the lowest level of interprocess communication. Sockets are, however, not in themselves a guarantee of communication between two different components; a common protocol must also be spoken. In this chapter you implemented a small portion of the HTTP specification to gain an understanding of the immense undertaking implementing a protocol can be. RMI, CORBA, and Web Services are all built on top of sockets and TCP/IP. RMI and CORBA implement complex protocols allowing them to provide such features as reliability, sessions, and transactions, and event callbacks. They are cornerstone technologies for many existing enterprise systems. Java EE makes extensive use of RMI, because RMI combined with JNDI allows for the objects of a system to be transparently spread across multiple machines without any changes in the application’s code. RMI and CORBA have become intertwined to some degree since support for CORBA’s IIOP protocol was added to RMI. Now RMI and CORBA have basic interoperability, and this makes it easier for developers to integrate legacy CORBA systems into their modern Java EE equivalents. None of the technologies used in this chapter is inherently better than any other. The right tool is needed for the right job. Sockets provide a low-level API that allows for the optimization and creation of new protocols. Some projects may require this — the remote control of external hardware, such as robotic devices, can usually be done best starting with sockets, and then building a more developer-friendly API layered on top. RMI and CORBA provide great foundations for distributed systems, and an understand- ing of them is necessary to utilize the full power of Java EE. The network latency implications of remote method calls must also be considered in any distributed system. Web Services complement existing web portals. They will be the simple mechanism by which information on the World Wide Web is shared for use by machines, not just by human eyes. Distributed applications and systems will probably make use of more than one component-to-component technology. As the integration of systems and information becomes easier with more platform-agnostic APIs and technologies, a whole new breed of information- centric applications can arise. Web Services are the future of distributed computing, and enable the evolution of the current World Wide Web of unstructured information to one of structured information. Web Services are not as advanced tech- nologically as RMI or CORBA, but there is power in their simplicity. Web Services require minimal devel- opment effort to implement and, because all of their underlying protocols are human readable, are easy to debug. With the OASIS WS-* standards, Web Services are on the path to support transactions, reliable messaging, and stronger security models. Once projects like WSIT and Microsoft’s Indigo mature, these next-generation Web Service goals will be a reality. 597 Chapter 11: Communicating between Java Components and Other Platforms 16_777106 ch11.qxp 11/28/06 10:48 PM Page 597 16_777106 ch11.qxp 11/28/06 10:48 PM Page 598 Service Oriented Integration The purpose of this chapter is to introduce you to a number of techniques and APIs for performing systems integration. Building a new system from scratch is quite an undertaking, but it is not the norm today — most companies have an extensive legacy IT investment. Their systems were devel- oped over time to meet a specific need. Whether the need was customer service, order fulfillment, or finance, there was something that drove the tremendous cost and heartache associated with IT development. Eventually the systems that represent the IT infrastructure of a corporation grow to the point where sharing data and collapsing stovepipes not only starts to make sense; it’s the only option. This chapter differs from a number of the other chapters in this book because it is focused on spe- cific solutions for software integration. Throughout this book you have learned a number of APIs, tools, and techniques for building software. This chapter, on the other hand, examines some spe- cialized issues related to integrating and managing distributed applications. Service Oriented Architecture One of the biggest design challenges is making systems that will be stable as they adapt to change over time. Service Oriented Architectures (SOA) are shown to be more stable because they reuse core business functions. Figure 12-1 shows a graphic depiction of a service oriented architecture. In an SOA the IT investment a company has made is leveraged by creating Service Layers around their existing applications. These services provide a standard interface to application functions that span the enterprise. A number of enabling technologies facilitate this design. The next section dis- cusses some of these technologies and where they are used in building an SOA. 17_777106 ch12.qxp 11/28/06 10:48 PM Page 599 Figure 12-1 Enabling Technology Three APIs stand out as important tools for building a service oriented architecture: JAVA Technology Relevance Web Services and Web Services are the public face of a service oriented architecture. XML Technology They define the information contract between two systems. Java Management JMX provides the service infrastructure to deploy and manage Extension (JMX) applications across a network. Java Messaging JMS provides location-independent processing of information via Service (JMS) message endpoints. Web Services are covered in Chapter 11, so they will not be discussed here. Instead, this chapter focuses on the service fulfillment side of SOAs by looking at enabling technologies for integration, as well as Integration Patterns for designing distributed systems. To understand the basis for this type of approach you first look at some underlying technologies of JMX. JMX is the Java standard for managing remote resources. Following that, you examine JMS for loosely integrating systems via Message-Oriented Middleware (MOM). Java Management Extensions Java Management Extension (JMX) is a technology for managing and monitoring applications systems and network devices. This technology allows you to deploy specialized Java classes called MBeans to a software agent and interact with them at runtime. HR Service Layer Finance Enterprise Application Service Layer Shipping Marketing Customer Service Inventory Service Layer Service Layer Service Layer Service Layer 600 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 17_777106 ch12.qxp 11/28/06 10:48 PM Page 600 Why Is JMX Important? As of JDK 1.5, JMX is a standard part of the Java Platform. It is also the foundation for many of the J2EE application servers including JBoss, Websphere, and Weblogic. By understanding JMX technology, it will be easier for you to work with these products as well as develop your own extensions with this technology. The JMX Architecture JMX is composed of a three-layer architecture. Each layer has its own responsibility in creating manage- able resources. The layers are Instrumentation, Agent, and Remote Management. Figure 12-2 shows the high-level architecture. Figure 12-2 The following table describes the role of each layer within the architecture. Layer Description Instrumentation Defines the resources, called MBeans, to be managed in the JMX architec- ture. This can be anything from applications, services, to network devices. Agent The infrastructure that allows for management, deployment, event notifica- tion, and monitoring. All communication with the Instrumented resources happens through the Agent layer. The most significant component is the MBeanServer. Remote Defines the external communication with the agent by specifying protocol Management adaptors and connectors. An adaptor allows a client application to communi- cate with an MBeanServer. An MBeanServer must deploy at least one adap- tor. There are numerous adaptors for different protocols. HTTP, RMI, and SMTP are a few basic adaptors for communicating with an MBeanServer. Now that you understand the architecture at a high level, you can create a simple example to utilize a few of the capabilities of the technology. MBean Instrumentation Layer Resources Agent Layer Registration Notification MonitoringMBeanServer Connector Remote Management Layer Management Application Adaptor 601 Chapter 12: Service Oriented Integration 17_777106 ch12.qxp 11/28/06 10:48 PM Page 601 [...]... destination: 61 4 Chapter 12: Service Oriented Integration package wrox.ch12.jms; import import import import import import import import import import import javax.jms.Connection; javax.jms.ConnectionFactory; javax.jms.Destination; javax.jms.JMSException; javax.jms.Message; javax.jms.MessageConsumer; javax.jms.MessageListener; javax.jms.MessageProducer; javax.jms.Session; javax.naming.InitialContext; javax.naming.NamingException;... involved in sending a message The two main packages are javax.jms.* and javax.naming.*: import import import import import import import import import javax.jms.Connection; javax.jms.ConnectionFactory; javax.jms.Destination; javax.jms.JMSException; javax.jms.MessageProducer; javax.jms.Session; javax.jms.TextMessage; javax.naming.InitialContext; javax.naming.NamingException; public class MessageClient... JMXServiceURL(“service:jmx:rmi:///jndi/rmi://localhost :99 99/ server”); JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); 60 6 Chapter 12: Service Oriented Integration System.out.println(“starting rmi connector server”); server.start(); } } To run the agent, first start the RMI Registry on port 99 99: C:\>rmiregistry 99 99 & Then start the agent The agent will bind to the... them via the MBeanServer: package wrox.ch12.jmx; import java. util.Iterator; import java. util.Set; import import import import import import import javax.management.MBeanServerConnection; javax.management.ObjectName; javax.management.Query; javax.management.QueryExp; javax.management.remote.JMXConnector; javax.management.remote.JMXConnectorFactory; javax.management.remote.JMXServiceURL; public class RemoteClient... specified: javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1 099 and discovery failed with error: javax.naming.CommunicationException: Receive timed out [Root exception is java. net.SocketTimeoutException: Receive timed out] [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1 099 [Root exception is javax.naming.ServiceUnavailableException:... public RemoteClient() throws Exception { JMXServiceURL url = new JMXServiceURL( “service:jmx:rmi:///jndi/rmi://localhost :99 99/ server”); JMXConnector connector = JMXConnectorFactory.connect(url); connection = connector.getMBeanServerConnection(); } 60 7 Part II: A Broad Understanding of Java APIs, Tools, and Techniques With the connection interface you can manipulate the managed resources The deploy method... the RemoteAgent uses the javax.management and the javax.management.remote packages The remote package defines the standard for creating a connector server so the agent can receive external process requests: package wrox.ch12.jmx; import import import import import javax.management.MBeanServer; javax.management.MBeanServerFactory; javax.management.remote.JMXConnectorServer; javax.management.remote.JMXConnectorServerFactory;... all the manageable Java objects deployed to the JVM Select the Operations subtab and click the calcGreetings button You should see Figure 12-5 Figure 12-5 This is because you prevented the service from running until you explicitly started it So click the Start button, and then click calcGreetings again You should see Figure 12 -6 Figure 12 -6 605 Part II: A Broad Understanding of Java APIs, Tools, and... application stubs required to communicate with the MBeanServer: c:\ >java wrox.ch12.jmx.RemoteAgent With the agent started you will be able to connect to it via the JConsole application as you did in the previous example This time select Remote connection and specify the following as the connection string: service:jmx:rmi:///jndi/rmi://localhost :99 99/ server The application should behave in the same way even... information This is done by putting a jndi.properties file in your class path Your file will look like this for JBoss: java. naming.factory.initial=org.jnp.interfaces.NamingContextFactory java. naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java. naming.provider.url=localhost:1 099 The resources org.jnp.interfaces.NamingContextFactory and org.jboss.naming:org.jnp interfaces must be in your application’s . 11/28/ 06 10:48 PM Page 60 6 System.out.println(“starting rmi connector server”); server.start(); } } To run the agent, first start the RMI Registry on port 99 99: C:>rmiregistry 99 99 &. be a reality. 597 Chapter 11: Communicating between Java Components and Other Platforms 16_ 7771 06 ch11.qxp 11/28/ 06 10:48 PM Page 597 16_ 7771 06 ch11.qxp 11/28/ 06 10:48 PM Page 598 Service Oriented. cross-platform communication. 5 96 Part II: A Broad Understanding of Java APIs, Tools, and Techniques 16_ 7771 06 ch11.qxp 11/28/ 06 10:48 PM Page 5 96 Summary In this chapter, you have learned some possible ways to enable Java

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

TỪ KHÓA LIÊN QUAN