?? 10.txt
字號:
例程10-1
// org.apache.soap.server.ServiceManagerClient.Java
package org.apache.soap.server;
import Java.net.URL;
import Java.io.*;
import Java.util.*;
import Javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.encoding.SOAPMappingRegistry;
import org.apache.soap.transport.http.SOAPHTTPConnection;
import org.apache.soap.rpc.*;
/**
* This is a client to talk to an Apache SOAP ServiceManager to manage services
* deployed on the server.
*
* @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
*/
public class ServiceManagerClient {
URL routerURL;
Vector params = new Vector ();
Call call = new Call ();
String userName;
String password;
public ServiceManagerClient (URL routerURL) {
Serializer bs = new org.apache.soap.encoding.soapenc.BeanSerializer ();
this.routerURL = routerURL;
SOAPMappingRegistry smr = call.getSOAPMappingRegistry ();
// register serializer/deserializer for DeploymentDescriptor.class
// and TypeMapping.class
smr.mapTypes (Constants.NS_URI_SOAP_ENC,
new QName (Constants.NS_URI_XML_SOAP,
"DeploymentDescriptor"),
DeploymentDescriptor.class, bs, (Deserializer) bs);
bs = new TypeMappingSerializer ();
smr.mapTypes (Constants.NS_URI_SOAP_ENC,
new QName (Constants.NS_URI_XML_SOAP, "TypeMapping"),
TypeMapping.class, bs, (Deserializer) bs);
}
public void setUserName (String userName) {
this.userName = userName;
}
public void setPassword (String password) {
this.password = password;
}
//invoke the remote rpc method
private Response invokeMethod (String methodName, Parameter param)
throws SOAPException {
call.setTargetObjectURI (ServerConstants.SERVICE_MANAGER_SERVICE_NAME);
call.setMethodName (methodName);
call.setEncodingStyleURI (Constants.NS_URI_SOAP_ENC);
if (userName != null) {
SOAPHTTPConnection hc = new SOAPHTTPConnection ();
hc.setUserName (userName);
hc.setPassword (password);
call.setSOAPTransport (hc);
}
if (param != null) {
params.removeAllElements ();
params.addElement (param);
call.setParams (params);
} else {
call.setParams (null);
}
Response resp = call.invoke (routerURL, "");
if (resp.generatedFault ()) {
Fault fault = resp.getFault ();
System.out.println ("Ouch, the call failed: ");
System.out.println (" Fault Code = " + fault.getFaultCode ());
System.out.println (" Fault String = " + fault.getFaultString ());
}
return resp;
}
//deploy a new service descripted by the specified DD
public void deploy (DeploymentDescriptor dd) throws SOAPException {
Parameter p1 = new Parameter ("descriptor", DeploymentDescriptor.class,
dd, null);
invokeMethod ("deploy", p1);
}
//undeploy specified service
public void undeploy (String serviceName) throws SOAPException {
Parameter p1 = new Parameter ("name", String.class, serviceName, null);
invokeMethod ("undeploy", p1);
}
//list the deployed services
public String[] list () throws SOAPException {
Response resp = invokeMethod ("list", null);
if (!resp.generatedFault ()) {
Parameter result = resp.getReturnValue ();
return (String[]) result.getValue ();
} else {
return null;
}
}
//query specified service
public DeploymentDescriptor query (String serviceName) throws SOAPException {
Parameter p1 = new Parameter ("name", String.class, serviceName, null);
Response resp = invokeMethod ("query", p1);
if (!resp.generatedFault ()) {
Parameter result = resp.getReturnValue ();
return (DeploymentDescriptor) result.getValue ();
} else {
Exception {
12
13 Call call = new Call ();
14
15 // Service uses standard SOAP encoding
16 String encodingStyleURI = Constants.NS_URI_SOAP_ENC;
17 call.setEncodingStyleURI(encodingStyleURI);
18
19 // Set service locator parameters
20 call.setTargetObjectURI ("urn:xmethods-Temperature");
21 call.setMethodName ("getTemp");
22
23 // Create input parameter vector
24 Vector params = new Vector ();
25 params.addElement (new Parameter("zipcode", String.class, zipcode, null));
26 call.setParams (params);
27
28 // Invoke the service ....
29 Response resp = call.invoke (url,"");
30
31 // ... and evaluate the response
32 if (resp.generatedFault ()) {
33 throw new Exception();
34 } else {
35 // Call was successful. Extract response parameter and return result
36 Parameter result = resp.getReturnValue ();
37 Float rate=(Float) result.getValue();
38 return rate.floatValue();
39 }
40 }
41
42 // Driver to illustrate service invocation
43 public static void main(String[] args)
44 {
45 try
46 {
47 URL url=new URL("http://services.xmethods.com:80/soap/servlet/rpcrouter");
48 String zipcode= "94041";
49 float temp = getTemp(url,zipcode);
50 System.out.println(temp);
51 }
52 catch (Exception e) {e.printStackTrace();}
53 }
54 }
例程10-4
001 /**
002 * SOAPClient4XG. Read the SOAP envelope file passed as the second
003 * parameter, pass it to the SOAP endpoint passed as the first parameter, and
004 * print out the SOAP envelope passed as a response. with help from Michael
005 * Brennan 03/09/01
006 *
007 *
008 * @author Bob DuCharme
009 * @version 1.1
010 * @param SOAPUrl URL of SOAP Endpoint to send request.
011 * @param xmlFile2Send A file with an XML document of the request.
012 *
013 * 5/23/01 revision: SOAPAction added
014 */
015
016 import Java.io.*;
017 import Java.net.*;
018
019 public class SOAPClient4XG {
020 public static void main(String[] args) throws Exception {
021
022 if (args.length < 2) {
023 System.err.println("Usage: Java SOAPClient4XG " +
024 "http://soapURL soapEnvelopefile.xml" +
025 " [SOAPAction]");
026 System.err.println("SOAPAction is optional.");
027 System.exit(1);
028 }
029
030 String SOAPUrl = args[0];
031 String xmlFile2Send = args[1];
032
033 String SOAPAction = "";
034 if (args.length > 2)
035 SOAPAction = args[2];
036
037 // Create the connection where we're going to send the file.
038 URL url = new URL(SOAPUrl);
039 URLConnection connection = url.openConnection();
040 HttpURLConnection httpConn = (HttpURLConnection) connection;
041
042 // Open the input file. After we copy it to a byte array, we can see
043 // how big it is so that we can set the HTTP Cotent-Length
044 // property. (See complete e-mail below for more on this.)
045
046 FileInputStream fin = new FileInputStream(xmlFile2Send);
047
048 ByteArrayOutputStream bout = new ByteArrayOutputStream();
049
050 // Copy the SOAP file to the open connection.
051 copy(fin,bout);
052 fin.close();
053
054 byte[] b = bout.toByteArray();
055
056 // Set the appropriate HTTP parameters.
057 httpConn.setRequestProperty( "Content-Length",
058 String.valueOf( b.length ) );
059 httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
060 httpConn.setRequestProperty("SOAPAction",SOAPAction);
061 httpConn.setRequestMethod( "POST" );
062 httpConn.setDoOutput(true);
063 httpConn.setDoInput(true);
064
065 // Everything's set up; send the XML that was read in to b.
066 OutputStream out = httpConn.getOutputStream();
067 out.write( b );
068 out.close();
069
070 // Read the response and write it to standard out.
071
072 InputStreamReader isr =
073 new InputStreamReader(httpConn.getInputStream());
074 BufferedReader in = new BufferedReader(isr);
075
076 String inputLine;
077
078 while ((inputLine = in.readLine()) != null)
079 System.out.println(inputLine);
080
081 in.close();
082 }
083
084
085 // copy method from From E.R. Harold's book "Java I/O"
086 public static void copy(InputStream in, OutputStream out)
087 throws IOException {
088
089 // do not allow other threads to read from the
090 // input or write to the output while copying is
091 // taking place
092
093 synchronized (in) {
094 synchronized (out) {
095
096 byte[] buffer = new byte[256];
097 while (true) {
098 int bytesRead = in.read(buffer);
099 if (bytesRead == -1) break;
100 out.write(buffer, 0, bytesRead);
101 }
102 }
103 }
104 }
例程10-5
01 //samples.stockquote.StockQuoteService.Java
02 package samples.stockquote;
03
04 import Java.net.URL;
05 import Java.io.*;
06 import org.w3c.dom.*;
07 import org.xml.sax.*;
08 import Javax.xml.parsers.*;
09 import org.apache.soap.util.xml.*;
10
11 /**
12 * See \samples\stockquote\readme for info.
13 *
14 * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
15 */
16 public class StockQuoteService {
17 DocumentBuilder xdb = XMLParserUtils.getXMLDocBuilder();
18
19 public float getQuote (String symbol) throws Exception {
20 // get a real (delayed by 20min) stockquote from
21 // http://www.xmltoday.com/examples/stockquote/. The IP addr
22 // below came from the host that the above form posts to ..
23 URL url = new URL
("http://www.xmltoday.com/examples/stockquote/getxmlquote.vep?s="+symbol);
24 InputStream is = url.openStream ();
25 Document d = xdb.parse(is);
26 Element e = d.getDocumentElement ();
27 NodeList nl = e.getElementsByTagName ("price");
28 e = (Element) nl.item (0);
29 String quoteStr = e.getAttribute ("value");
30 try {
31 return Float.valueOf (quoteStr).floatValue ();
32 } catch (NumberFormatException e1) {
33 // mebbe its an int?
34 try {
35 return Integer.valueOf (quoteStr).intValue () * 1.0F;
36 } catch (NumberFormatException e2) {
37 return -1.0F;
38 }
39 }
40 }
41 }
例程10-6
01 // samples.stockquote.GetQuote.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.rpc.*;
09
10 /**
11 * See README for info.
12 *
13 * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
14 */
15 public class GetQuote {
16 public static void main (String[] args) throws Exception {
17 if (args.length != 2
18 && (args.length != 3 || !args[0].startsWith ("-"))) {
19 System.err.println ("Usage: Java " + GetQuote.class.getName () +
20 " [-encodingStyleURI] SOAP-router-URL symbol");
21 System.exit (1);
22 }
23
24 // Process the arguments.
25 int offset = 3 - args.length;
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -