KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > components > modules > input > LocateResource


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.modules.input;
17
18 import org.apache.avalon.framework.component.ComponentException;
19 import org.apache.avalon.framework.component.ComponentManager;
20 import org.apache.avalon.framework.component.Composable;
21 import org.apache.avalon.framework.configuration.Configuration;
22 import org.apache.avalon.framework.configuration.ConfigurationException;
23 import org.apache.avalon.framework.thread.ThreadSafe;
24
25 import org.apache.excalibur.source.Source;
26 import org.apache.excalibur.source.SourceResolver;
27
28 import java.util.Collection JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.TreeSet JavaDoc;
32 import java.util.Vector JavaDoc;
33
34 /**
35  * Locate a resource in a resource tree. Any attribute name is interpreted as a
36  * URI with the last part being the resource name unless it ends with a slash.
37  * The URI is checked if the resource exists and the URI is returned. If the
38  * resource does not exist, the URI is shortened until the resource name is found
39  * and the new URI is returned. If no resource with the given name exists, null
40  * is returned.
41  *
42  * <p>A use case is to locate the closest menu file or when moving a site from
43  * a filesystem path == URL system from a httpd to Cocoon and provide similar
44  * functions to .htaccess files.</p>
45  *
46  * <p>Example: for context:/some/path/to/a/file.xml the following URIs
47  * are tested: context:/some/path/to/a/file.xml, context:/some/path/to/file.xml,
48  * context:/some/path/file.xml, context:/some/file.xml, and context:/file.xml.
49  * For the attribute name context:/some/path/foo/ tests context:/some/path/foo/,
50  * context:/some/path/, context:/some/, and context:/ are tested.</p>
51  *
52  * <p>The getAttribute() method will return the URI for the first match while
53  * getAttributeValues() will return an array of all existing paths.
54  * getAttributeNames() will return an Iterator to an empty collection.</p>
55  *
56  * @author <a HREF="mailto:haul@apache.org">Christian Haul</a>
57  * @version CVS $Id: LocateResource.java 178939 2005-05-29 11:07:16Z antonio $
58  */

59 public class LocateResource extends AbstractInputModule implements Composable, ThreadSafe {
60
61     protected static final Collection JavaDoc col = new TreeSet JavaDoc();
62
63     protected ComponentManager manager = null;
64
65     /**
66      * Calculate the minimal length of the URL, that is the position
67      * of the first ":" if a protocol is provided or otherwise 0.
68      * @param name
69      * @return minimal length
70      */

71     protected int calculateMinLen(String JavaDoc name) {
72
73         int minLen = name.indexOf(':');
74         minLen = (minLen == -1 ? 0 : minLen);
75
76         return minLen;
77     }
78
79     /**
80      * Remove one path element from the URL unless minimum length has
81      * been reached.
82      *
83      * @param urlstring
84      * @param minLen
85      * @return shortened URI
86      */

87     protected String JavaDoc shortenURI(String JavaDoc urlstring, int minLen) {
88
89         int idx = urlstring.lastIndexOf('/');
90         idx = (idx <= minLen + 1) ? minLen : idx;
91         urlstring = urlstring.substring(0, idx);
92
93         return urlstring;
94     }
95
96     /**
97      * if the url does not end with a "/", keep the last part in
98      * order to add it later again after traversing up
99      */

100     protected String JavaDoc extractFilename(String JavaDoc urlstring) {
101
102         String JavaDoc filename = "";
103         if (!urlstring.endsWith("/")) {
104             int idx = urlstring.lastIndexOf('/');
105             filename = urlstring.substring(idx);
106         }
107
108         return filename;
109     }
110
111     /**
112      * Locate a resource with the given URL consisting of urlstring + filename.
113      * The filename is appended each time the path is shortened. Returns the first
114      * existing occurance.
115      *
116      * @param urlstring
117      * @param filename
118      * @param minLen
119      * @return urlstring if resource was found, <code>null</code> otherwise
120      */

121     protected String JavaDoc locateResource(String JavaDoc urlstring, String JavaDoc filename, int minLen) {
122         String JavaDoc sourcename = null;
123         Source src = null;
124         SourceResolver resolver = null;
125         boolean found = false;
126         try {
127             resolver =
128                 (SourceResolver) this.manager.lookup(
129                     org.apache.excalibur.source.SourceResolver.ROLE);
130             while (!found && urlstring.length() > minLen) {
131                 sourcename = urlstring + filename;
132                 try {
133                     src = resolver.resolveURI(sourcename);
134                     if (src.exists())
135                         found = true;
136                 } catch (Exception JavaDoc e) {
137                     if (this.getLogger().isWarnEnabled())
138                         this.getLogger().warn("Exception resolving URL " + sourcename, e);
139                 } finally {
140                     resolver.release(src);
141                 }
142                 if (!found) {
143                     urlstring = shortenURI(urlstring, minLen);
144                 }
145             }
146         } catch (ComponentException e1) {
147             if (this.getLogger().isErrorEnabled())
148                 this.getLogger().error("Exception obtaining source resolver ", e1);
149         } finally {
150             if (resolver != null) {
151                 this.manager.release(resolver);
152             }
153         }
154         return (found ? urlstring : null);
155     }
156
157     /**
158      * Set the current <code>ComponentManager</code> instance used by this
159      * <code>Composable</code>.
160      */

161     public void compose(ComponentManager manager) throws ComponentException {
162         this.manager = manager;
163     }
164
165     /* (non-Javadoc)
166      * @see org.apache.cocoon.components.modules.input.InputModule#getAttribute(java.lang.String, org.apache.avalon.framework.configuration.Configuration, java.util.Map)
167      */

168     public Object JavaDoc getAttribute(String JavaDoc name, Configuration modeConf, Map JavaDoc objectModel)
169         throws ConfigurationException {
170
171         String JavaDoc urlstring = name;
172         String JavaDoc filename = extractFilename(urlstring);
173         int minLen = calculateMinLen(name);
174         if (!filename.equals("")) {
175             urlstring = shortenURI(urlstring, minLen);
176         }
177
178         String JavaDoc result = locateResource(urlstring, filename, minLen);
179         result = (result == null? result : result + filename);
180         if (this.getLogger().isDebugEnabled())
181             this.getLogger().debug(
182                 "located " + name + " @ " + result);
183         return result;
184     }
185
186     /* (non-Javadoc)
187      * @see org.apache.cocoon.components.modules.input.InputModule#getAttributeNames(org.apache.avalon.framework.configuration.Configuration, java.util.Map)
188      */

189     public Iterator JavaDoc getAttributeNames(Configuration modeConf, Map JavaDoc objectModel)
190         throws ConfigurationException {
191         // return an iterator to an empty collection
192
return LocateResource.col.iterator();
193     }
194
195     /* (non-Javadoc)
196      * @see org.apache.cocoon.components.modules.input.InputModule#getAttributeValues(java.lang.String, org.apache.avalon.framework.configuration.Configuration, java.util.Map)
197      */

198     public Object JavaDoc[] getAttributeValues(String JavaDoc name, Configuration modeConf, Map JavaDoc objectModel)
199         throws ConfigurationException {
200
201         Vector JavaDoc uris = null;
202         String JavaDoc urlstring = name;
203         String JavaDoc filename = extractFilename(urlstring);
204         int minLen = calculateMinLen(name);
205         if (!filename.equals("")) {
206             urlstring = shortenURI(urlstring, minLen);
207         }
208
209         while (urlstring != null && urlstring.length() > minLen) {
210             urlstring = this.locateResource(urlstring, filename, minLen);
211             if (urlstring != null) {
212                 if (uris == null)
213                     uris = new Vector JavaDoc();
214                 if (this.getLogger().isDebugEnabled())
215                     this.getLogger().debug("-> located " + name + " @ " + urlstring + filename);
216                 uris.add(urlstring + filename);
217                 urlstring = shortenURI(urlstring, minLen);
218             }
219         }
220         return (uris == null ? null : uris.toArray());
221     }
222
223 }
224
Popular Tags