1   package org.mortbay.cxf.demo;
2   //========================================================================
3   //Copyright 2007 Mort Bay Consulting Pty. Ltd.
4   //------------------------------------------------------------------------
5   //Licensed under the Apache License, Version 2.0 (the "License");
6   //you may not use this file except in compliance with the License.
7   //You may obtain a copy of the License at 
8   //http://www.apache.org/licenses/LICENSE-2.0
9   //Unless required by applicable law or agreed to in writing, software
10  //distributed under the License is distributed on an "AS IS" BASIS,
11  //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  //See the License for the specific language governing permissions and
13  //limitations under the License.
14  //========================================================================
15  
16  
17  import javax.servlet.ServletException;
18  import javax.servlet.http.HttpServlet;
19  import javax.servlet.http.HttpServletRequest;
20  import javax.servlet.http.HttpServletResponse;
21  import javax.xml.ws.BindingProvider;
22  
23  import java.io.IOException;
24  import java.io.PrintWriter;
25  import java.util.*;
26  import java.net.URL;
27  
28  import ebay.apis.eblbasecomponents.FindItemsRequestType;
29  import ebay.apis.eblbasecomponents.Shopping;
30  import ebay.apis.eblbasecomponents.ShoppingInterface;
31  import ebay.apis.eblbasecomponents.SimpleItemType;
32  
33  public class AggregateAsyncCXFServlet extends HttpServlet
34  {
35      public static final String CLIENT_ATTR="org.mortbay.cxf.client";
36      public static final String ITEMS_ATTR="org.mortbay.cxf.items";
37      public static final String DURATION_ATTR="org.mortbay.cxf.duration";
38      public static final String ITEMS_PARAM="items";
39  
40      ShoppingInterface _shoppingPort;
41  
42      public void init() throws ServletException
43      {
44          super.init();
45  
46          try
47          {
48              _shoppingPort = new Shopping(new URL("http://developer.ebay.com/webservices/551/ShoppingService.wsdl")).getShopping();
49              BindingProvider bp = (BindingProvider) _shoppingPort;
50  
51              // retrieve the URL stub from the WSDL
52              String ebayURL = (String) bp.getRequestContext().
53                      get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
54  
55              // add eBay-required parameters to the URL
56              String endpointURL = ebayURL + "?callname=FindItems&siteid=0" +
57                      "&appid=JesseMcC-1aff-4c3c-b0be-e8379d036f56" +
58                      "&version=551&requestencoding=SOAP";
59  
60              // replace the endpoint address with the new value
61              bp.getRequestContext().
62                      put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
63              
64          }
65          catch (Exception e)
66          {
67              System.out.println("Exception: " + e.getMessage());
68              throw new ServletException(e);
69          }
70      }
71      
72      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
73      {
74          doPost(req,resp);
75      }
76           
77      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
78      {
79          long start = System.currentTimeMillis();
80          if (req.isInitial())
81          {
82              // first time we have seen this request, so lets start handling it
83  
84              // look for key words in query string
85              Object itemsObj = req.getParameter( ITEMS_PARAM );
86              if ( itemsObj == null )
87              {
88                  resp.setContentType("text/html");
89                  PrintWriter out = resp.getWriter();
90  
91                  out.println("<HTML><BODY>pass in url with ?items=a,b,c,d<br/>for more dramatic results run multiple times with 10 or more items</BODY></HTML>");
92                  out.close();
93                  return;
94              }
95                  
96  
97              ArrayList<String> items = new ArrayList<String>();
98              StringTokenizer strtok = new StringTokenizer( (String)itemsObj, ",");
99              while ( strtok.hasMoreTokens() )
100             {
101                 items.add( strtok.nextToken() );
102             }
103 
104 
105             try
106             {
107                 System.out.println("suspending after making initial request");
108                 req.suspend();
109 
110                 // Make the webservice requests
111                 EbayFindItemAsync greets = new EbayFindItemAsync(_shoppingPort,req);
112                 synchronized (greets)
113                 {
114                     // add as many different searchs here, each will be a seperate async call and ebayAggregate will not be 'done'
115                     // until all Future's are returned.
116                     for (String keyword : items)
117                     {
118                         greets.search( keyword );
119                     }
120                 }
121 
122                 req.setAttribute( CLIENT_ATTR, greets );
123                 req.setAttribute( ITEMS_ATTR, items );
124                 req.setAttribute( DURATION_ATTR, new Long(System.currentTimeMillis()-start));
125             }
126             catch(Exception e)
127             {
128                 // there was a problem sending the requests, so lets resume now
129                 req.resume();
130             }
131             
132         }
133         else
134         {
135             // This is a resumed request - 
136             // so either we have all the results or we timed out
137             System.out.println("resumed request "+req.isResumed());
138 
139             // Look for an existing client and protect from context restarts
140             EbayFindItemAsync ebayAggregate =(EbayFindItemAsync)req.getAttribute(CLIENT_ATTR);
141             ArrayList<String> items = (ArrayList<String>)req.getAttribute(ITEMS_ATTR);
142             long duration=(Long)(req.getAttribute(DURATION_ATTR));
143 
144             List<EbayFindItemAsyncHandler> handlers = ebayAggregate.getPayload();
145 
146             resp.setContentType( "text/html" );
147             PrintWriter out = resp.getWriter();
148             out.println( "<HTML><BODY>");
149             
150             int i=0;
151             for (EbayFindItemAsyncHandler handler : handlers)
152             {
153                 
154                 if (handler.getResponse()==null)
155                 {
156                     out.println(items.get(i) +": MISSING RESPONSE!");
157                 }
158                 else
159                 {
160                     out.print( "<b>" );
161                     out.print( items.get(i) );
162                     out.println( "</b>: " );
163                     String coma=null;
164                     for (SimpleItemType sit : handler.getResponse().getItem())
165                     {
166                         if (coma==null)
167                             coma=", ";
168                         else
169                             out.print(coma);
170                         out.print("<a href=\"");
171                         out.print( sit.getViewItemURLForNaturalSearch());
172                         out.print("\">");
173                         out.print(sit.getTitle());
174                         out.print("</a>");
175                     }
176                 }
177                 i++;
178                 out.println( "<br/>");
179             }
180 
181             long now=System.currentTimeMillis();
182             out.print( "Total Time: ");
183             out.print( now-ebayAggregate.getStartTime() );
184             out.println( "ms<br/>");
185             out.print( "Thread held: ");
186             long duration2=now-start;
187             out.print( duration+duration2 );
188             out.println( "ms ("+duration+" initial + "+duration2+" resume )");
189 
190             
191             out.println("</BODY></HTML>" );
192             out.close();
193         }
194 
195     }
196 }