Debian Codegraph @

src/java/org/astrogrid/samp/xmlrpc/internal/InternalClient.java

raw
1 package org.astrogrid.samp.xmlrpc.internal;
2
3 import java.io.BufferedInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.net.HttpURLConnection;
9 import java.net.URL;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.logging.Logger;
14 import javax.xml.parsers.ParserConfigurationException;
15 import org.w3c.dom.DOMException;
16 import org.w3c.dom.Document;
17 import org.w3c.dom.Element;
18 import org.xml.sax.SAXException;
19 import org.astrogrid.samp.SampUtils;
20 import org.astrogrid.samp.xmlrpc.SampXmlRpcClient;
21
22 /**
23 * XML-RPC client implementation suitable for use with SAMP.
24 * This implementation is completely freestanding and requires no other
25 * libraries.
26 *
27 * @author Mark Taylor
28 * @since 26 Aug 2008
29 */
30 public class InternalClient implements SampXmlRpcClient {
31
32 private final URL endpoint_;
33 private final String userAgent_;
34 private static final Logger logger_ =
35 Logger.getLogger( InternalClient.class.getName() );
36
37 /**
38 * Constructor.
39 *
40 * @param endpoint endpoint
41 */
42 public InternalClient( URL endpoint ) {
43 endpoint_ = endpoint;
44 userAgent_ = "JSAMP/" + SampUtils.getSoftwareVersion();
45 }
46
47 public Object callAndWait( String method, List params )
48 throws IOException {
49 HttpURLConnection connection =
50 (HttpURLConnection) endpoint_.openConnection();
51 byte[] callBuf = serializeCall( method, params );
52 connection.setDoOutput( true );
53 connection.setDoInput( true );
54 connection.setRequestMethod( "POST" );
55 connection.setRequestProperty( "Content-Type", "text/xml" );
56 connection.setRequestProperty( "Content-Length",
57 Integer.toString( callBuf.length ) );
58 connection.setRequestProperty( "User-Agent", userAgent_ );
59 connection.connect();
60 OutputStream out = connection.getOutputStream();
61 out.write( callBuf );
62 out.flush();
63 out.close();
64 int responseCode = connection.getResponseCode();
65 if ( responseCode != HttpURLConnection.HTTP_OK ) {
66 throw new IOException( responseCode + " "
67 + connection.getResponseMessage() );
68 }
69 InputStream in = new BufferedInputStream( connection.getInputStream() );
70 Object result = deserializeResponse( in );
71 connection.disconnect();
72 return result;
73 }
74
75 // NOTE: if this method is invoked from a shutdownHook thread,
76 // the call may not complete because it is completed from a new thread.
77 public void callAndForget( String method, List params )
78 throws IOException {
79 final HttpURLConnection connection =
80 (HttpURLConnection) endpoint_.openConnection();
81 byte[] callBuf = serializeCall( method, params );
82 connection.setDoOutput( true );
83 connection.setDoInput( true );
84 connection.setRequestMethod( "POST" );
85 connection.setRequestProperty( "Content-Type", "text/xml" );
86 connection.setRequestProperty( "Content-Length",
87 Integer.toString( callBuf.length ) );
88 connection.setRequestProperty( "User-Agent", userAgent_ );
89 connection.connect();
90 OutputStream out = connection.getOutputStream();
91 out.write( callBuf );
92 out.flush();
93 out.close();
94
95 // It would be nice to just not read the input stream at all.
96 // However, connection.setDoInput(false) and doing no reads causes
97 // trouble - probably the call doesn't complete at the other end or
98 // something. So read it to the end asynchronously.
99 new Thread() {
100 public void run() {
101 try {
102 InputStream in =
103 new BufferedInputStream( connection.getInputStream() );
104 while ( in.read() >= 0 ) {}
105 int responseCode = connection.getResponseCode();
106 if ( responseCode != HttpURLConnection.HTTP_OK ) {
107 logger_.warning( responseCode + " " +
108 connection.getResponseMessage() );
109 }
110 }
111 catch ( IOException e ) {
112 }
113 finally {
114 connection.disconnect();
115 }
116 }
117 }.start();
118 }
119
120 /**
121 * Generates the XML <code>methodCall</code> document corresponding
122 * to an XML-RPC method call.
123 *
124 * @param method methodName string
125 * @param paramList list of XML-RPC parameters
126 * @return XML document as byte array
127 */
128 protected byte[] serializeCall( String method, List paramList )
129 throws IOException {
130 ByteArrayOutputStream bos = new ByteArrayOutputStream();
131 XmlWriter xout = new XmlWriter( bos, 2 );
132 xout.start( "methodCall" );
133 xout.inline( "methodName", method );
134 if ( ! paramList.isEmpty() ) {
135 xout.start( "params" );
136 for ( Iterator it = paramList.iterator(); it.hasNext(); ) {
137 xout.start( "param" );
138 xout.sampValue( it.next() );
139 xout.end( "param" );
140 }
141 xout.end( "params" );
142 }
143 xout.end( "methodCall" );
144 xout.close();
145 return bos.toByteArray();
146 }
147
148 /**
149 * Deserializes an XML-RPC <code>methodResponse</code> document to a
150 * Java object.
151 *
152 * @param in input stream containing response document
153 */
154 protected Object deserializeResponse( InputStream in )
155 throws IOException {
156 try {
157 Document doc = XmlUtils.createDocumentBuilder().parse( in );
158 Element top =
159 XmlUtils.getChild( XmlUtils.getChild( doc, "methodResponse" ) );
160 String topName = top.getTagName();
161 if ( "fault".equals( topName ) ) {
162 Element value = XmlUtils.getChild( top, "value" );
163 XmlUtils.getChild( value, "struct" );
164 Map faultMap = (Map) XmlUtils.parseSampValue( value );
165 Object fcode = faultMap.get( "faultCode" );
166 Object fmsg = faultMap.get( "faultString" );
167 int code = fcode instanceof Integer
168 ? ((Integer) fcode).intValue()
169 : -9999;
170 final String msg = String.valueOf( fmsg );
171 throw new XmlRpcFault( code, msg );
172 }
173 else if ( "params".equals( topName ) ) {
174 Element value =
175 XmlUtils.getChild( XmlUtils.getChild( top, "param" ),
176 "value" );
177 return XmlUtils.parseSampValue( value );
178 }
179 else {
180 throw new XmlRpcFormatException( "Not <fault> or <params>?" );
181 }
182 }
183 catch ( ParserConfigurationException e ) {
184 throw (IOException) new IOException( "Trouble with XML parsing" )
185 .initCause( e );
186 }
187 catch ( SAXException e ) {
188 throw (IOException) new IOException( "Trouble with XML parsing" )
189 .initCause( e );
190 }
191 catch ( DOMException e ) {
192 throw (IOException) new IOException( "Trouble with XML parsing" )
193 .initCause( e );
194 }
195 }
196
197 /**
198 * IOException representing an incoming XML-RPC fault.
199 */
200 private static class XmlRpcFault extends IOException {
201 public XmlRpcFault( int code, String msg ) {
202 super( "XML-RPC Fault (" + code + ": " + msg + ")" );
203 }
204 }
205 }