1 /*
2  * Created on May 18, 2004
3  *
4  * To change the template for this generated file go to
5  * Window>Preferences>Java>Code Generation>Code and Comments
6  */
7 package com.borneo.beans;
8 
9 import java.io.ByteArrayInputStream;
10import java.io.ByteArrayOutputStream;
11import java.io.IOException;
12import java.io.InputStream;
13import java.util.ArrayList;
14import java.util.LinkedList;
15import java.util.Locale;
16
17import javax.servlet.http.HttpServletRequest;
18import javax.servlet.http.HttpServletResponse;
19import javax.servlet.http.HttpSession;
20import javax.xml.soap.SOAPException;
21
22import org.apache.axis.AxisFault;
23import org.apache.axis.Message;
24import org.apache.axis.MessageContext;
25import org.apache.axis.client.Service;
26import org.apache.axis.message.RPCElement;
27import org.apache.axis.message.SOAPEnvelope;
28import org.apache.axis.soap.SOAPConnectionFactoryImpl;
29import org.apache.commons.logging.Log;
30import org.apache.commons.logging.LogFactory;
31import org.apache.struts.action.Action;
32import org.apache.struts.action.ActionForm;
33import org.apache.struts.action.ActionForward;
34import org.apache.struts.action.ActionMapping;
35import org.apache.struts.util.MessageResources;
36
37import com.borneo.net.soap.SAAJCallMgr;
38import com.borneo.util.POProperty;
39import com.google.soap.search.TestSearch;
40
41/**
42 * @author r
43 *
44 * Invoke the google API sending thru as the query parm the values from the b2bpo form.
45 * When the google response comes back with search hits as XML, use XSLT to transform  
46 * into a array of bytes. The byte[] is passed on to be posted to normal b2bpo
47 * publishing on pre-existing "GOOGLE" topic. The byte[] is html from xslt
48 * process and is object of "toSTring", then passed on to bean in Request Scope for
49 * the UI layer and the JSP that strut's forward mapping on "success" will handle.  
50 * The JSP renders the google response as part of the http
51 * response to browser that submitted the original request. 
52 */
53public class ProcessGoogle extends Action {
54    private Log log =
55        LogFactory.getLog("org.apache.struts.webapp.Example");
56    private Exception _failure = null;
57        
58    public ActionForward execute(ActionMapping mapping,
59             ActionForm form,
60             HttpServletRequest request,
61             HttpServletResponse response)
62    throws Exception {
63        Locale locale = getLocale(request);
64        MessageResources messages = getResources(request);
65        HttpSession session = request.getSession();
66        GoogleForm searchform = (GoogleForm) form;
67        if (searchform.getAction() == null ) searchform.setAction("Create");
68
69        // searchform used to convey Google result back to UI ( property=googleResult )
70        // google registration needs to be in web-inf/web.xml file like google samples
71        // use the Columba email interface to get OctetStrms from results of google search
72        // google search in "doTestSearch" gets html image of the "results"
73        // the cached page is what is pumped into b2bpo as new event on topicname
74        TestSearch ts = new TestSearch();
75        ts.setQueryString(searchform.getQ());
76        ts.setMaxResults(10);
77        ts.setKey(
78            request.getSession().getServletContext().getInitParameter("google_key")
79        );
80        // Run search calling Google's WS API then twiddle bits to suitable format for bean
81        byte[] storesult = ts.doTestSearch();
82        ByteArrayInputStream bis = new ByteArrayInputStream(storesult);
83        ByteArrayOutputStream bout = new ByteArrayOutputStream(storesult.length);
84
85        int c;                                         
86        while((c=bis.read()) != -1) {
87            bout.write(c);
88        };              
89        searchform.setGoogleResult(bout.toString());
90        
91        // "doTstsearch" method above returns the google results as bytes
92        // this byte[] immediately becomes part of an RPC Parm for another WS call.
93        // 2nd WS call dumps google's Response into the B2BPO Topic "google" where it's
94        // Published to ALL subscribers on the "google" topic.
95        
96        SAAJCallMgr mgr = new SAAJCallMgr();
97        mgr.setMessageContext(new MessageContext(new Service().getEngine()));
98        //      get new  SOAPenvelope that will hold all attachments
99        mgr.setRequestEnvelope(
00            new SOAPEnvelope(
01                mgr.getMessageContext().getSOAPConstants(),
02                mgr.getMessageContext().getSchemaVersion()));
03        LinkedList nlist = new LinkedList();        
04        nlist.add(
05            new ByteArrayInputStream(
06                storesult
07            )
08        );          
09        InputStream[] dharray = new InputStream[0];
10        // JAXRPC element for the WS call is formatted              
11        RPCElement myRpcEl = new RPCElement(
12                POProperty.get("wsdl.service.addr.port.name")
13                , POProperty.get("soap.rpc.methodname.postoctet")
14                , mgr.setParams( request.getParameter("topicname")
15                        , (InputStream[])new ArrayList(nlist).toArray(dharray)  )
16            );
17        // this is all standard SOAP messaging ( static call stuff using Apache
18        // AXIS in place of some of the normal SOAP APIs )
19        try {
20            myRpcEl.setEncodingStyle(
21                mgr.getMessageContext().getSOAPConstants().getEncodingURI());
22            // envelope hasA bodyElement and a ref to a Context                     
23            mgr.getRequestEnvelope().addBodyElement(myRpcEl);
24            mgr.getRequestEnvelope().setMessageType(Message.REQUEST);
25            mgr.getMessageContext().setTargetService(
26                mgr.getRequestEnvelope().getFirstBody().getNamespaceURI());
27            // get the required SOAPconnection                          
28            mgr.setConnection(
29                SOAPConnectionFactoryImpl.newInstance().createConnection());
30        } catch (UnsupportedOperationException e) {
31            // TODO Auto-generated catch block
32            e.printStackTrace();
33        } catch (AxisFault e) {
34            // TODO Auto-generated catch block
35            e.printStackTrace();
36        } catch (SOAPException e) {
37            // TODO Auto-generated catch block
38            e.printStackTrace();
39        }
40        
41        // Access B2BPO API - call "PostOctet" WebService ( WSDL at link below:
42        // http://www.b2bpo.com/axis/services/urn:EchoAttachmentsService?WSDL
43        // on the SOAPconnection with parms for "topicName" and stream of bytes 
44        // corresponding to the Google search response ( base8 binArray )
45        mgr.setReqMessage(new Message(mgr.getRequestEnvelope()));
46        mgr.getReqMessage().setMessageContext(mgr.getMessageContext());
47        Message wsresponse = (Message) mgr.call(mgr.getReqMessage());
48        try {
49            //  b2bpo WS call   response.writeTo(System.out);
50            if (wsresponse == null) throw new NullPointerException("WSDL HostAddr not found");
51            log.debug("attachment cnt : " + new Integer(wsresponse.countAttachments()).toString());
52            wsresponse.getAttachmentsImpl().writeContentToStream(System.out);
53
54        } catch (IOException e1) {
55            // TODO Auto-generated catch block
56            _failure = e1;
57            e1.printStackTrace();
58        }  finally {
59            mgr.close();
60            log.debug("SOAP Connection closed");
61        }
62        
63        // DO NOT Remove the obsolete STRUTS form bean and current subscription
64        // The UI needs the form Bean.
65        
66//      if (mapping.getAttribute() != null) {
67//              if ("request".equals(mapping.getScope()))
68//                  request.removeAttribute(mapping.getAttribute());
69//              else
70//                  request.getSession().removeAttribute(mapping.getAttribute());
71//          }
72//      session.removeAttribute(Constants.SUBSCRIPTION_KEY);
73
74        // Forward control to the specified success URI
75            if (log.isTraceEnabled()) {
76                log.trace(" Forwarding to success page");
77            }
78        return (mapping.findForward("success"));
79    }
80}
81