KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > remoting > transport > http > HTTPClientInvoker


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7 package org.jboss.remoting.transport.http;
8
9 import java.io.IOException JavaDoc;
10 import java.io.InputStream JavaDoc;
11 import java.io.OutputStream JavaDoc;
12 import java.net.HttpURLConnection JavaDoc;
13 import java.net.URL JavaDoc;
14 import java.util.Iterator JavaDoc;
15 import java.util.Map JavaDoc;
16 import java.util.Set JavaDoc;
17 import org.jboss.logging.Logger;
18 import org.jboss.remoting.CannotConnectException;
19 import org.jboss.remoting.ConnectionFailedException;
20 import org.jboss.remoting.InvokerLocator;
21 import org.jboss.remoting.RemoteClientInvoker;
22 import org.jboss.remoting.marshal.Marshaller;
23 import org.jboss.remoting.marshal.UnMarshaller;
24 import org.jboss.remoting.marshal.http.HTTPMarshaller;
25 import org.jboss.util.Base64;
26
27 /**
28  * HTTP client invoker. Used for making http requests on http/servlet invoker.
29  *
30  * @author <a HREF="mailto:tom@jboss.org">Tom Elrod</a>
31  */

32 public class HTTPClientInvoker extends RemoteClientInvoker
33 {
34
35    protected final Logger log = Logger.getLogger(getClass());
36
37    public HTTPClientInvoker(InvokerLocator locator)
38    {
39       super(locator);
40    }
41
42    /**
43     * @param sessionId
44     * @param invocation
45     * @param marshaller
46     * @return
47     * @throws java.io.IOException
48     * @throws org.jboss.remoting.ConnectionFailedException
49     *
50     */

51    protected Object JavaDoc transport(String JavaDoc sessionId, Object JavaDoc invocation, Map JavaDoc metadata,
52                               Marshaller marshaller, UnMarshaller unmarshaller)
53          throws IOException JavaDoc, ConnectionFailedException
54    {
55       String JavaDoc targetURL = getLocator().getOriginalURI();
56       Object JavaDoc httpResponse = useHttpURLConnection(targetURL, invocation, metadata, marshaller, unmarshaller);
57
58       return httpResponse;
59    }
60
61    private Object JavaDoc useHttpURLConnection(String JavaDoc url, Object JavaDoc invocation, Map JavaDoc metadata,
62                                        Marshaller marshaller, UnMarshaller unmarshaller)
63    {
64       Object JavaDoc result = null;
65       try
66       {
67          HttpURLConnection JavaDoc conn = createURLConnection(url, metadata);
68
69          // check to see if basic auth required
70
String JavaDoc basicAuth = getBasicAuth(metadata);
71          if(basicAuth != null)
72          {
73             conn.setRequestProperty("Authorization", basicAuth);
74          }
75
76          // Get the request method type
77
boolean isPost = true;
78          if(metadata != null)
79          {
80             String JavaDoc type = (String JavaDoc) metadata.get("TYPE");
81             if(type != null && type.equals("GET"))
82             {
83                isPost = false;
84             }
85
86             // Set request headers
87
Map JavaDoc header = (Map JavaDoc) metadata.get("HEADER");
88             if(header != null)
89             {
90                Set JavaDoc keys = header.keySet();
91                Iterator JavaDoc itr = keys.iterator();
92                while(itr.hasNext())
93                {
94                   String JavaDoc key = (String JavaDoc) itr.next();
95                   String JavaDoc value = (String JavaDoc) header.get(key);
96                   log.debug("Setting request header with " + key + " : " + value);
97                   conn.setRequestProperty(key, value);
98                }
99             }
100          }
101
102          if(isPost)
103          {
104             //POST
105
conn.setDoOutput(true);
106             conn.setDoInput(true);
107             conn.setRequestMethod("POST");
108
109             OutputStream JavaDoc stream = conn.getOutputStream();
110             marshaller.write(invocation, stream);
111             InputStream JavaDoc is = conn.getInputStream();
112             Map JavaDoc headers = conn.getHeaderFields();
113             result = unmarshaller.read(is, headers);
114          }
115          else
116          {
117             throw new Exception JavaDoc("HTTP GET opperation not currently supported.");
118          }
119       }
120       catch(Exception JavaDoc e)
121       {
122          log.debug("Error invoking http client invoker.", e);
123          throw new CannotConnectException("Can not connect http client invoker.", e);
124       }
125
126       return result;
127    }
128
129    protected HttpURLConnection JavaDoc createURLConnection(String JavaDoc url, Map JavaDoc metadata) throws IOException JavaDoc
130    {
131       URL JavaDoc externalURL = null;
132       HttpURLConnection JavaDoc httpURLConn = null;
133
134       // need to find out if need to use a proxy or not
135
String JavaDoc proxyHost = null;
136       String JavaDoc proxyportString = null;
137       int proxyPort = -1;
138       boolean proxyOn = true;
139
140       if(metadata != null)
141       {
142          // first check the metadata as will have precedence
143
proxyHost = (String JavaDoc) metadata.get("http.proxyHost");
144          proxyportString = (String JavaDoc) metadata.get("http.proxyPort");
145          if(proxyportString != null && proxyportString.length() > 0)
146          {
147             try
148             {
149                proxyPort = Integer.parseInt(proxyportString);
150             }
151             catch(NumberFormatException JavaDoc e)
152             {
153                log.warn("Error converting proxy port specified (" + proxyportString + ") to a number.");
154             }
155          }
156       }
157
158       // if not set in the metadata, try the system properties
159
if(proxyHost == null)
160       {
161          // have found that the actual system property to be set can differ between VMs,
162
// so will try all the ones I know of.
163
proxyHost = System.getProperty("http.proxyHost");
164          if(proxyHost == null)
165          {
166             proxyHost = System.getProperty("proxyHost");
167          }
168
169          // since not set by metadata, need to check if proxy turned off by property setting
170
String JavaDoc proxyOnString = System.getProperty("http.proxySet");
171          if(proxyOnString == null)
172          {
173             proxyOnString = System.getProperty("proxySet");
174          }
175          if(proxyOnString != null)
176          {
177             proxyOn = Boolean.getBoolean(proxyOnString);
178          }
179       }
180       if(proxyPort < 0)
181       {
182          String JavaDoc proxyPortString = System.getProperty("http.proxyPort");
183          if(proxyPortString == null)
184          {
185             proxyPortString = System.getProperty("proxyPort");
186          }
187          if(proxyPortString != null)
188          {
189             try
190             {
191                proxyPort = Integer.parseInt(proxyPortString);
192             }
193             catch(NumberFormatException JavaDoc e)
194             {
195                log.warn("Error converting proxy port specified (" + proxyportString + ") to a number.");
196             }
197          }
198       }
199
200       // now determin if going to use proxy or not
201
if(proxyHost != null && proxyOn)
202       {
203          // is ok if port is -1 since URL constructor will use default port for protocol
204
externalURL = new URL JavaDoc("http", proxyHost, proxyPort, url);
205
206          httpURLConn = (HttpURLConnection JavaDoc) externalURL.openConnection();
207
208          // since know it is a proxy being used, see if have proxy auth
209
String JavaDoc proxyAuth = getProxyAuth(metadata);
210          if(proxyAuth != null)
211          {
212             httpURLConn.setRequestProperty("Proxy-Authorization", proxyAuth);
213          }
214       }
215       else
216       {
217          externalURL = new URL JavaDoc(url);
218          httpURLConn = (HttpURLConnection JavaDoc) externalURL.openConnection();
219       }
220
221       return httpURLConn;
222    }
223
224    private String JavaDoc getProxyAuth(Map JavaDoc metadata)
225    {
226       String JavaDoc authString = null;
227       String JavaDoc username = null;
228       String JavaDoc password = null;
229
230       if(metadata != null)
231       {
232          username = (String JavaDoc) metadata.get("http.proxy.username");
233       }
234       if(username == null || username.length() == 0)
235       {
236          username = System.getProperty("http.proxy.username");
237       }
238       if(metadata != null)
239       {
240          password = (String JavaDoc) metadata.get("http.proxy.password");
241       }
242       if(password == null || password.length() == 0)
243       {
244          password = System.getProperty("http.proxy.password");
245       }
246
247       if(username != null && password != null)
248       {
249          StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
250          buffer.append(username);
251          buffer.append(":");
252          buffer.append(password);
253
254          String JavaDoc encoded = Base64.encodeBytes(buffer.toString().getBytes());
255
256          authString = "Basic " + encoded;
257
258       }
259
260       return authString;
261    }
262
263    private String JavaDoc getBasicAuth(Map JavaDoc metadata)
264    {
265       String JavaDoc authString = null;
266       String JavaDoc username = null;
267       String JavaDoc password = null;
268
269       if(metadata != null)
270       {
271          username = (String JavaDoc) metadata.get("http.basic.username");
272       }
273       if(username == null || username.length() == 0)
274       {
275          username = System.getProperty("http.basic.username");
276       }
277       if(metadata != null)
278       {
279          password = (String JavaDoc) metadata.get("http.basic.password");
280       }
281       if(password == null || password.length() == 0)
282       {
283          password = System.getProperty("http.basic.password");
284       }
285
286       if(username != null && password != null)
287       {
288          StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
289          buffer.append(username);
290          buffer.append(":");
291          buffer.append(password);
292
293          String JavaDoc encoded = Base64.encodeBytes(buffer.toString().getBytes());
294
295          authString = "Basic " + encoded;
296
297       }
298
299       return authString;
300    }
301
302
303    /**
304     * subclasses must implement this method to provide a hook to connect to the remote server, if this applies
305     * to the specific transport. However, in some transport implementations, this may not make must difference since
306     * the connection is not persistent among invocations, such as SOAP. In these cases, the method should
307     * silently return without any processing.
308     *
309     * @throws org.jboss.remoting.ConnectionFailedException
310     *
311     */

312    protected void handleConnect() throws ConnectionFailedException
313    {
314       // NO OP as not statefull connection
315
}
316
317    /**
318     * subclasses must implement this method to provide a hook to disconnect from the remote server, if this applies
319     * to the specific transport. However, in some transport implementations, this may not make must difference since
320     * the connection is not persistent among invocations, such as SOAP. In these cases, the method should
321     * silently return without any processing.
322     */

323    protected void handleDisconnect()
324    {
325       // NO OP as not statefull connection
326
}
327
328    /**
329     * Each implementation of the remote client invoker should have
330     * a default data type that is uses in the case it is not specified
331     * in the invoker locator uri.
332     *
333     * @return
334     */

335    protected String JavaDoc getDefaultDataType()
336    {
337       return HTTPMarshaller.DATATYPE;
338    }
339
340 }
Popular Tags