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

Professional Portal Development with Open Source Tools Java Portlet API phần 8 ppsx

46 297 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 46
Dung lượng 0,98 MB

Nội dung

13 469513 Ch09.qxd 1/16/04 11:06 AM Page 284 Portlet Integration with Web Services Throughout this book, we have discussed portal development as it relates to the user interface. This chapter, however, focuses on the information transmission between your portal and your enterprise information stores with Web services. Portlets are a great way to provide a front-end-user interface to back-end data sources, and Web services provide a standard interface for the transmission of that information. Traditional Web services are data-oriented and presentation-neutral, and must be aggregated and styled in order to provide presentation. On the other hand, the OASIS WSRP (Web Services for Remote Portlets) specification introduces a presentation-oriented Web service interface façade for remote portlets that mixes application and presentation logic. WSRP defines how a port- let can be invoked remotely by another portal, and is a mechanism for simpler integration between portals and Web services. In this chapter, we describe the basic concepts of Web services and portal integration; build exam- ples of portlets interacting with traditional Web services; and provide an overview of the WSRP specification. All source code for the examples in this chapter, including the code referred to but not listed, is on the book’s Web site, at www.wrox.com. Basic Concepts Unless you have been in a cave for the last few years, you know that Web services are software appli- cations that can be discovered, described, and accessed based on XML and standard Web protocols over computer networks. The messaging foundation of Web services is SOAP (Simple Object Access Protocol). WSDL (Web Service Definition Language) is used for describing the interfaces of SOAP Web services, and UDDI (Universal Description, Discovery, and Integration) registries are used for discovering and finding such Web services. Because there is community acceptance and standards agreement on these specifications to promote interoperability between applications, any portal 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 285 developer should understand these basic concepts and know how to integrate with Web services. As this book is geared toward portal developers and is not a Web services tutorial, we do not explain every detail of the SOAP, WSDL, and UDDI specifications. We do, however, briefly discuss the SOAP message syntax, show you SOAP messaging and WSDL examples, discuss Web services as they relate to portlet develop- ment, and show you examples of portlets integrating with sample Web services using Apache Axis. If you are entirely new to Web services, we recommend that you spend some time looking at the Web Services Primer at http://webservices.xml.com/, as well as the Sun Java documentation at http://java. sun.com/webservices. The examples in this chapter use the Apache Axis framework to deploy our Web services, and in one case, use Axis-generated objects to communicate with them. For more information about Apache Axis, please visit their Web site (http://xml.apache.org/axis). One of the first things that you should understand is the format of the SOAP message syntax. An entire Web service message is encapsulated by a SOAP envelope, optional header information (mostly security- related information) is contained in the SOAP header, and the body of your Web service messages is con- tained in the SOAP body. The following code shows a sample SOAP request asking for the last stock trade price for a ticker sym- bol, taken from the first example in the SOAP 1.1 specification. [SOAP] The SOAP body contains the main request, and the SOAP envelope wraps the entire message. On lines 4–7 is the SOAP body of the message, which wraps the application-specific information (the call to GetLastTradePrice in the SOAP body). A Web service receives this information, processes the request in the SOAP body, and returns a SOAP response. In this example, there was no SOAP header, but if there were such a header, it would precede the SOAP body as another child of the SOAP envelope: 01: <SOAP-ENV:Envelope 02: xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/” 03: SOAP-ENV:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”> 04: <SOAP-ENV:Body> 05: <m:GetLastTradePrice xmlns:m=”Some-URI”> 06: <symbol>DIS</symbol> 07: </m:GetLastTradePrice> 08: </SOAP-ENV:Body> 09: </SOAP-ENV:Envelope> The WSDL for this Web service would list the SOAP message format for the requests and responses. The SOAP response in the following code, much like the request in the preceding code, contains the “guts” of the application’s message in the SOAP body. No presentation is included in the SOAP response; there- fore, any portal calling this Web service will have to add presentation to the results: <SOAP-ENV:Envelope xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/” SOAP-ENV:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”/> <SOAP-ENV:Body> <m:GetLastTradePriceResponse xmlns:m=”Some-URI”> <Price>34.5</Price> </m:GetLastTradePriceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> 286 Chapter 10 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 286 If you developed a portlet to call the GetLastTradePrice Web service with a request shown in the first nine lines of code, you would have to do a little bit of extra work to add presentation to the response shown in the second group. The service itself provides no graphics, and simply sends an XML message response. Because SOAP messages are presentation-neutral, they must be styled (usually with stylesheets) to produce content. A simple scenario of the interaction between a portal and a Web service is shown in Figure 10.1. This figure shows three important concepts: ❑ The use of a Web service as a façade to the data source ❑ The interaction between a portlet in a portal and a Web service ❑ Taking the contents of the SOAP response and applying presentation Figure 10.1 In Figure 10.1, a portlet sends a SOAP request to a Web service, which in turn makes a request to an information store. When the Web service is able to respond, it sends a SOAP response back to the portal. At this point, however, another process must take place in order to style the response content. Often, the presentation process could use XSL (the eXtensible Stylesheet Language) with a stylesheet in order to style the content for display in the portlet. Of course, this example could become more complicated if the portlet speaks to several Web services and needs to aggregate content before styling the information. As a result, your design needs to accommodate such complexity. As we discussed in the last chapter, such a design can be accomplished by using the Model-View-Controller (MVC) paradigm. Portlet development with Web services using MVC can take a very similar approach, with the Web services representing the model. In a portlet architecture with Web services, your Portlet developed with the Java Portlet API may act as the controller, and delegate presentation to other components, including JSPs. In the next section, you will see several examples of building portlets that integrate with traditional, data-centric Web ser- vices, following the MVC paradigm. Integrating with Traditional Web Services Portlets may be used as controllers to connect to your Web services, and dispatch presentation to other components, such as JSPs. Figure 10.2 shows a typical example of how you can develop your portlets to the MVC paradigm. In Figure 10.2, the portlet gets initialization information from the portlet descriptor as well as the names of the JSPs for VIEW mode, EDIT mode, and HELP mode. The portlet, using the doView(), doEdit(), and doHelp() methods inherited from the class javax.portlet.GenericPortlet, is able to dispatch to the proper presentation defined by the mappings in the portlet deployment descriptor. Depending on your Web services, your portlet itself may initiate the call to the Web service, or your JSPs may invoke a class or a bean to call the Web service. Web Service Portal Portlet Information Store 2. Request/Response 1. SOAP Request 4. Presentation 3. Soap Response 287 Portlet Integration with Web Services 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 287 Figure 10.2 Figure 10.2 provides a good overview of how your portlets can be designed, whereby your portlets act as controllers to JSPs based on the VIEW/EDIT/HELP modes of your portlet. This takes advantage of the MVC paradigm, and can help you when you develop your portlets — regardless of whether you will be interacting with Web services. Sun Microsystems developed some excellent sample portlets that follow this model, and these JSPs are used in several open-source portlet containers, which are available at http://developers.sun.com/ prodtech/portalserver/reference/techart/jsr168/index.html. In their design, they have created a JSPPortlet class that extends the javax.portlet.GenericPortlet class that performs the redirec- tion to the appropriate VIEW, EDIT, and HELP pages. This class is extended by their sample portlets, and a UML class diagram for their design is shown in Figure 10.3. Figure 10.3 shows the design of Sun’s example JSP portlets, where JSPPortlet is a superclass for dis- patching the presentation of the portlet, based on the contentPage, editPage, and helpPage parame- ters in a portlet descriptor. The demonstration portlets that extend JSPPortlet are WeatherPortlet, NotepadPortlet, and BookmarkPortlet, all of which are good examples that you can use to under- stand portlet development. A partial listing of the code for JSPPortlet is shown in the following code. Because this code was developed by Sun Microsystems, we are listing the copyright: /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: dispatches to the “HELP” JSP dispatches to the “EDIT” JSP dispatches to the “VIEW” JSP Portlet Deployment Descriptor (portlet.xml) Defines Mappings Between Modes and JSPs SOAP Request/Response Web Service Portlet View.jsp Help.jsp Edit.jsp DoHelp DoView DoEdit 288 Chapter 10 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 288 * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided “AS IS,” without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of * any nuclear facility. */ package com.sun.portal.portlet.samples.jspportlet; import javax.portlet.*; import java.io.*; import java.util.*; public class JSPPortlet extends GenericPortlet { private PortletContext pContext; public void init(PortletConfig config) throws PortletException { super.init(config); pContext = config.getPortletContext(); } public void doView(RenderRequest request,RenderResponse response) throws PortletException,IOException { String contentPage = getContentJSP(request); response.setContentType(request.getResponseContentType()); if (contentPage != null && contentPage.length() != 0) { try { System.out.println(“Dispatching to content page: “ + contentPage); PortletRequestDispatcher dispatcher = pContext.getRequestDispatcher(contentPage); dispatcher.include(request, response); } catch (IOException e) { throw new PortletException(“JSPPortlet.doView exception”, e); } } } 289 Portlet Integration with Web Services 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 289 Figure 10.3 Generic Portlet is Default Implementation for Portlet Interface javax. portlet (Main Portlet API Package) com.sun.portal.portlet.sample s Main Portlet Interface Interface that Provides Portlet with a Configuration These are sample portlets that SUN Microsystems created # doEdit() # doHelp() # doView() + init() # processAction() # getTitle() # doDispatch() Generic Portlet JSPPortlet is a "h elper" portlet from which JSP-specific portlets can inherit. It gets the "VIEW", "EDIT", and "CONTENT" jsps from the associated parameters in the portlet descriptor, helps resolve JSP pathnames from that descriptor , and dispa tches information to the JSPs themselves + init() + destroy() + processAction() + render() Portlet + getInitParameter() + getInitParameterNames() + getPortletContext() + getPortletName() + getResourceBundle() PortletConfig WeatherPortlet NotepadPortlet BookmarkPortlet + doEdit() + doHelp() + doView() + init() + processAction() # getContentJSP() # getEditJSP() # getHelpJSP() - getJSPPath() # getLocalizedJSP() com.sun.portal.portlet.samples.jspportlet.JSPPortlet 290 Chapter 10 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 290 In the preceding listing, you saw that the doView() method uses the PortletRequestDispatcher object to dispatch the listing to the content page, specified in the portlet descriptor. In the same way, the doEdit() and doHelp() methods that were deleted from this listing delegate the view to the appro- priate JSPs. In the following code, additional methods from JSPPortlet continue such delegation. The getContentJSP() page returns the localized JSP for the VIEW mode of the portlet. In the same manner, getEditJSP(), and getHelpJSP() in the file return the localized JSPs for the EDIT and HELP JSP pages, respectively. In the following code, the class resolves the localized path in the getLocalizedJSP() and getJSPPath() methods: protected String getContentJSP(RenderRequest request) throws PortletException { PortletPreferences pref = request.getPreferences(); String contentPage = pref.getValue(“contentPage”,””); return getLocalizedJSP(request.getLocale(), contentPage); } /* NOTE: getEditJSP() and getHelpJSP() were removed from this listing for space-saving purposes. They are very similar to getContentJSP(). */ protected String getLocalizedJSP(Locale locale, String jspPath) { String realJspPath = jspPath; if (locale != null) { int separator = jspPath.lastIndexOf(“/”); String jspBaseDir = jspPath.substring(0, separator); String jspFileName = jspPath.substring(separator+1); PortletContext pContext = getPortletContext(); String searchPath = getJSPPath(jspBaseDir, locale.toString(), jspFileName); if (pContext.getResourceAsStream(searchPath) != null) { realJspPath = searchPath; } else { if (!locale.getCountry().equals(“”)) { searchPath = getJSPPath(jspBaseDir, locale.getLanguage(), jspFileName); if (pContext.getResourceAsStream(searchPath) != null) { realJspPath = searchPath; } } } } return realJspPath; } private String getJSPPath(String jspBaseDir, String localeStr, String jspFileName) { StringBuffer sb = new StringBuffer(); sb.append(jspBaseDir) .append(“_”) .append(localeStr) .append(“/”) .append(jspFileName); return sb.toString(); } } 291 Portlet Integration with Web Services 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 291 The preceding code samples show some of the major methods of JSPPortlet.java. Its doView(), doEdit(), and doHelp() methods get the appropriate JSPs from the portlet’s descriptor. They dispatch to the appropriate pages, calling the getContentJSP(), getEditJSP(), and doHelpJSP() methods, depending on the mode of the portlet. As you can see, the Java class can be a very helpful class for JSP redirection. We will extend this class in our example portlets in this chapter. The next section provides an example of two different designs for integrating with Web services using such an architecture, explaining the pros and cons of each. In one example, the portlet delegates com- plete responsibility to its corresponding JSP pages for its respective modes; in the other, the Web service is called from the portlet and sends data information to the corresponding JSPs. A Simple Example For this example, we will develop a very simple portlet connecting to a simple Web service. Because we often see a lot of “stock quote” examples for Web services, which get boring after a while, we’ve created an example that is a little different. For this example, we will build a simple Llama portlet that shows inven- tory for a llama farm, based on results returned from a Llama Inventory Web service. The results from the Web service are based on a common XML Llama schema. This portlet acts only in VIEW and HELP modes. We will show two approaches for invoking the Llama Web service: one showing and using SOAP and WSDL messaging, and one using objects generated with Web service tools. The first approach will show the “gory details” of SOAP and WSDL because it is sometimes helpful to see this in order to understand how SOAP and WSDL work. (It is also very helpful when you are debugging!) In the first approach, we’ll provide an example of delegating responsibility to a JSP that calls the Web service and styles the SOAP message. In the second approach, we’ll show you an example of using Axis-generated objects for communicating with your Web service. Both approaches focus on the Llama Inventory Web service. First Approach: SOAP and WSDL Messaging Our first approach has been created more for instructional (tutorial) use than for production. This will help you understand SOAP “on the wire,” and some of the nitty-gritty details of WSDL. At the end of this section, you should have an appreciation for what “automatic” Web service integration tools do for you. The WSDL that our Web service uses for this example is based on a “common llama schema” shared by many llama farms. The WSDL for this example, for “Bonnie’s Llama Farm”, is shown in the follow- ing code sections. As you can see by looking at the LlamaResults element in the WSDL, inventories consist of a list of llamas, including each llama’s international identifier, its age, a description, a name, the type of llama it is (usually a stud, weanling, cria, or female), and a URL for its image on the Web. The types section is shown here, which indicates the schema that we are using: <?xml version=”1.0” encoding=”UTF-8” ?> <definitions targetNamespace=”http://trumantruck.com/bonniellama” xmlns=”http://schemas.xmlsoap.org/wsdl/” xmlns:apachesoap=”http://xml.apache.org/xml-soap” xmlns:impl=”http://trumantruck.com/bonniellama” xmlns:soapenc=”http://schemas.xmlsoap.org/soap/encoding/” xmlns:soap=”http://schemas.xmlsoap.org/wsdl/soap/” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”> <!— types section —> <types> 292 Chapter 10 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 292 <schema xmlns=”http://www.w3.org/2001/XMLSchema”> <simpleType name=”LlamaTypes”> <restriction base=”string”> <enumeration value=”STUD”/> <enumeration value=”INTACT WEANLING MALE”/> <enumeration value=”ADULT FEMALE”/> <enumeration value=”FEMALE CRIA”/> <enumeration value=”WEANLING FEMALE”/> <enumeration value=”WEANLING MALE (NON-INTACT)”/> </restriction> </simpleType> <element name=”LlamaResults”> <complexType> <sequence> <element name=”Llama” minOccurs=”0”> <complexType> <sequence> <element name=”identifier” type=”string”/> <element name=”age” type=”string” minOccurs=”0”/> <element name=”description” type=”string” minOccurs=”0”/> <element name=”name” type=”string”/> <element name=”type” type=”impl:LlamaTypes”/> <element name=”imgurl” type=”string” minOccurs=”0”/> </sequence> </complexType> </element> </sequence> </complexType> </element> <element name=”getLlamasInput” type=”xsd:anyType”/> </schema> </types> Next, we must define our message declarations, our port type declarations, and our bindings. These parts of the WSDL are shown in the following code: <!— message declarations —> <message name=”getLlamasRequest”> <part element=”impl:getLlamasInput” name=”part”/> </message> <message name=”getLlamasResponse”> <part element=”impl:LlamaResults” name=”getLlamasReturn”/> </message> <!— port type declarations —> <portType name=”BonniesLlamaFarmInfoService”> <operation name=”getLlamas”> <input message=”impl:getLlamasRequest”/> <output message=”impl:getLlamasResponse”/> </operation> </portType> <!— bindings —> <binding name=”BonniesLlamasSoapBinding” type=”impl:BonniesLlamaFarmInfoService”> 293 Portlet Integration with Web Services 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 293 [...]... method from JSPPortlet, because we are not sending any parameters to our HELP page, and the inherited method already does the dispatching for us: 295 Chapter 10 import javax .portlet. *; import java. io.*; import com.sun .portal. portlet. samples.jspportlet.JSPPortlet; public class LlamaPortlet extends JSPPortlet { private String m_llamaURLString; public void init(PortletConfig config) throws PortletException,... including portlet markup 302 Portlet Integration with Web Services WSRP Consumer WSRP Producer SOAP Portal Portlet WSRP Interfaces Server Portal Portlet Portlet Figure 10.5 In Figure 10.5, note that a standard Web service interface (the block that says WSRP Interfaces) enables the consumer portal to include remote portlets from the producer This is what WSRP is all about! When a portal uses a remote portlet, ... 082 : 083 : 084 : 085 : The run_commandline_test target that starts on line 86 determines which test to select for operation If the test name selected is Test1, then a text string will be echoed to the console with the value Test1 Otherwise, the target portal tests, not shown in this script, will be called: 086 : 087 : 088 : 089 : 090: 091: 092: 093: 094: 095: 096: 097: 0 98: 099: 100:... 0 68: 069: 070: 071: 072: 073: 074: 075: 076: 077: 0 78: 079: 080 : 3 18 Performance Testing, Administering, and Monitoring Your Portal 081 : 082 : ... call those WSRP services (unless you are developing a portlet container!) Because your portlet container will do most of the hard work as a consumer or producer of remote portlets, all you have to do is develop your portlets with your Java Portlet API, using standard markup required by the WSRP and Java Portlet specification For the most part, portals utilize HTML and XHTML, and WSRP lists guidelines... using a local interface Portal User’s Client SOAP WSRP Service Portlet Portal Remote Portlet Proxy Aggregation Local Portlet Interface Portlet Portlet Portlet Portlet Portlet Figure 10.6 As simple as Figure 10.6 looks, a few complexities of producer-consumer interaction can result A typical process flow, based on the Web Services for Remote Portlets Specification 1.0, is shown here [WSRP]: 1 The consumer... messages), we can certainly style the output with XSLT Because this example will not utilize EDIT mode, our portlet descriptor provides pages only for VIEW and HELP mode, as shown in the following code: Llama Portlet LlamaPortlet < /portlet- class> llama.url http://localhost :80 /axis/services/BonniesLlamas ... com.trumantruck.bonniellama.*; import javax .portlet. *; import java. io.*; import java. net.*; //import the Sun JSP portlet that we will extend import com.sun .portal. portlet. samples.jspportlet.JSPPortlet; public class LlamaPortlet2 extends JSPPortlet { private String m_llamaURLString; public void init(PortletConfig config) throws PortletException, UnavailableException 299 Chapter 10 { String llamaURLString;... mode in this portlet —> EDIT< /portlet- mode> —> HELP< /portlet- mode> Bonnie’s Llamas < /portlet- info> contentPage /llama/llamaView.jsp helpPage /llama/llamaHelp.jsp < /portlet- preferences> < /portlet> As... consumers, and portlet management ❑ WSRP Consumers — Consumers are portals or applications that communicate with presentationoriented Web services (remote portlets) They gather the markup delivered by the portlets and present the aggregation to the end-user ❑ Remote Portlets — Remote portlets are those portlets that are hosted and disseminated by a WSRP producer through a Web services interface These portlets . facility. */ package com.sun .portal. portlet. samples.jspportlet; import javax .portlet. *; import java. io.*; import java. util.*; public class JSPPortlet extends GenericPortlet { private PortletContext pContext; public. remote portlet to the producer, receives the page, and presents this content to the end-user. SOAP User’s Client Portal Portlet Portlet Portlet Portlet Portlet Portlet Remote Portlet Proxy Local Portlet Interface Aggregation Portal WSRP Service SOAP Portal WSRP. us: 295 Portlet Integration with Web Services 14 469513 Ch10.qxd 1/16/04 11:06 AM Page 295 import javax .portlet. *; import java. io.*; import com.sun .portal. portlet. samples.jspportlet.JSPPortlet; public

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