KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > quercus > lib > curl > CurlResource


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Nam Nguyen
28  */

29
30 package com.caucho.quercus.lib.curl;
31
32 import com.caucho.quercus.QuercusModuleException;
33 import com.caucho.quercus.env.*;
34 import com.caucho.quercus.lib.file.BinaryInput;
35 import com.caucho.quercus.lib.file.BinaryOutput;
36 import com.caucho.quercus.lib.file.FileModule;
37 import com.caucho.util.L10N;
38 import com.caucho.vfs.Path;
39 import com.caucho.vfs.WriteStream;
40
41 import java.io.IOException JavaDoc;
42 import java.net.HttpURLConnection JavaDoc;
43 import java.util.HashMap JavaDoc;
44 import java.util.Map JavaDoc;
45 import java.util.logging.Logger JavaDoc;
46
47 public class CurlResource
48 {
49   private static final Logger JavaDoc log
50     = Logger.getLogger(CurlResource.class.getName());
51   private static final L10N L = new L10N(CurlResource.class);
52
53   private String JavaDoc _requestMethod = "GET";
54   private int _responseCode;
55
56   private String JavaDoc _URL;
57   private int _port = -1;
58
59   private String JavaDoc _username;
60   private String JavaDoc _password;
61
62   private boolean _isProxying = false;
63   private String JavaDoc _proxyUsername;
64   private String JavaDoc _proxyPassword;
65   private String JavaDoc _proxyURL;
66   private String JavaDoc _proxyType = "HTTP";
67   private int _proxyPort = -1;
68
69   private boolean _isFollowingRedirects = true;
70   private boolean _isReturningBody = true;
71   private boolean _isReturningData = false;
72   private boolean _isReturningHeader = false;
73
74   private boolean _ifModifiedSince = true;
75   private String JavaDoc _modifiedTime;
76
77   private int _errorCode = CurlModule.CURLE_OK;
78   private String JavaDoc _error = "";
79   private boolean _failOnError = false;
80   private boolean _isVerbose = false;
81
82   private int _readTimeout = -1;
83   private int _connectTimeout = -1;
84
85   private HashMap JavaDoc<String JavaDoc,String JavaDoc> _requestProperties
86     = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
87
88   private StringValue _header;
89   private StringValue _body;
90   private BinaryValue _postBody;
91
92   private String JavaDoc _contentType;
93   private int _contentLength;
94
95   private String JavaDoc _cookie;
96   private String JavaDoc _cookieFilename;
97
98   private BinaryOutput _outputFile;
99   private BinaryOutput _outputHeaderFile;
100   private BinaryInput _uploadFile;
101   private int _uploadFileSize;
102
103   private Callback _headerFunction;
104   private Callback _passwordFunction;
105   private Callback _readFunction;
106   private Callback _writeFunction;
107
108   public CurlResource()
109   {
110   }
111
112   /**
113    * Returns body of last transfer.
114    */

115   public Value getBody()
116   {
117     return _body;
118   }
119
120   /**
121    * Sets the body of the last request.
122    */

123   public void setBody(StringValue body)
124   {
125     _body = body;
126   }
127
128   /**
129    * Returns the max time until timeout while establishing a connection.
130    */

131   public int getConnectTimeout()
132   {
133     return _connectTimeout;
134   }
135
136   /**
137    * Sets the max time until timeout while establishing a connection.
138    */

139   public void setConnectTimeout(int timeout)
140   {
141     _connectTimeout = timeout;
142   }
143
144   /**
145    * Returns the length of the body from the last request.
146    */

147   public int getContentLength()
148   {
149     return _contentLength;
150   }
151
152   /**
153    * Sets the length of the body from the last request.
154    */

155   public void setContentLength(int length)
156   {
157     _contentLength = length;
158   }
159
160   /**
161    * Returns the "Content-Type" header from the last request.
162    */

163   public String JavaDoc getContentType()
164   {
165     return _contentType;
166   }
167
168   /**
169    * Sets the "Content-Type" from the last request.
170    */

171   public void setContentType(String JavaDoc type)
172   {
173     _contentType = type;
174   }
175
176   /**
177    * Sets the "Set-Cookie" request property.
178    */

179   public void setCookie(String JavaDoc cookie)
180   {
181     _cookie = cookie;
182   }
183
184   /**
185    * Sets the filename to save the cookies from the last request.
186    */

187   public void setCookieFilename(String JavaDoc filename)
188   {
189     _cookieFilename = filename;
190   }
191
192   /**
193    * Returns the error string from the last request.
194    */

195   public String JavaDoc getError()
196   {
197     return _error;
198   }
199
200   /**
201    * Sets the error string from the last request.
202    */

203   public void setError(String JavaDoc error)
204   {
205     _error = error;
206   }
207
208   /**
209    * Sets the error code from the last request.
210    */

211   public int getErrorCode()
212   {
213     return _errorCode;
214   }
215
216   /**
217    * Returns the error code from the last request.
218    */

219   public void setErrorCode(int code)
220   {
221     _errorCode = code;
222   }
223
224   /**
225    * Set to true to fail on response codes >= 400.
226    */

227   public void setFailOnError(boolean failOnError)
228   {
229     _failOnError = failOnError;
230   }
231
232   /**
233    * Returns the header from the last request.
234    */

235   public Value getHeader()
236   {
237     return _header;
238   }
239
240   /**
241    * Saves the header that was returned by the server.
242    */

243   public void setHeader(StringValue header)
244   {
245     _header = header;
246   }
247
248   /**
249    *
250    */

251   public void setHeaderFunction(Callback callback)
252   {
253     _headerFunction = callback;
254   }
255
256   /**
257    * Set to true to set the If-Modified-Since property.
258    * Time to use is set with setModifiedTime().
259    */

260   public void setIfModifiedSince(boolean option)
261   {
262     _ifModifiedSince = option;
263   }
264
265   /**
266    * Returns true if automatically following redirects.
267    */

268   public boolean getIsFollowingRedirects()
269   {
270     return _isFollowingRedirects;
271   }
272
273   /**
274    * Set to true to automatically follow redirects.
275    */

276   public void setIsFollowingRedirects(boolean followRedirects)
277   {
278     _isFollowingRedirects = followRedirects;
279   }
280
281   /**
282    * Returns true if a proxy is to be used.
283    */

284   public boolean getIsProxying()
285   {
286     return _isProxying;
287   }
288
289   /**
290    * Set to true to proxy request.
291    */

292   public void setIsProxying(boolean proxy)
293   {
294     _isProxying = proxy;
295   }
296
297   /**
298    * Set to true to return body for this request.
299    */

300   public void setIsReturningBody(boolean returnBody)
301   {
302     _isReturningBody = returnBody;
303   }
304
305   /**
306    * Set to true to return data instead of to stdout.
307    */

308   public void setIsReturningData(boolean returnData)
309   {
310     _isReturningData = returnData;
311   }
312
313   /**
314    * Set to true to return the body from this request.
315    */

316   public void setIsReturningHeader(boolean returnHeader)
317   {
318     _isReturningHeader = returnHeader;
319   }
320
321   /**
322    * Returns the verbosity of this library.
323    */

324   public boolean getIsVerbose()
325   {
326     return _isVerbose;
327   }
328
329   /**
330    * Sets the verbosity of this library.
331    */

332   public void setIsVerbose(boolean verbose)
333   {
334     _isVerbose = verbose;
335   }
336
337   /**
338    * Sets the modified time request property.
339    */

340   public void setModifiedTime(String JavaDoc time)
341   {
342     _modifiedTime = time;
343   }
344
345   /**
346    * Sets the file to save the data to save from a request.
347    */

348   public void setOutputFile(BinaryOutput file)
349   {
350     _outputFile = file;
351   }
352
353   /**
354    * Sets the file to save the header from a request.
355    */

356   public void setOutputHeaderFile(BinaryOutput file)
357   {
358     _outputHeaderFile = file;
359   }
360
361   /**
362    * Returns the password to use for authentication.
363    */

364   public String JavaDoc getPassword()
365   {
366     return _password;
367   }
368
369   /**
370    * Sets the password to use for authentication.
371    */

372   public void setPassword(String JavaDoc pwd)
373   {
374     _password = pwd;
375   }
376
377   /**
378    *
379    */

380   public void setPasswordFunction(Callback callback)
381   {
382     _passwordFunction = callback;
383   }
384
385   /**
386    * Returns the port to use for this request.
387    */

388   public int getPort()
389   {
390     return _port;
391   }
392
393   /**
394    * Sets the port to use for this request.
395    */

396   public void setPort(int port)
397   {
398     _port = port;
399   }
400
401   /**
402    * Sets the body to POST to the server.
403    */

404   public BinaryValue getPostBody()
405   {
406     return _postBody;
407   }
408
409   /**
410    * Sets the body to POST to the server.
411    */

412   public void setPostBody(BinaryValue body)
413   {
414     _postBody = body;
415   }
416
417   /**
418    * Returns the password to use for proxy authentication.
419    */

420   public String JavaDoc getProxyPassword()
421   {
422     return _proxyPassword;
423   }
424
425   /**
426    * Sets the password to use for proxy authentication.
427    */

428   public void setProxyPassword(String JavaDoc pass)
429   {
430     _proxyPassword = pass;
431   }
432
433   /**
434    * Returns the port to use for the proxy.
435    */

436   public int getProxyPort()
437   {
438     return _proxyPort;
439   }
440
441   /**
442    * Sets the port to use for the proxy.
443    */

444   public void setProxyPort(int port)
445   {
446     _proxyPort = port;
447   }
448
449   /**
450    * Returns of type of the proxy (Http or SOCKS).
451    */

452   public String JavaDoc getProxyType()
453   {
454     return _proxyType;
455   }
456
457   /**
458    * Sets the type of the proxy (Http or SOCKS).
459    */

460   public void setProxyType(String JavaDoc type)
461   {
462     _proxyType = type;
463   }
464
465   /**
466    * Returns the URL of the proxy.
467    */

468   public String JavaDoc getProxyURL()
469   {
470     return _proxyURL;
471   }
472
473   /**
474    * Sets the URL of the proxy.
475    */

476   public void setProxyURL(String JavaDoc proxy)
477   {
478     _proxyURL = proxy;
479   }
480
481   /**
482    * Returns the username to use for proxy authentication.
483    */

484   public String JavaDoc getProxyUsername()
485   {
486     return _proxyUsername;
487   }
488
489   /**
490    * Sets the username to use for proxy authentication.
491    */

492   public void setProxyUsername(String JavaDoc user)
493   {
494     _proxyUsername = user;
495   }
496
497   /**
498    *
499    */

500   public void setReadFunction(Callback callback)
501   {
502     _readFunction = callback;
503   }
504
505   /**
506    * Returns the max time until timeout while reading body.
507    */

508   public int getReadTimeout()
509   {
510     return _readTimeout;
511   }
512
513   /**
514    * Sets the max time until timeout while reading body.
515    */

516   public void setReadTimeout(int timeout)
517   {
518     _readTimeout = timeout;
519   }
520
521   /**
522    * Returns the current request method.
523    */

524   public String JavaDoc getRequestMethod()
525   {
526     return _requestMethod;
527   }
528
529   /**
530    * Sets the request method to use for this request.
531    */

532   public void setRequestMethod(String JavaDoc method)
533   {
534     _requestMethod = method;
535   }
536
537   /**
538    * Returns a map of all the request properties.
539    */

540   public HashMap JavaDoc<String JavaDoc,String JavaDoc> getRequestPropertiesMap()
541   {
542     return _requestProperties;
543   }
544
545   /**
546    * Returns all the request properties as a String.
547    */

548   public Value getRequestProperties()
549   {
550     BinaryBuilderValue bb = new BinaryBuilderValue();
551
552     for (Map.Entry JavaDoc<String JavaDoc,String JavaDoc> entry: _requestProperties.entrySet()) {
553       bb.appendBytes(entry.getKey());
554       bb.appendBytes(": ");
555       bb.appendBytes(entry.getValue());
556       bb.appendBytes("\r\n");
557     }
558
559     bb.appendBytes("\r\n");
560
561     return bb;
562   }
563
564   /**
565    * Sets a request property to use for this request.
566    */

567   public void setRequestProperty(String JavaDoc key, String JavaDoc value)
568   {
569     _requestProperties.put(key, value);
570   }
571
572   /**
573    * Returns the response code for the last request.
574    */

575   public int getResponseCode()
576   {
577     return _responseCode;
578   }
579
580   /**
581    * Sets the response code for the last request.
582    */

583   public void setResponseCode(int code)
584   {
585     _responseCode = code;
586   }
587
588   /**
589    * Returns handle of file to upload.
590    */

591   public BinaryInput getUploadFile()
592   {
593     return _uploadFile;
594   }
595
596   /**
597    * Sets handle of file to upload.
598    */

599   public void setUploadFile(BinaryInput file)
600   {
601     _uploadFile = file;
602   }
603
604   /**
605    * Returns size of file to upload.
606    */

607   public int getUploadFileSize()
608   {
609     return _uploadFileSize;
610   }
611
612   /**
613    * Sets size of file to upload.
614    */

615   public void setUploadFileSize(int size)
616   {
617     _uploadFileSize = size;
618   }
619
620   /**
621    * Gets the URL to use for this request.
622    */

623   public String JavaDoc getURL()
624   {
625     return _URL;
626   }
627
628   /**
629    * Sets the URL to use for this request.
630    */

631   public void setURL(String JavaDoc url)
632   {
633     _URL = url;
634   }
635
636   /**
637    * Gets the username to use for authentication.
638    */

639   public String JavaDoc getUsername()
640   {
641     return _username;
642   }
643
644   /**
645    * Sets the username to use for authentication.
646    */

647   public void setUsername(String JavaDoc user)
648   {
649     _username = user;
650   }
651
652   /**
653    *
654    */

655   public void setWriteFunction(Callback callback)
656   {
657     _writeFunction = callback;
658   }
659
660   /**
661    * Remove a request property.
662    */

663   public void removeRequestProperty(String JavaDoc key)
664   {
665     _requestProperties.remove(key);
666   }
667
668
669   /**
670    * Finalizes the request properties for this connection.
671    */

672   private void init()
673   {
674     _error = null;
675     _errorCode = CurlModule.CURLE_OK;
676
677     if (_modifiedTime != null) {
678       if (_ifModifiedSince) {
679         removeRequestProperty("If-Unmodified-Since");
680         setRequestProperty("If-Modified-Since", _modifiedTime);
681       }
682       else {
683         removeRequestProperty("If-Modified-Since");
684         setRequestProperty("If-Unmodified-Since", _modifiedTime);
685       }
686     }
687
688     if (_cookie != null)
689       setRequestProperty("Cookie", _cookie);
690     else
691       removeRequestProperty("Cookie");
692   }
693
694   /**
695    * Executes this request.
696    */

697   public Value execute(Env env)
698   {
699     init();
700
701     HttpRequest httpRequest = HttpRequest.getRequest(this);
702
703     env.addClose(httpRequest);
704
705     httpRequest.execute(env);
706
707     if (hasError())
708       return BooleanValue.FALSE;
709
710     if (_cookie != null && _cookieFilename != null)
711       saveCookie(env);
712
713     return getReturnValue(env);
714   }
715
716   /**
717    * Returns headers and/or body of the last request.
718    */

719   private Value getReturnValue(Env env)
720   {
721     StringValue data;
722
723     if (_responseCode == HttpURLConnection.HTTP_NOT_MODIFIED ||
724         _responseCode == HttpURLConnection.HTTP_PRECON_FAILED ||
725         (_failOnError && _responseCode >= 400)) {
726       if (_isReturningHeader)
727         data = _header;
728       else
729         return BooleanValue.TRUE;
730     }
731     else {
732       BinaryBuilderValue bb = new BinaryBuilderValue();
733
734       if (_isReturningHeader)
735         _header.appendTo(bb);
736
737       if (_isReturningBody)
738         _body.appendTo(bb);
739
740       data = bb;
741     }
742
743     if (_isReturningData)
744       return data;
745
746     if (_outputHeaderFile != null) {
747       FileModule.fwrite(env,
748                         _outputHeaderFile,
749                         _header.toInputStream(),
750                         Integer.MAX_VALUE);
751     }
752
753     if (_outputFile != null) {
754       FileModule.fwrite(env,
755                         _outputFile,
756                         data.toInputStream(),
757                         Integer.MAX_VALUE);
758
759     }
760     else {
761       env.print(data);
762     }
763
764     return BooleanValue.TRUE;
765   }
766
767   /**
768    * Save the cookies from the last request.
769    */

770   private void saveCookie(Env env)
771   {
772     WriteStream out = null;
773
774     try {
775       Path path = env.getPwd().lookup(_cookieFilename);
776
777       out = path.openWrite();
778
779       int len = _cookie.length();
780
781       for (int i = 0; i < len; i++) {
782         out.write((byte)_cookie.charAt(i));
783       }
784     }
785     catch (IOException JavaDoc e) {
786       throw new QuercusModuleException(e);
787     }
788     finally {
789       try {
790         if (out != null)
791           out.close();
792       }
793       catch (IOException JavaDoc e) {}
794     }
795   }
796
797   /**
798    *
799    */

800   public void close()
801   {
802   }
803
804   /**
805    * Returns true if an error occuring during the last operation.
806    */

807   protected boolean hasError()
808   {
809     return _errorCode != CurlModule.CURLE_OK;
810   }
811
812   /**
813    * Returns a copy of this resource.
814    */

815   public CurlResource clone()
816   {
817     CurlResource curl = new CurlResource();
818
819     curl.setBody(_body);
820     curl.setConnectTimeout(_connectTimeout);
821     curl.setContentLength(_contentLength);
822     curl.setContentType(_contentType);
823     curl.setCookie(_cookie);
824     curl.setCookieFilename(_cookieFilename);
825     curl.setError(_error);
826     curl.setErrorCode(_errorCode);
827     curl.setFailOnError(_failOnError);
828     curl.setHeaderFunction(_headerFunction);
829     curl.setHeader(_header);
830     curl.setIsFollowingRedirects(_isFollowingRedirects);
831     curl.setIfModifiedSince(_ifModifiedSince);
832     curl.setIsProxying(_isProxying);
833     curl.setIsReturningBody(_isReturningBody);
834     curl.setIsReturningData(_isReturningData);
835     curl.setIsReturningHeader(_isReturningHeader);
836     curl.setIsVerbose(_isVerbose);
837     curl.setModifiedTime(_modifiedTime);
838     curl.setOutputFile(_outputFile);
839     curl.setOutputHeaderFile(_outputHeaderFile);
840     curl.setPassword(_password);
841     curl.setPasswordFunction(_passwordFunction);
842     curl.setPort(_port);
843     curl.setPostBody(_postBody);
844     curl.setProxyPassword(_proxyPassword);
845     curl.setProxyPort(_proxyPort);
846     curl.setProxyType(_proxyType);
847     curl.setProxyURL(_proxyURL);
848     curl.setProxyUsername(_proxyUsername);
849     curl.setReadFunction(_readFunction);
850     curl.setReadTimeout(_readTimeout);
851     curl.setRequestMethod(_requestMethod);
852
853     for (Map.Entry JavaDoc<String JavaDoc,String JavaDoc> entry: _requestProperties.entrySet()) {
854       curl.setRequestProperty(entry.getKey(), entry.getValue());
855     }
856
857     curl.setResponseCode(_responseCode);
858     curl.setUploadFile(_uploadFile);
859     curl.setUploadFileSize(_uploadFileSize);
860     curl.setURL(_URL);
861     curl.setUsername(_username);
862     curl.setWriteFunction(_writeFunction);
863
864     return curl;
865   }
866
867   public String JavaDoc toString()
868   {
869     return "CurlResource[" + _requestMethod + "]";
870   }
871
872 }
873
Popular Tags