KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sync4j > test > tools > HttpClientConnection


1 /**
2  * Copyright (C) 2003-2005 Funambol
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18 package sync4j.test.tools;
19
20 import java.net.*;
21 import java.io.*;
22 import java.util.logging.Logger JavaDoc;
23 import java.util.logging.Level JavaDoc;
24
25 import org.jibx.runtime.*;
26 import org.jibx.runtime.impl.*;
27
28 import sync4j.framework.core.Constants;
29 import sync4j.framework.core.SyncML;
30 import sync4j.framework.core.RepresentationException;
31 import sync4j.framework.core.Sync4jException;
32 import sync4j.framework.tools.WBXMLTools;
33
34 /**
35  *
36  * @version $Id: HttpClientConnection.java,v 1.6 2005/03/02 20:57:40 harrie Exp $
37  *
38  */

39 public final class HttpClientConnection {
40     public static String JavaDoc LOG_NAME = "sync4j.test.tools.PostSyncML";
41     private static final Logger JavaDoc log = Logger.getLogger(LOG_NAME);
42
43     //
44
// todo : decide if HttpURLConnection is a good implementation strategy...
45
// The other way to implement this would be to use a java.net.Socket
46
// The problem with java.net.Socket is that I'd have to write alot
47
// of low-level HTTP protocol code. The advantage of java.net.Socket
48
// is that I could explicitly set a Socket timeout value. Hmm....
49
//
50
// Also, another way to implement this class would be to use Apache's
51
// HttpClient code: http://jakarta.apache.org/commons/httpclient/
52
//
53

54     private final HttpURLConnection conn;
55     private OutputStream out;
56     private final String JavaDoc serverAddress;
57
58     private String JavaDoc lastResponse; // as string
59
private String JavaDoc lastMessage; // as string
60

61
62     /**
63      *
64      * @param strServerAddress must be non-null
65      *
66      */

67     public HttpClientConnection(final String JavaDoc strServerAddress)
68     throws IOException
69     {
70         if (strServerAddress == null)
71         {
72             throw new NullPointerException JavaDoc("strServerAddress parameter is null");
73         }
74
75         serverAddress = strServerAddress;
76
77         if (serverAddress.startsWith("http:") == false)
78         {
79             throw new IllegalArgumentException JavaDoc(
80                     "server address must start with 'http:'");
81
82         }
83
84         URL u = null;
85         try
86         {
87             u = new URL(serverAddress);
88         }
89         catch (java.net.MalformedURLException JavaDoc ex)
90         {
91             throw new IllegalArgumentException JavaDoc(
92                     "server address is not a valid URL");
93         }
94
95         lastMessage = lastResponse = null;
96
97         Object JavaDoc obj = u.openConnection();
98         if ((obj instanceof java.net.HttpURLConnection JavaDoc) == false)
99         {
100             // todo : throw exception here
101
}
102         conn = (HttpURLConnection) obj;
103         conn.setDoOutput(true);
104         conn.setDoInput(true);
105         conn.setAllowUserInteraction(false);
106         conn.setRequestMethod("POST");
107         conn.setUseCaches(false);
108         conn.setInstanceFollowRedirects(false);
109         conn.setRequestProperty("User-Agent", this.getClass().toString());
110     }
111
112     public SyncML sendMessage(final SyncML msg) throws Exception JavaDoc {
113         String JavaDoc syncML = marshallSyncML(msg);
114         return sendMessage(syncML);
115     }
116
117     public SyncML sendMessage(final String JavaDoc msg)
118     throws IOException, Sync4jException, RepresentationException {
119
120         final byte[] yaData = msg.getBytes();
121
122         conn.setRequestProperty("Content-Type", Constants.MIMETYPE_SYNCMLDS_XML);
123         conn.setRequestProperty("Content-Length", "" + yaData.length);
124
125         out = conn.getOutputStream();
126         out.write(yaData);
127         out.flush();
128
129         InputStream in = conn.getInputStream();
130
131         final int iResponseCode = conn.getResponseCode();
132
133         if (iResponseCode != HttpURLConnection.HTTP_OK) {
134             String JavaDoc error = "Response status: "
135                          + iResponseCode
136                          + ", Response message: "
137                          + conn.getResponseMessage()
138                          ;
139             throw new IOException(error);
140         }
141
142         final String JavaDoc strResponseContentType = conn.getContentType();
143
144         if (strResponseContentType == null)
145         {
146             throw new IOException("Content type: " + strResponseContentType);
147         }
148
149         if (strResponseContentType.equals(Constants.MIMETYPE_SYNCMLDS_XML) == false)
150         {
151             throw new IOException( "Content type: "
152                                  + strResponseContentType
153                                  + " (should be "
154                                  + Constants.MIMETYPE_SYNCMLDS_XML
155                                  + ")"
156                                  );
157         }
158
159         lastMessage = msg;
160
161         final int iResponseContentLength = conn.getContentLength();
162
163         if (iResponseContentLength < 1)
164         {
165            throw new IOException("Response content length: " + iResponseContentLength);
166         }
167
168         final byte[] yaResponse = new byte[iResponseContentLength];
169
170         int n = 0;
171         int iBytesRead = 0;
172         do
173         {
174             n = in.read(yaResponse,
175                     iBytesRead,
176                     yaResponse.length - iBytesRead);
177             if (n > 0)
178             {
179                 iBytesRead += n;
180             }
181         } while (n != -1);
182
183         if (iBytesRead != iResponseContentLength)
184         {
185             // todo : throw exception - ?
186
}
187
188         lastResponse = new String JavaDoc(yaResponse);
189
190         SyncML syncML = null;
191         try {
192
193             syncML = unmarshallSyncML(lastResponse);
194
195         } catch(Exception JavaDoc e) {
196             throw new Sync4jException(e);
197         }
198
199         return syncML;
200     }
201
202     public SyncML sendWBXMLMessage(final byte[] msg)
203     throws IOException, Sync4jException, RepresentationException
204     {
205         final byte[] yaData = msg;
206
207         conn.setRequestProperty("Content-Type", Constants.MIMETYPE_SYNCMLDS_WBXML);
208         conn.setRequestProperty("Content-Length", "" + yaData.length);
209
210         out = conn.getOutputStream();
211         out.write(yaData);
212         out.flush();
213
214         InputStream in = conn.getInputStream();
215
216         final int iResponseCode = conn.getResponseCode();
217
218         if (iResponseCode != HttpURLConnection.HTTP_OK)
219         {
220             String JavaDoc error = "Response status: "
221                          + iResponseCode
222                          + ", Response message: "
223                          + conn.getResponseMessage()
224                          ;
225             throw new IOException(error);
226         }
227
228         final String JavaDoc strResponseContentType = conn.getContentType();
229
230         if (strResponseContentType == null)
231         {
232             throw new IOException("Content type: " + strResponseContentType);
233         }
234
235         if (strResponseContentType.equals(Constants.MIMETYPE_SYNCMLDS_WBXML) == false)
236         {
237             throw new IOException( "Content type: "
238                                  + strResponseContentType
239                                  + " (should be "
240                                  + Constants.MIMETYPE_SYNCMLDS_WBXML
241                                  + ")"
242                                  );
243         }
244
245         final int iResponseContentLength = conn.getContentLength();
246
247         if (iResponseContentLength < 1)
248         {
249            throw new IOException("Response content length: " + iResponseContentLength);
250         }
251
252         final byte[] yaResponse = new byte[iResponseContentLength];
253
254         int n = 0;
255         int iBytesRead = 0;
256         do
257         {
258             n = in.read(yaResponse,
259                     iBytesRead,
260                     yaResponse.length - iBytesRead);
261             if (n > 0)
262             {
263                 iBytesRead += n;
264             }
265         } while (n != -1);
266
267         if (iBytesRead != iResponseContentLength)
268         {
269             // todo : throw exception - ?
270
}
271
272         //
273
//TRN - convert yaResponse from WBXML to XML string, then create the Message
274
//
275
String JavaDoc xmlResponse = WBXMLTools.wbxmlToXml(yaResponse);
276
277         SyncML syncML = null;
278         try {
279
280             syncML = unmarshallSyncML(xmlResponse);
281
282         } catch(Exception JavaDoc e) {
283             throw new Sync4jException(e);
284         }
285
286         return syncML;
287     }
288
289     public void close()
290     {
291         if (conn != null)
292         {
293             conn.disconnect();
294             try
295             {
296                 out.close();
297             }
298             catch (java.io.IOException JavaDoc ex)
299             {
300                 // ignore exception
301
}
302         }
303     }
304
305     public String JavaDoc toString()
306     {
307         return serverAddress;
308     }
309
310     public String JavaDoc getLastMessage() {
311         return lastMessage;
312     }
313
314     public String JavaDoc getLastResponse() {
315         return lastResponse;
316     }
317
318     private SyncML unmarshallSyncML(String JavaDoc response) throws Sync4jException {
319
320         SyncML syncML = null;
321         try {
322             IBindingFactory f = BindingDirectory.getFactory(SyncML.class);
323             IUnmarshallingContext c = f.createUnmarshallingContext();
324
325             syncML = (SyncML)c.unmarshalDocument(new ByteArrayInputStream(response.getBytes()), null);
326
327         } catch(org.jibx.runtime.JiBXException e) {
328             e.printStackTrace();
329             throw new Sync4jException(e);
330         } catch(Exception JavaDoc e) {
331             e.printStackTrace();
332             throw new Sync4jException(e);
333         }
334         return syncML;
335     }
336
337     private String JavaDoc marshallSyncML(SyncML syncML) throws Sync4jException {
338         String JavaDoc msg = null;
339         try {
340
341             ByteArrayOutputStream bout = new ByteArrayOutputStream();
342
343             IBindingFactory f = BindingDirectory.getFactory(SyncML.class);
344             IMarshallingContext c = f.createMarshallingContext();
345             c.setIndent(0);
346             c.marshalDocument(syncML, "UTF-8", null, bout);
347
348             msg = new String JavaDoc(bout.toByteArray());
349
350         } catch(org.jibx.runtime.JiBXException e) {
351             e.printStackTrace();
352             throw new Sync4jException(e);
353         } catch(Exception JavaDoc e) {
354             e.printStackTrace();
355             throw new Sync4jException(e);
356         }
357         return msg;
358     }
359 }
360
Popular Tags