KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sync4j > syncclient > spds > BaseSyncMLClient


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
19 package sync4j.syncclient.spds;
20
21 import java.io.InputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.OutputStream JavaDoc;
24
25 import java.net.URL JavaDoc;
26 import java.net.URLConnection JavaDoc;
27
28 import java.util.Properties JavaDoc;
29 import java.util.Vector JavaDoc;
30
31 import sync4j.syncclient.common.logging.Logger;
32 import sync4j.syncclient.spds.SyncMLClient;
33
34 import sync4j.syncclient.spds.event.SyncTransportEvent;
35
36 import sync4j.syncclient.spds.event.SyncTransportListener;
37
38
39 /**
40  * Implement send / receive message by HttpConnection
41  *
42  * The charSet is specified with the system property
43  * <code>spds.charset</code>;
44  * if <code>DEFAULT</code> value, the default charSet value is taken.<br>
45  * if no value, the default charSet API <code>UTF-8</vode> value is taken.
46  *
47  * @author Stefano Fornari
48  *
49  * @version $Id: BaseSyncMLClient.java,v 1.5 2005/01/19 11:18:36 fabius Exp $
50  *
51  */

52 abstract class BaseSyncMLClient implements SyncMLClient {
53
54     // --------------------------------------------------------------- Constants
55

56     private static final String JavaDoc API_CHARSET = "UTF-8" ;
57     private static final String JavaDoc PROP_CHARSET = "spds.charset" ;
58     private static final String JavaDoc KEY_DEFAULT_CHARSET = "DEFAULT" ;
59
60     private static final String JavaDoc PROP_CONTENT_TYPE = "Content-Type" ;
61     private static final String JavaDoc PROP_CONTENT_LENGTH = "Content-Length" ;
62
63     private static final String JavaDoc PROP_PROXY_HOST = "http.proxyHost" ;
64     private static final String JavaDoc PROP_PROXY_PORT = "http.proxyPort" ;
65
66     // --------------------------------------------------------------- Private data
67

68     private URL JavaDoc requestURL = null ;
69     private Logger logger = new Logger() ;
70     private Vector JavaDoc syncTransportListeners = null ;
71     private SyncTransportEvent syncTransportEvent = null ;
72
73     // --------------------------------------------------------------- Properties
74

75     /**
76      * The charSet (encoding)
77      */

78     private String JavaDoc charSet = null;
79
80     /**
81      * Getter for property charSet.
82      * @return Value of property charSet.
83      */

84     public String JavaDoc getCharSet() {
85         return charSet;
86     }
87
88     /**
89      * Setter for property charSet
90      * @param charSet New value of property charSet.
91     */

92     public void setCharSet(String JavaDoc charSet) {
93         this.charSet = charSet;
94     }
95
96     /**
97      * The content-type (mime-type)
98      */

99     private String JavaDoc contentType = null;
100
101
102     /**
103      * Setter for property contentType
104      * @param contentType
105      * New value of property contentType.
106      */

107     public void setContentType(String JavaDoc contentType) {
108         this.contentType = contentType;
109     }
110
111     /**
112      * The timeout (in milliseconds) for the request
113      * (it defaults to 1 minute)
114      */

115     private int timeout = 60000;
116
117     /**
118      * Getter for property timeout.
119      * @return Value of property timeout.
120      */

121     public int getTimeout() {
122         return timeout;
123     }
124
125     /**
126      * Setter for property timeout.
127      * Default: 60 sec. 0 means forever
128      * @param timeout New value of property timeout.
129     */

130     public void setTimeout(int timeout) {
131         this.timeout = timeout;
132     }
133
134     /**
135      * The proxy server. If null no proxy are used.
136      */

137     private String JavaDoc proxyHost = null;
138
139     /** Getter for property proxyHost.
140      * @return Value of property proxyHost.
141      */

142     public java.lang.String JavaDoc getProxyHost() {
143         return proxyHost;
144     }
145
146     /** Setter for property proxyHost.
147      * @param proxyHost New value of property proxyHost.
148      */

149     public void setProxyHost(java.lang.String JavaDoc proxyHost) {
150         this.proxyHost = proxyHost;
151     }
152
153     /**
154      * The proxy server port.
155      * It defaults to 8080.
156      */

157     private int proxyPort = 8080;
158
159     /** Getter for property proxyPort.
160      * @return Value of property proxyPort.
161      */

162     public int getProxyPort() {
163         return proxyPort;
164     }
165
166     /** Setter for property proxyPort.
167      * @param proxyPort New value of property proxyPort.
168      */

169     public void setProxyPort(int proxyPort) {
170         this.proxyPort = proxyPort;
171     }
172
173     /**
174      * The proxy enable / disable setting
175      * It defaults to false.
176      */

177     private boolean useProxy = false;
178
179     /** Getter for property useProxy.
180      * @return Value of property useProxy.
181      */

182     public boolean getUseProxy() {
183         return useProxy;
184     }
185
186     /** Setter for property userProxy.
187      * @param useProxy New value of property userProxy.
188      */

189     public void setUseProxy(boolean useProxy) {
190         this.useProxy = useProxy;
191     }
192
193     /** Setter for property url.
194      * @param url New value of property url.
195      */

196     public void setUrl(String JavaDoc url)
197     throws IOException JavaDoc {
198
199         if (url == null) {
200             throw new NullPointerException JavaDoc
201                 ("requestURL parameter is null");
202         }
203
204         try {
205             this.requestURL = new URL JavaDoc(url);
206         } catch (Exception JavaDoc e) {
207             throw new IOException JavaDoc (e.getMessage());
208
209         }
210     }
211
212     // ------------------------------------------------------------ Constructors
213

214     /**
215      *
216      * @param requestURL must be non-null
217      *
218      */

219     public BaseSyncMLClient() {
220
221       syncTransportListeners = new Vector JavaDoc();
222
223     }
224
225     // ---------------------------------------------------------- Public methods
226

227     /**
228      * Register a new SyncTransportListener.
229      *
230      * @param listener
231      */

232     public void addSyncTransportListener (SyncTransportListener listener) {
233         syncTransportListeners.addElement(listener);
234     }
235
236     /**
237      * Remove the specified SyncTransportListener.
238      *
239      * @param listener
240      */

241     public void removeSyncTransportListener (SyncTransportListener listener) {
242         syncTransportListeners.removeElement(listener);
243     }
244
245     public String JavaDoc toString() {
246         return requestURL.toString();
247     }
248
249     // ---------------------------------------------------------- Protected methods
250

251     protected String JavaDoc sendMessage(byte[] bytes)
252     throws IOException JavaDoc {
253
254         URLConnection JavaDoc conn = null ;
255         OutputStream JavaDoc os = null ;
256         InputStream JavaDoc is = null ;
257
258         Properties JavaDoc prop = null ;
259
260         setCharSet();
261
262         prop = System.getProperties();
263
264         try {
265
266             if (this.useProxy) {
267                 prop.put(PROP_PROXY_HOST, proxyHost ) ;
268                 prop.put(PROP_PROXY_PORT, String.valueOf(proxyPort) ) ;
269             }
270
271             conn = requestURL.openConnection();
272             conn.setDoInput (true) ;
273             conn.setDoOutput(true) ;
274             conn.setRequestProperty (PROP_CONTENT_TYPE,
275                                      contentType );
276             conn.setRequestProperty (PROP_CONTENT_LENGTH,
277                                      String.valueOf(bytes.length) );
278
279             if (logger.isLoggable(Logger.DEBUG)) {
280                 logger.debug("Connected to " + requestURL);
281             }
282
283             os = conn.getOutputStream();
284
285             syncTransportEvent =
286                 new SyncTransportEvent(SyncTransportEvent.SEND_DATA_BEGIN ,
287                                        bytes.length );
288             fireSyncTransportEvent(syncTransportEvent);
289
290             os.write(bytes); os.flush();
291
292             syncTransportEvent =
293                 new SyncTransportEvent(SyncTransportEvent.SEND_DATA_END ,
294                                        bytes.length );
295             fireSyncTransportEvent(syncTransportEvent);
296
297             if (logger.isLoggable(Logger.DEBUG)) {
298                 logger.debug("Message sent" ) ;
299                 logger.debug("Reading response..." ) ;
300             }
301
302             is = conn.getInputStream();
303
304             int contentLength = conn.getContentLength () ;
305             String JavaDoc contentType = conn.getContentType () ;
306
307             syncTransportEvent =
308                 new SyncTransportEvent(SyncTransportEvent.RECEIVE_DATA_BEGIN ,
309                                        contentLength );
310             fireSyncTransportEvent(syncTransportEvent);
311
312             if (logger.isLoggable(Logger.DEBUG)) {
313                 logger.debug(PROP_CONTENT_TYPE + ": " + contentType ) ;
314                 logger.debug(PROP_CONTENT_LENGTH + ": " + contentLength ) ;
315             }
316
317             if (contentType == null) {
318                 throw new IOException JavaDoc("Content type is null");
319             }
320
321             byte[] buf = new byte[contentLength];
322
323             int c = 0 ;
324             int b = 0 ;
325
326             while ((c < buf.length) && (b = is.read(buf, c, buf.length-c)) >= 0) {
327                 c+=b;
328                 syncTransportEvent =
329                     new SyncTransportEvent(SyncTransportEvent.DATA_RECEIVED ,
330                                            b );
331                 fireSyncTransportEvent(syncTransportEvent);
332             }
333
334             if (logger.isLoggable(Logger.DEBUG)) {
335                 logger.debug("Response read") ;
336             }
337
338             syncTransportEvent =
339                 new SyncTransportEvent(SyncTransportEvent.RECEIVE_DATA_END ,
340                            contentLength );
341             fireSyncTransportEvent(syncTransportEvent);
342
343             if (!KEY_DEFAULT_CHARSET.equals(charSet)) {
344                 return new String JavaDoc(buf, charSet);
345             } else {
346                 return new String JavaDoc(buf);
347             }
348
349         } catch (IOException JavaDoc e) {
350             e.printStackTrace();
351             throw e;
352         } finally {
353
354             //
355
// Shut down the connection
356
//
357

358             if (is != null) {
359                 is.close();
360                 is = null ;
361             }
362             if (os != null) {
363                 os.close();
364                 os = null ;
365             }
366             if (conn != null) {
367                 conn = null ;
368             }
369         }
370
371     }
372
373     // ---------------------------------------------------------- Private methods
374

375     /**
376      * set charSet
377      */

378     private void setCharSet() {
379         this.charSet = System.getProperty(PROP_CHARSET, API_CHARSET);
380     }
381
382     /**
383      * Fire SyncTransportEvent
384      * to syncTransportListeners.
385      *
386      * @param syncTransportEvent
387      */

388     private void fireSyncTransportEvent(SyncTransportEvent syncTransportEvent) {
389
390          for (int i = 0, l = syncTransportListeners.size(); i < l; i++) {
391
392            if (syncTransportEvent.getType() ==
393                         SyncTransportEvent.SEND_DATA_BEGIN) {
394                 ((SyncTransportListener)
395                     syncTransportListeners.elementAt(i)).
396                         sendDataBegin(syncTransportEvent);
397             } else if (syncTransportEvent.getType() ==
398                         SyncTransportEvent.SEND_DATA_END) {
399                 ((SyncTransportListener)
400                     syncTransportListeners.elementAt(i)).
401                         sendDataEnd(syncTransportEvent);
402             } else if (syncTransportEvent.getType() ==
403                         SyncTransportEvent.RECEIVE_DATA_BEGIN) {
404                 ((SyncTransportListener)
405                     syncTransportListeners.elementAt(i)).
406                         receiveDataBegin(syncTransportEvent);
407             } else if (syncTransportEvent.getType() ==
408                         SyncTransportEvent.DATA_RECEIVED) {
409                 ((SyncTransportListener)
410                     syncTransportListeners.elementAt(i)).
411                         dataReceived(syncTransportEvent);
412             } else if (syncTransportEvent.getType() ==
413                     SyncTransportEvent.RECEIVE_DATA_END) {
414                 ((SyncTransportListener)
415                     syncTransportListeners.elementAt(i)).
416                         receiveDataEnd(syncTransportEvent);
417             }
418
419         }
420
421     }
422
423 }
Popular Tags