KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jdon > bussinessproxy > remote > http > HttpClient


1 /**
2  * Copyright 2003-2006 the original author or authors.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6
7        http://www.apache.org/licenses/LICENSE-2.0
8
9   * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */

15
16 package com.jdon.bussinessproxy.remote.http;
17
18 import java.lang.reflect.Method JavaDoc;
19 import java.net.HttpURLConnection JavaDoc;
20 import java.rmi.RemoteException JavaDoc;
21
22 import com.jdon.bussinessproxy.TargetMetaDef;
23 import com.jdon.bussinessproxy.remote.auth.AuthException;
24 import com.jdon.util.Debug;
25
26
27 /**
28  * 将客户端的方法调用等å?‚数通过httpå??è®®å?‘å¾€J2EEæœ?务器
29  *
30  * 安全验è¯?是采å?–æœ?务器端基于Httpçš„Basice Auth,因此J2EEæœ?务器端需è¦?设置。
31  * å?¯ä»¥ä½¿ç”¨ä¸€ä¸ªä¸“门的EJB网关æœ?务器æ?¥ä¸“门供远程调用。
32  *
33  *
34  * @author banq
35  */

36 public class HttpClient {
37
38   public final static String JavaDoc module = HttpClient.class.getName();
39
40   private HttpServerParam httpServerParam;
41
42   private static int requestNb;
43   private String JavaDoc sessionId;
44
45   private String JavaDoc userPasswordPair = null;
46
47   /** Default Server File*/
48   private static final int DEFAULT_THREAD_COUNT = 1;
49
50   /** The number of parallel thread used to perform the http call. */
51   private int maxThreadCount = DEFAULT_THREAD_COUNT;
52
53   /** The number of thread that are currently making a call */
54   private int curUsedThread = 0;
55
56   // Singleton attribute
57
protected static HttpClient httpClient = new HttpClient();
58   public static HttpClient getInstance() {
59     return httpClient;
60   }
61
62   private HttpClient() {
63     httpServerParam = new HttpServerParam();
64
65   }
66
67   /**
68    * 外界å?¯ä»¥è®¾ç½®æ”¹å?˜httpServerParam中的å?‚æ•°
69    * @param httpServerParam
70    */

71   public void setHttpServerParam(HttpServerParam httpServerParam) {
72     this.httpServerParam = httpServerParam;
73   }
74
75   /**
76    * Invokes EJB service
77    */

78   public Object JavaDoc invoke(TargetMetaDef targetMetaDef, Method JavaDoc m, Object JavaDoc[] args) throws
79       Throwable JavaDoc {
80     Object JavaDoc result = null;
81
82     getThreadLock();
83
84     int currentRequestNb = requestNb++;
85     Debug.logVerbose("[JdonFramework]Start remote call " + currentRequestNb + " " +
86                      m.getName(), module);
87
88     //准备å?‚æ•°
89
HttpRequest request = new HttpRequest(
90             targetMetaDef, m.getName(), m.getParameterTypes(), args);
91
92     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(httpServerParam.getServletPath().
93                                        toString());
94     if (sessionId != null) {
95       sb.append(";jsessionid=");
96       sb.append(sessionId);
97     }
98     httpServerParam.setServletPath(sb.toString());
99
100     result = invokeHttp(request, args);
101
102     Debug.logVerbose("[JdonFramework]Ending remote call " + currentRequestNb, module);
103     releaseThreadLock();
104
105     return result;
106   }
107
108   /**
109    * Performs the http call.
110    */

111   public Object JavaDoc invokeHttp(HttpRequest request, Object JavaDoc[] args) throws
112       Throwable JavaDoc {
113     HttpResponse httpResponse;
114     try {
115       HttpConnectionHelper httpConnectionHelper = new HttpConnectionHelper();
116
117       HttpURLConnection JavaDoc httpURLConnection;
118       if (httpServerParam.isDebug()) {//调试方å¼?无需安全验è¯?
119
//连接�务器
120
Debug.logVerbose("[JdonFramework]connect service..", module);
121           httpURLConnection = httpConnectionHelper.connectService(httpServerParam, null);
122           //å?‘出request
123
Debug.logVerbose("[JdonFramework]send request: class=" + request.getTargetMetaDef().getClassName(), module);
124           Debug.logVerbose("[JdonFramework]method=" + request.getMethodName(), module);
125           httpConnectionHelper.sendObjectRequest(httpURLConnection, request);
126       }else{
127           httpURLConnection = httpConnectionHelper.connectService(httpServerParam, getUserPassword(args));
128           //å?‘出request
129
httpConnectionHelper.sendObjectRequest(httpURLConnection, request);
130           //接å?—response
131
if (httpURLConnection.getResponseCode() == 401) {
132               throw new AuthException(" http Server authentication failed!");
133           }
134       }
135           
136       //接å?—response
137
httpResponse = (HttpResponse) httpConnectionHelper.getObjectResponse(
138           httpURLConnection);
139       //获得jsessionid
140
sessionId = httpURLConnection.getHeaderField("jsessionid");
141
142       //断开连接
143
httpURLConnection.disconnect();
144
145       if (httpResponse.isExceptionThrown())
146         throw httpResponse.getThrowable();
147       return httpResponse.getResult();
148
149     } catch (ClassNotFoundException JavaDoc e) {
150       Debug.logError(e, module);
151       throw new RemoteException JavaDoc(" Class Not Found ", e);
152     } catch (AuthException ae) {
153       throw new AuthException(ae.getMessage());
154     } catch (Exception JavaDoc e) {
155       String JavaDoc message = "invokeHttp error:";
156       Debug.logError(message + e, module);
157       throw new RemoteException JavaDoc(message, e);
158     }
159
160   }
161
162   /**
163    * 用户第一次 Login调用
164    */

165   public Object JavaDoc invokeAuth(Object JavaDoc[] args) throws Throwable JavaDoc {
166     Object JavaDoc result = null;
167     try {
168
169       Debug.logVerbose("[JdonFramework] begin to auth from J2EE Server", module);
170
171       HttpConnectionHelper httpConnectionHelper = new HttpConnectionHelper();
172
173       //连接æœ?务器
174
HttpURLConnection JavaDoc httpURLConnection = httpConnectionHelper.connectLogin(
175           httpServerParam, getUserPassword(args));
176       //å?‘出request
177

178       //传递一个å?‚数,å?¯ä»¥ä¸?用
179
java.util.Hashtable JavaDoc params = new java.util.Hashtable JavaDoc();
180       params.put("login", "1");
181       httpConnectionHelper.sendDataRequest(httpURLConnection, params);
182
183       //接å?—response
184
int status = httpURLConnection.getResponseCode();
185       if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
186         throw new AuthException(" http Server authentication failed!");
187       }
188
189       result = httpConnectionHelper.getStringResponse(httpURLConnection);
190
191       //断开连接
192
httpURLConnection.disconnect();
193
194 // Debug.logVerbose("[JdonFramework]result:"+text, module);
195
} catch (AuthException ae) {
196       throw new AuthException(ae.getMessage());
197     } catch (Exception JavaDoc e) {
198       String JavaDoc message = "invokeAuth error:";
199       Debug.logError(message + e, module);
200       throw new RemoteException JavaDoc(message, e);
201     }
202
203     return result;
204   }
205
206   /**
207    * "username:password"
208    * @param args
209    * @return
210    * @throws AuthException
211    */

212   private String JavaDoc getUserPassword(Object JavaDoc[] args) throws AuthException {
213     if (args ==null) throw new AuthException("auth error: args is null");
214     if ( (userPasswordPair == null) || userPasswordPair.equals("")) {
215       try {
216         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
217           if ( (args[0] != null) && (args[1] != null)) {
218             sb.append(args[0]);
219             sb.append(":");
220             sb.append(args[1]);
221             userPasswordPair = sb.toString();
222           }
223     } catch (Exception JavaDoc e) {
224         throw new AuthException("auth error: args is null");
225     }
226     }
227     Debug.logVerbose("[JdonFramework] url param is" + userPasswordPair, module);
228     return userPasswordPair;
229   }
230
231   /**
232    * This method is used to limit the concurrent http call to the max
233    * fixed by maxThreadCount and to wait the end of the first call that
234    * will return the session id.
235    */

236   private synchronized void getThreadLock() {
237     while (sessionId == null && curUsedThread > 1) {
238       try {
239         Debug.logVerbose(
240             "No session. Only one thread is authorized. Waiting ...", module);
241         wait();
242       } catch (InterruptedException JavaDoc e) {
243         e.printStackTrace();
244       }
245     }
246
247     while (curUsedThread >= maxThreadCount) {
248       try {
249         Debug.logVerbose("[JdonFramework]Max concurent http call reached. Waiting ...", module);
250         wait();
251       } catch (InterruptedException JavaDoc e) {
252         e.printStackTrace();
253       }
254     }
255     curUsedThread++;
256   }
257
258   private synchronized void releaseThreadLock() {
259     curUsedThread--;
260     notify();
261   }
262
263   public int getThreadCount() {
264     return maxThreadCount;
265   }
266
267   public void setThreadCount(int threadCount) {
268     this.maxThreadCount = threadCount;
269
270     Debug.logVerbose("[JdonFramework]Max concurrent thread set to " + threadCount, module);
271   }
272
273 }
274
Popular Tags