⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 10.txt

📁 JavaWeb服务应用开发详解的配套源码,欢迎下载
💻 TXT
📖 第 1 页 / 共 5 页
字号:
26        String encodingStyleURI = args.length == 3
27                                  ? args[0].substring(1)
28                                  : Constants.NS_URI_SOAP_ENC;
29        URL url = new URL (args[1 - offset]);
30        String symbol = args[2 - offset];
31    
32        // Build the call.
33        Call call = new Call ();
34        call.setTargetObjectURI ("urn:xmltoday-delayed-quotes");
35        call.setMethodName ("getQuote");
36        call.setEncodingStyleURI(encodingStyleURI);
37        Vector params = new Vector ();
38        params.addElement (new Parameter("symbol", String.class, symbol, null));
39        call.setParams (params);
40    
41        // make the call: note that the action URI is empty because the 
42        // XML-SOAP rpc router does not need this. This may change in the
43        // future.
44        Response resp = call.invoke (/* router URL */ url, /* actionURI */ "" );
45    
46        // Check the response.
47        if (resp.generatedFault ()) {
48          Fault fault = resp.getFault ();
49          System.out.println ("Ouch, the call failed: ");
50          System.out.println ("  Fault Code   = " + fault.getFaultCode ());  
51          System.out.println ("  Fault String = " + fault.getFaultString ());
52        } else {
53          Parameter result = resp.getReturnValue ();
54          System.out.println (result.getValue ());
55        }
56      }
57    }
例程10-7
001    //org.apache.soap.server.SMTP2HTTPBridge.Java
002    package org.apache.soap.server;
003    
004    import Java.io.*;
005    import Java.net.*;
006    import Java.util.*;
007    
008    import com.ibm.network.mail.base.*;
009    import com.ibm.network.mail.smtp.event.*;
010    import org.apache.soap.util.net.*;
011    import org.apache.soap.util.*;
012    import org.apache.soap.rpc.SOAPContext;
013    import org.apache.soap.Constants;
014    import org.apache.soap.transport.*;
015    import org.apache.soap.transport.smtp.*;
016    import Javax.mail.MessagingException;
017    
018    /**
019     * This class can be used as a bridge to relay SOAP messages received via
020     * email to an HTTP SOAP listener. This is basically a polling POP3 client
021     * that keeps looking for new messages to work on. When it gets one,
022     * it forwards it to a SOAP HTTP listener and forwards the response via
023     * SMTP to the original requestor (to either the ReplyTo: or From: address).
024     *
025     * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
026     */
027    public class SMTP2HTTPBridge implements Runnable {
028      Object waitObject = new Object ();
029      long pollDelayMillis;
030      com.ibm.network.mail.pop3.protocol.CoreProtocolBean pop3 =
031        new com.ibm.network.mail.pop3.protocol.CoreProtocolBean ();
032      com.ibm.network.mail.smtp.protocol.CoreProtocolBean smtp =
033        new com.ibm.network.mail.smtp.protocol.CoreProtocolBean ();
034      URL httpURL;
035    
036      /**
037       * Constructor: creates a bridge. Call run() to start polling using
038       * the current thread. (If you want to use a separate thread then
039       * do new Thread (new SMT2HTTPBridge (...)).start ();
040       *
041       * @param pollDelayMillis number of milli-seconds to sleep b'ween polls
042       * @param popServer hostname of POP3 server
043       * @param popLoginName login ID
044       * @param password password for login
045       * @param smtpServer hostname of SMTP server
046       */
047      public SMTP2HTTPBridge (/* POP3 params */
048                              long pollDelayMillis,
049                              String popServer, String popLoginName,
050                              String password,
051                              /* HTTP params */
052                              URL httpURL,
053                              /* SMTP params */
054                              String smtpServer) {
055        /* set up the pop3 side */
056        this.pollDelayMillis = pollDelayMillis;
057        pop3.setPOP3ServerHost (popServer);
058        pop3.setUserOptions(/* popLoginName */ popLoginName,
059          /* password */ password,
060          /* leaveMessagesOnServer */ false,
061          /* rememberPassword */ false);
062        pop3.addMessageListener (
063          new com.ibm.network.mail.pop3.event.MessageListener () {
064            public void messageReceived (
065                com.ibm.network.mail.pop3.event.MessageEvent me) {
066              receiveMessage (me.getMessage ());
067            }
068          }
069        );
070        pop3.addStatusListener (new POP3StatusListener ());
071    
072        /* set up the http side */
073        this.httpURL = httpURL;
074    
075        /* set up the smtp side */
076        smtp.setSmtpServerHost (smtpServer);
077        smtp.addStatusListener (new StatusListener () {
078          public void operationComplete (StatusEvent e) {
079            System.err.println ("DONE: " + e.getStatusString ());
080            synchronized (waitObject) {
081              waitObject.notify ();
082            }
083          }
084    
085          public void processStatus (StatusEvent e) {
086            System.err.println ("Status update: " + e.getStatusString ());
087          }
088        });
089      }
090    
091      /**
092       * Poll for messages forever.
093       */
094      public void run () {
095        while (true) {
096          if (pop3.isReady ()) {
097            System.err.println ("SMTP2HTTPBridge: Polling for messages ..");
098            pop3.receiveMessage ();
099          }
100          try {
101            Thread.sleep (pollDelayMillis);
102          } catch (Exception e) {
103            e.printStackTrace ();
104          }
105        }
106      }
107    
108      /**
109       * This is called by the POP3 message listener after receiving a 
110       * message from the pop server.
111       * 
112       * @param msg the message that was received
113       */
114      void receiveMessage (MimeMessage msg) {
115        /* extract the stuff from the SMTP message received */
116       String subject = msg.getHeader (SMTPConstants.SMTP_HEADER_SUBJECT);
117        String actionURI = msg.getHeader (Constants.HEADER_SOAP_ACTION);
118        String toAddr = msg.getHeader (SMTPConstants.SMTP_HEADER_TO);
119       String fromAddr = msg.getHeader (SMTPConstants.SMTP_HEADER_FROM);
120        MimeBodyPart mbp = (MimeBodyPart) msg.getContent ();
121        byte[] ba = (byte[]) mbp.getContent ();
122    
123        /* forward the content to the HTTP listener as an HTTP POST */
124        Hashtable headers = new Hashtable ();
125        headers.put (Constants.HEADER_SOAP_ACTION, actionURI);
126        TransportMessage response;
127        // This is the reponse SOAPContext. Sending it as a reply not supported yet.
128        SOAPContext ctx;
129        try
130        {
131            // Note: no support for multipart MIME request yet here...
132            TransportMessage tmsg = new TransportMessage(new String (ba),
133                                                      new SOAPContext(),
134                                                         headers);
135            tmsg.save();
136    
137            response = HTTPUtils.post (httpURL, tmsg,
138                                       30000, null, 0);
139            ctx = response.getSOAPContext();
140        } catch (Exception e) {
141            e.printStackTrace();
142    	return;
143        }
144        System.err.println ("HTTP RESPONSE IS: ");
145        String payload = null;
146        try {
147          // read the stream
148            payload = IOUtils.getStringFromReader (response.getEnvelopeReader());
149        } catch (Exception e) {
150          e.printStackTrace ();
151        }
152        System.err.println ("'" + payload + "'");
153    
154        /* forward the response via SMTP to the original sender */
155        MimeBodyPart mbpResponse = new MimeBodyPart ();
156        mbpResponse.setContent (new String (payload), response.getContentType());
157        mbpResponse.setEncoding (MimePart.SEVENBIT);
158        mbpResponse.setDisposition (MimePart.INLINE);
159    
160        MimeMessage msgResponse = new MimeMessage();
161        msgResponse.setContent (mbpResponse, "");
162        msgResponse.addHeader (SMTPConstants.SMTP_HEADER_SUBJECT,
163                               "Re: " + subject);
164        msgResponse.addHeader (Constants.HEADER_SOAP_ACTION, actionURI);
165        msgResponse.addHeader (SMTPConstants.SMTP_HEADER_FROM, 
166                            SMTPUtils.getAddressFromAddressHeader (toAddr));
167        String sendTo = SMTPUtils.getAddressFromAddressHeader (fromAddr);
168        msgResponse.addRecipients (MimeMessage.TO, 
169                                   new InternetAddress[] { 
170                                     new InternetAddress (sendTo)
171                                   });
172        smtp.sendMessage (msgResponse);
173      }
174    
175      public static void main (String[] args) throws Exception {
176        if (args.length != 6) {
177          System.err.println ("Usage: Java " + SMTP2HTTPBridge.class.getName () +
178                              " polldelay \\");
179          System.err.println ("\t\t pop3host pop3login pop3passwd httpurl " +
180                              "smtphostname");
181          System.err.println ("  where:");
182          System.err.println ("    polldelay    number of millisec to " +
183                              "sleep between polls");
184          System.err.println ("    pop3host     hostname of the POP3 server");
185          System.err.println ("    pop3login    login ID of POP3 account");
186          System.err.println ("    pop3passwd   POP3 account password");
187          System.err.println ("    routerURL    http URL of SOAP router to " +
188                              "bridge to");
189          System.err.println ("    smtphostname SMTP server host name");
190          System.exit (1);
191        }
192        SMTP2HTTPBridge sb = new SMTP2HTTPBridge (/* POP3 params */
193                                                  Integer.parseInt (args[0]),
194                                                  args[1],
195                                                  args[2],
196                                                  args[3],
197                                                  /* HTTP params */
198                                                  new URL (args[4]),
199                                                  /* SMTP params */
200                                                  args[5]);
201        new Thread (sb).start ();
202      }
203    }
例程10-8
01     //samples.stockquote.GetQuoteSMTP.Java
02     package samples.stockquote;
03     
04     import Java.io.*;
05     import Java.net.*;
06     import Java.util.*;
07     import org.apache.soap.*;
08     import org.apache.soap.transport.*;
09     import org.apache.soap.transport.smtp.*;
10     import org.apache.soap.rpc.*;
11     
12     /**
13      * This shows how to get invoke the stockquote service using
14      * SOAP over SMTP. I gave up on command line args for this and
15      * decided to prompt for the info .. just too much stuff to 
16      * set up. 
17      *
18      * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
19      */
20     public class GetQuoteSMTP {
21       public static void main (String[] args) throws Exception {
22         if (args.length != 7
23             && (args.length != 8 || !args[0].startsWith ("-"))) {
24           System.err.println ("Usage: Java " + GetQuoteSMTP.class.getName () +
25                               " [-encodingStyleURI] routerURL smtpserver" +
26     			  " replyaddr popserver poplogin poppasswd symbol");
27           System.err.println ("  where:");
28           System.err.println ("    routerURL   mailto: URL of SOAP router");
29           System.err.println ("    smtpserver  SMTP server host name");
30           System.err.println ("    replyaddr   email addr that response should " +
31     			  "be sent to (my address)");
32           System.err.println ("    popserver   POP server host name");
33           System.err.println ("    poplogin    login ID to get response email");
34           System.err.println ("    poppasswd   password for above");
35           System.err.println ("    symbol      stock symbol");
36           System.exit (1);
37         }
38     
39         // Process the arguments.
40         int offset = 8 - args.length;
41         String encodingStyleURI = args.length == 8
42                                   ? args[0].substring(1)
43                                   : Constants.NS_URI_SOAP_ENC;
44         URL url = new URL (args[1 - offset]);
45         String smtpserver = args[2 - offset];
46         String replyaddr = args[3 - offset];
47         String popserver = args[4 - offset];
48         String poplogin = args[5 - offset];
49         String poppasswd = args[6 - offset];
50         String symbol = args[7 - offset];
51     
52         // Build the call.
53        SOAPTransport ss = new SOAPSMTPConnection (/* from address */ replyaddr, 
54     					       /* subject */ "SOAP Request",
55     					       /* smtpServer */ smtpserver,
56     					       /* popPollDelay */ 20000,
57     					       /* popServer */ popserver,
58     					       /* popLogin */ poplogin,
59     					       /* popPassword */ poppasswd);
60         Call call = new Call ();
61         call.setSOAPTransport (ss);
62         call.setTargetObjectURI ("urn:xmltoday-delayed-quotes");
63         call.setMethodName ("getQuote");
64         call.setEncodingStyleURI(encodingStyleURI);
65         Vector params = new Vector ();
66         params.addElement (new Parameter ("symbol", String.class, symbol, null));
67         call.setParams (params);
68     
69         // make the call: note that the action URI is empty because the 
70         // XML-SOAP rpc router does not need this. This may change in the
71         // future.
72         Response resp = call.invoke (/* router URL */ url, /* actionURI */ "" );
73     
74         // Check the response.
75         if (resp.generatedFault ()) {
76           Fault fault = resp.getFault ();
77           System.out.println ("Ouch, the call failed: ");
78           System.out.println ("  Fault Code   = " + fault.getFaultCode ());  
79           System.out.println ("  Fault String = " + fault.getFaultString ());
80         } else {
81           Parameter result = resp.getReturnValue ();
82           System.out.println (result.getValue ());
83         }
84       }
85     }
例程10-9
01    //samples.messaging.POProcessor.Java

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -