KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > components > source > URLSource


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

16 package org.apache.cocoon.components.source;
17
18 import org.apache.avalon.framework.component.ComponentManager;
19
20 import org.apache.cocoon.ProcessingException;
21 import org.apache.cocoon.ResourceNotFoundException;
22
23 import org.apache.excalibur.source.SourceParameters;
24 import org.apache.excalibur.source.SourceUtil;
25
26 import java.io.File JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileNotFoundException JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.lang.reflect.Method JavaDoc;
32 import java.net.HttpURLConnection JavaDoc;
33 import java.net.JarURLConnection JavaDoc;
34 import java.net.URL JavaDoc;
35 import java.net.URLConnection JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.jar.JarEntry JavaDoc;
38
39 /**
40  * Description of a source which is described by an URL.
41  *
42  * @deprecated by the Avalon Exalibur Source Resolving
43  * @author <a HREF="mailto:cziegeler@apache.org">Carsten Ziegeler</a>
44  * @version CVS $Id: URLSource.java 30932 2004-07-29 17:35:38Z vgritsenko $
45  */

46 public class URLSource extends AbstractStreamSource {
47
48     /** Identifier for file urls */
49     private final String JavaDoc FILE = "file:";
50
51     /** The last modification date or 0 */
52     private long lastModificationDate;
53
54     /** The content length */
55     private long contentLength;
56
57     /** Is the content html or xml? */
58     private boolean isHTMLContent = false;
59
60     /** The system id */
61     private String JavaDoc systemId;
62
63     /** The URL of the source */
64     private URL JavaDoc url;
65
66     /** The connection for a real URL */
67     private URLConnection JavaDoc connection;
68
69     /** Is this a file or a "real" URL */
70     private boolean isFile;
71
72     /** Are we initialized? */
73     private boolean gotInfos;
74
75     /** The <code>SourceParameters</code> for post */
76     private SourceParameters postParameters;
77
78     /**
79      * Construct a new object
80      */

81     public URLSource(URL JavaDoc url, ComponentManager manager)
82     throws IOException JavaDoc {
83         super(manager);
84         this.systemId = url.toExternalForm();
85         this.isFile = systemId.startsWith(FILE);
86         if (this.isFile == true) {
87             if (systemId.endsWith(".htm") || systemId.endsWith(".html")) {
88                 this.isHTMLContent = true;
89             }
90         }
91         this.url = url;
92         this.gotInfos = false;
93     }
94
95     protected boolean isHTMLContent() {
96         return this.isHTMLContent;
97     }
98
99     /**
100      * Get the last modification date and content length of the source.
101      * Any exceptions are ignored.
102      */

103     private void getInfos() {
104         if (!this.gotInfos) {
105             if (this.isFile) {
106                 File JavaDoc file = new File JavaDoc(systemId.substring(FILE.length()));
107                 this.lastModificationDate = file.lastModified();
108                 this.contentLength = file.length();
109             } else {
110                 if (this.postParameters == null) {
111                     try {
112                         if (this.connection == null) {
113                             this.connection = this.url.openConnection();
114                             String JavaDoc userInfo = this.getUserInfo();
115                             if (this.url.getProtocol().startsWith("http") && userInfo != null) {
116                                 this.connection.setRequestProperty("Authorization","Basic "+SourceUtil.encodeBASE64(userInfo));
117                             }
118                         }
119                         if(this.connection instanceof JarURLConnection JavaDoc) {
120                             JarEntry JavaDoc entry = ((JarURLConnection JavaDoc)this.connection).getJarEntry();
121                             this.lastModificationDate = entry.getTime();
122                         } else {
123                             this.lastModificationDate = this.connection.getLastModified();
124                         }
125                         this.contentLength = this.connection.getContentLength();
126                     } catch (IOException JavaDoc ignore) {
127                         this.lastModificationDate = 0;
128                         this.contentLength = -1;
129                     }
130                 } else {
131                         // do not open connection when using post!
132
this.lastModificationDate = 0;
133                         this.contentLength = -1;
134                 }
135             }
136             this.gotInfos = true;
137         }
138     }
139
140     /**
141      * Get the last modification date of the source or 0 if it
142      * is not possible to determine the date.
143      */

144     public long getLastModified() {
145         this.getInfos();
146         return this.lastModificationDate;
147     }
148
149     /**
150      * Get the content length of the source or -1 if it
151      * is not possible to determine the length.
152      */

153     public long getContentLength() {
154         this.getInfos();
155         return this.contentLength;
156     }
157
158     /**
159      * Return an <code>InputStream</code> object to read from the source.
160      *
161      * @throws ResourceNotFoundException if file not found or
162      * HTTP location does not exist.
163      * @throws IOException if I/O error occured.
164      */

165     public InputStream JavaDoc getInputStream()
166     throws IOException JavaDoc, ProcessingException {
167         this.getInfos();
168         try {
169             InputStream JavaDoc input = null;
170             if ( this.isFile ) {
171                 input = new FileInputStream JavaDoc(this.systemId.substring(FILE.length()));
172             } else {
173                 if (this.connection == null) {
174                     this.connection = this.url.openConnection();
175                     /* The following requires a jdk 1.3 */
176                     String JavaDoc userInfo = this.getUserInfo();
177                     if (this.url.getProtocol().startsWith("http") && userInfo != null) {
178                         this.connection.setRequestProperty("Authorization","Basic "+SourceUtil.encodeBASE64(userInfo));
179                     }
180                     // do a post operation
181
if (this.connection instanceof HttpURLConnection JavaDoc
182                         && this.postParameters != null) {
183                         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(2000);
184                         String JavaDoc key;
185                         Iterator JavaDoc i = postParameters.getParameterNames();
186                         Iterator JavaDoc values;
187                         String JavaDoc value;
188                         boolean first = true;
189                         while ( i.hasNext() ) {
190                             key = (String JavaDoc)i.next();
191                             values = this.postParameters.getParameterValues(key);
192                             while (values.hasNext() == true) {
193                                 value = SourceUtil.encode((String JavaDoc)values.next());
194                                 if (first == false) buffer.append('&');
195                                 first = false;
196                                 buffer.append(key.toString());
197                                 buffer.append('=');
198                                 buffer.append(value);
199                             }
200                         }
201                         HttpURLConnection JavaDoc httpCon = (HttpURLConnection JavaDoc)connection;
202                         httpCon.setDoInput(true);
203
204                         if (buffer.length() > 1) { // only post if we have parameters
205
String JavaDoc postString = buffer.toString();
206                             httpCon.setRequestMethod("POST"); // this is POST
207
httpCon.setDoOutput(true);
208                             httpCon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
209
210                             // A content-length header must be contained in a POST request
211
httpCon.setRequestProperty("Content-length", Integer.toString(postString.length()));
212                             java.io.OutputStream JavaDoc out = new java.io.BufferedOutputStream JavaDoc(httpCon.getOutputStream());
213                             out.write(postString.getBytes());
214                             out.close();
215                         }
216                         if ("text/html".equals(httpCon.getContentType()) == true) {
217                             this.isHTMLContent = true;
218                         }
219                         input = httpCon.getInputStream();
220                         this.connection = null; // make sure a new connection is created next time
221
return input;
222                     }
223                 }
224                 if ("text/html".equals(this.connection.getContentType()) == true) {
225                     this.isHTMLContent = true;
226                 }
227                 input = this.connection.getInputStream();
228                 this.connection = null; // make sure a new connection is created next time
229
}
230             return input;
231         } catch (FileNotFoundException JavaDoc e) {
232             throw new ResourceNotFoundException("Resource not found "
233                                                 + this.systemId, e);
234         }
235     }
236
237     private static boolean checkedURLClass = false;
238     private static boolean urlSupportsGetUserInfo = false;
239     private static Method JavaDoc urlGetUserInfo = null;
240     private static Object JavaDoc[] emptyParams = new Object JavaDoc[0];
241
242     /**
243      * Check if the <code>URL</code> class supports the getUserInfo()
244      * method which is introduced in jdk 1.3
245      */

246     private String JavaDoc getUserInfo() {
247         if (URLSource.checkedURLClass) {
248             if (URLSource.urlSupportsGetUserInfo) {
249                 try {
250                     return (String JavaDoc) URLSource.urlGetUserInfo.invoke(this.url, URLSource.emptyParams);
251                 } catch (Exception JavaDoc e){
252                     // ignore this anyway
253
}
254             }
255             return null;
256         } else {
257             // test if the url class supports the getUserInfo method
258
try {
259                 URLSource.urlGetUserInfo = URL JavaDoc.class.getMethod("getUserInfo", null);
260                 String JavaDoc ui = (String JavaDoc)URLSource.urlGetUserInfo.invoke(this.url, URLSource.emptyParams);
261                 URLSource.checkedURLClass = true;
262                 URLSource.urlSupportsGetUserInfo = true;
263                 return ui;
264             } catch (Exception JavaDoc e){
265             }
266             URLSource.checkedURLClass = true;
267             URLSource.urlSupportsGetUserInfo = false;
268             URLSource.urlGetUserInfo = null;
269             return null;
270         }
271     }
272
273     /**
274      * Return the unique identifer for this source
275      */

276     public String JavaDoc getSystemId() {
277         return this.systemId;
278     }
279
280     /**
281      * Refresh this object and update the last modified date
282      * and content length.
283      */

284     public void refresh() {
285         // reset connection
286
this.connection = null;
287         this.gotInfos = false;
288     }
289
290     public void recycle() {
291         refresh();
292     }
293
294     /**
295      * Set the post parameters
296      */

297     public void setPostParameters(SourceParameters pars) {
298         this.postParameters = pars;
299     }
300
301 }
302
Popular Tags