KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > components > SourceRepository


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;
17
18 import java.io.IOException JavaDoc;
19 import java.io.InputStream JavaDoc;
20 import java.io.OutputStream JavaDoc;
21 import java.net.MalformedURLException JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Collection JavaDoc;
24 import java.util.Enumeration JavaDoc;
25 import java.util.Iterator JavaDoc;
26
27 import org.apache.avalon.framework.component.ComponentException;
28 import org.apache.avalon.framework.component.ComponentManager;
29 import org.apache.cocoon.environment.Request;
30 import org.apache.cocoon.servlet.multipart.Part;
31 import org.apache.excalibur.source.ModifiableSource;
32 import org.apache.excalibur.source.ModifiableTraversableSource;
33 import org.apache.excalibur.source.Source;
34 import org.apache.excalibur.source.SourceException;
35 import org.apache.excalibur.source.SourceResolver;
36 import org.apache.excalibur.source.SourceUtil;
37 import org.apache.excalibur.source.TraversableSource;
38
39 /**
40  * @author stefano
41  * @version CVS $Id: SourceRepository.java 30932 2004-07-29 17:35:38Z vgritsenko $
42  */

43 public class SourceRepository {
44     
45     public static final String JavaDoc FILE_NAME = "document";
46     
47     private static SourceRepository instance;
48     
49     private static ComponentManager manager;
50     
51     private SourceRepository() {
52         manager = CocoonComponentManager.getSitemapComponentManager();
53     }
54     
55     public static SourceRepository getInstance() {
56         if (instance == null) {
57             instance = new SourceRepository();
58         }
59         return instance;
60     }
61
62     private static Source resolve(String JavaDoc uri)
63     throws MalformedURLException JavaDoc, IOException JavaDoc {
64         SourceResolver resolver = null;
65         TraversableSource source;
66         try {
67             resolver = (SourceResolver) manager.lookup(SourceResolver.ROLE);
68             source = (TraversableSource) resolver.resolveURI(uri);
69         } catch (ComponentException ce) {
70             throw new IOException JavaDoc("ComponentException");
71         } finally {
72             manager.release(resolver);
73         }
74         return source;
75     }
76
77     private static TraversableSource getCollection(String JavaDoc colName) {
78         TraversableSource source;
79         try {
80             source = (TraversableSource)resolve(colName);
81         } catch (MalformedURLException JavaDoc e) {
82             throw new RuntimeException JavaDoc("'unable to resolve source: malformed URL");
83         } catch (IOException JavaDoc e) {
84             throw new RuntimeException JavaDoc("'unable to resolve source: IOException");
85         }
86         if (!source.isCollection()) throw new RuntimeException JavaDoc(colName + " is not a collection!");
87         return source;
88     }
89
90     public static void save(Request request, String JavaDoc dirName) throws Exception JavaDoc {
91         TraversableSource collection = getCollection(dirName);
92         ModifiableTraversableSource result;
93         
94         Enumeration JavaDoc params = request.getParameterNames();
95         while (params.hasMoreElements()) {
96             String JavaDoc name = (String JavaDoc) params.nextElement();
97             if (name.indexOf("..") > -1) throw new Exception JavaDoc("We are under attack!!");
98 //System.out.println("[param] " + name);
99
if (name.startsWith("save:")) {
100                 Part part = (Part) request.get(name);
101                 String JavaDoc code = name.substring(5);
102                 if (!(collection instanceof ModifiableSource)) {
103                     throw new RuntimeException JavaDoc("Cannot modify the given source");
104                 }
105                 result = (ModifiableTraversableSource)resolve(collection.getURI() + "/" + code);
106                 
107                 save(part, result);
108             } else if (name.startsWith("delete:")) {
109                 String JavaDoc value = request.getParameter(name);
110                 if (value.length() > 0) {
111                     String JavaDoc code = name.substring(7);
112                     result = (ModifiableTraversableSource)resolve(collection + "/" + code);
113                     remove(result);
114                 }
115             }
116         }
117     }
118     
119     public static void save(Request request, String JavaDoc param, String JavaDoc dest) throws Exception JavaDoc {
120         Part part = (Part) request.get(param);
121         save(part, (ModifiableTraversableSource)resolve(dest));
122     }
123     
124     public static void save(Part part, ModifiableTraversableSource destination) throws Exception JavaDoc {
125         InputStream JavaDoc in = null;
126         OutputStream JavaDoc out = null;
127         try {
128             in = part.getInputStream();
129             out = destination.getOutputStream();
130             copy(in, out);
131         } finally {
132             if (out != null) {
133                 out.close();
134             }
135             if (in != null) {
136                 in.close();
137             }
138         }
139     }
140     
141     public static OutputStream JavaDoc getOutputStream(String JavaDoc collection) throws IOException JavaDoc {
142         String JavaDoc mainResource = collection + "/" + FILE_NAME + ".xml";
143         String JavaDoc versionedResource = collection + "/" + FILE_NAME + "." + getVersionID(collection) + ".xml";
144         copy(mainResource, versionedResource);
145         return ((ModifiableSource)resolve(mainResource)).getOutputStream();
146     }
147
148     public static void revertFrom(String JavaDoc collection, int version) throws IOException JavaDoc {
149         String JavaDoc mainResource = collection + "/" + FILE_NAME + ".xml";
150         String JavaDoc versionedResource = collection + "/" + FILE_NAME + "." + version + ".xml";
151         copy(versionedResource,mainResource);
152     }
153     
154     /**
155      * Returns the highest version id of the files included in the given
156      * directory.
157      */

158     public static int getVersionID(String JavaDoc colName) {
159         TraversableSource collection = getCollection(colName);
160         int id = 0;
161         Collection JavaDoc contents;
162         try {
163             contents = collection.getChildren();
164         } catch (SourceException se) {
165             throw new RuntimeException JavaDoc("Unable to list contents for collection " + colName);
166         }
167         for (Iterator JavaDoc iter = contents.iterator(); iter.hasNext();) {
168             TraversableSource content = (TraversableSource) iter.next();
169             if (!content.isCollection()) {
170                 try {
171                     int localid = getVersion(content.getName());
172                     if (localid > id) id = localid;
173                 } catch (Exception JavaDoc e) {}
174                                 
175             }
176         }
177         
178         return ++id;
179     }
180
181     public static Object JavaDoc[] getVersions(String JavaDoc colName) {
182         TraversableSource collection = getCollection(colName);
183         ArrayList JavaDoc versions = new ArrayList JavaDoc();
184
185         Collection JavaDoc contents;
186         try {
187             contents = collection.getChildren();
188         } catch (SourceException se) {
189             throw new RuntimeException JavaDoc("Unable to list contents for collection " + colName);
190         }
191
192         for (Iterator JavaDoc iter = contents.iterator(); iter.hasNext();) {
193             TraversableSource content = (TraversableSource) iter.next();
194             if (!content.isCollection()) {
195                  try {
196                      int version = getVersion(content.getName());
197                      if (version > 0) {
198                          versions.add(new Integer JavaDoc(version));
199                      }
200                  } catch (Exception JavaDoc e) {}
201              }
202             
203         }
204
205         return versions.toArray();
206     }
207         
208     /**
209      * Return the version encoded into the name as a numeric subextension of
210      * an .xml extension.
211      *
212      * Example:
213      * anything.123.xml -> 123
214      * document.3.xml -> 3
215      * document.0.xml -> 0
216      * document.xml -> -1
217      * image.0.jpg -> -1
218      */

219     private static int getVersion(String JavaDoc name) {
220         int extIndex = name.lastIndexOf(".xml");
221         if (extIndex > 0) {
222             String JavaDoc nameWithoutExtension = name.substring(0,extIndex);
223             int dotIndex = nameWithoutExtension.lastIndexOf('.');
224             if (dotIndex > 0) {
225                 String JavaDoc localidString = nameWithoutExtension.substring(dotIndex + 1);
226                 return Integer.parseInt(localidString);
227             }
228         }
229         return -1;
230     }
231     
232     public static int getID(String JavaDoc colName) {
233         TraversableSource collection = getCollection(colName);
234
235         int id = 0;
236         Collection JavaDoc contents;
237         try {
238             contents = collection.getChildren();
239         } catch (SourceException se) {
240             throw new RuntimeException JavaDoc("Unable to list contents for collection " + colName);
241         }
242         
243         for (Iterator JavaDoc iter = contents.iterator(); iter.hasNext();) {
244             TraversableSource content = (TraversableSource) iter.next();
245             if (content.isCollection()) {
246                 try {
247                     String JavaDoc name = content.getName();
248                     int localid = Integer.parseInt(name);
249                     if (localid > id) id = localid;
250                 } catch (Exception JavaDoc e) {}
251             }
252         }
253         return ++id;
254     }
255     
256     public static boolean remove(String JavaDoc resourceName) {
257         try {
258             return remove((ModifiableTraversableSource)resolve(resourceName));
259         } catch (MalformedURLException JavaDoc e) {
260             return false;
261         } catch (IOException JavaDoc e) {
262             return false;
263         }
264         
265     }
266     
267     public static boolean remove(ModifiableTraversableSource resource) {
268         boolean success = true;
269         
270         if (resource.isCollection()) {
271             Collection JavaDoc contents;
272             try {
273                 contents = resource.getChildren();
274             } catch (SourceException se) {
275                 throw new RuntimeException JavaDoc("Unable to list contents for collection " + resource);
276             }
277             for (Iterator JavaDoc iter = contents.iterator(); iter.hasNext();) {
278                 ModifiableTraversableSource element = (ModifiableTraversableSource) iter.next();
279                 success = remove(element);
280             }
281                         
282         }
283         try {
284             resource.delete();
285             return success;
286         } catch (SourceException e) {
287             return false;
288         }
289         
290     }
291     
292     public static void copy(String JavaDoc from, String JavaDoc to) throws IOException JavaDoc {
293         copy((ModifiableTraversableSource)resolve(from), (ModifiableTraversableSource)resolve(to));
294     }
295
296     public static void copy(ModifiableTraversableSource from, ModifiableTraversableSource to) throws IOException JavaDoc {
297         
298         if (!from.exists()) {
299             throw new IOException JavaDoc("Cannot find source file/folder");
300         }
301         
302         if (from.isCollection()) {
303             to.makeCollection();
304             Collection JavaDoc contents;
305             try {
306                 contents = from.getChildren();
307             } catch (SourceException se) {
308                 throw new RuntimeException JavaDoc("Unable to list contents for collection " + from);
309             }
310             for (Iterator JavaDoc iter = contents.iterator(); iter.hasNext();) {
311                 ModifiableTraversableSource src = (ModifiableTraversableSource) iter.next();
312                 SourceUtil.copy(src, resolve(to.getURI() + "/" + src.getName()));
313
314             }
315         } else {
316             to = (ModifiableTraversableSource)resolve(to.getURI());
317             InputStream JavaDoc in = null;
318             OutputStream JavaDoc out = null;
319             try {
320                 in = from.getInputStream();
321                 out = to.getOutputStream();
322                 copy(in,out);
323             } finally {
324                 if (out != null) out.close();
325                 if (in != null) in.close();
326             }
327         }
328     }
329     
330     public static void copy(InputStream JavaDoc from, OutputStream JavaDoc to) throws IOException JavaDoc {
331         byte[] buffer = new byte[64 * 1024];
332         int count = 0;
333         do {
334             to.write(buffer, 0, count);
335             count = from.read(buffer, 0, buffer.length);
336         } while (count != -1);
337     }
338        
339 }
340
Popular Tags