KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > vfs > VFSRepository


1 /* ========================================================================== *
2  * Copyright (C) 2004-2005 Pier Fumagalli <http://www.betaversion.org/~pier/> *
3  * All rights reserved. *
4  * ========================================================================== *
5  * *
6  * Licensed under the Apache License, Version 2.0 (the "License"). You may *
7  * not use this file except in compliance with the License. You may obtain a *
8  * copy of the License at <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, WITHOUT *
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the *
13  * License for the specific language governing permissions and limitations *
14  * under the License. *
15  * *
16  * ========================================================================== *
17  * *
18  * */

19 /*
20  * SSL-Explorer
21  *
22  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
23  *
24  * This program is free software; you can redistribute it and/or
25  * modify it under the terms of the GNU General Public License
26  * as published by the Free Software Foundation; either version 2 of
27  * the License, or (at your option) any later version.
28  * This program is distributed in the hope that it will be useful,
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31  * GNU General Public License for more details.
32  *
33  * You should have received a copy of the GNU General Public
34  * License along with this program; if not, write to the Free Software
35  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
36  */

37             
38 package com.sslexplorer.vfs;
39
40 import java.io.File JavaDoc;
41 import java.io.IOException JavaDoc;
42 import java.net.URI JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.util.HashSet JavaDoc;
45 import java.util.Iterator JavaDoc;
46 import java.util.List JavaDoc;
47 import java.util.Map JavaDoc;
48 import java.util.Set JavaDoc;
49
50 import javax.servlet.http.HttpSession JavaDoc;
51
52 import org.apache.commons.logging.Log;
53 import org.apache.commons.logging.LogFactory;
54 import org.apache.commons.vfs.FileSystemException;
55 import org.apache.commons.vfs.FileSystemManager;
56 import org.apache.commons.vfs.VFS;
57 import org.apache.commons.vfs.impl.DefaultFileReplicator;
58 import org.apache.commons.vfs.impl.DefaultFileSystemManager;
59
60 import com.sslexplorer.boot.Util;
61 import com.sslexplorer.core.BundleActionMessage;
62 import com.sslexplorer.policyframework.LaunchSession;
63 import com.sslexplorer.policyframework.NoPermissionException;
64 import com.sslexplorer.policyframework.PolicyException;
65 import com.sslexplorer.security.PasswordCredentials;
66 import com.sslexplorer.security.SessionInfo;
67 import com.sslexplorer.vfs.utils.DAVCredentialsCache;
68 import com.sslexplorer.vfs.webdav.DAVBundleActionMessageException;
69 import com.sslexplorer.vfs.webdav.DAVException;
70 import com.sslexplorer.vfs.webdav.DAVListener;
71 import com.sslexplorer.vfs.webdav.DAVUtilities;
72
73 /**
74  * <p>
75  * A simple class representing a {@link File} based WebDAV repository.
76  * </p>
77  *
78  * @author <a HREF="http://www.betaversion.org/~pier/">Pier Fumagalli</a>
79  */

80 public class VFSRepository {
81
82     final static Log log = LogFactory.getLog(VFSRepository.class);
83
84     final static String JavaDoc REPOSITORY_ATTR = "networkPlacesRepository";
85     /**
86      * <p>
87      * The {@link Set} of all configured {@link DAVListener}s.
88      * </p>
89      */

90     private Set JavaDoc<DAVListener> listeners = new HashSet JavaDoc<DAVListener>();
91
92     /**
93      * <p>
94      * The {@link FileSystemManager} used to retrieve resources
95      * </p>
96      */

97     private FileSystemManager fsManager;
98
99     /**
100      * <p>
101      * The {@link VFSStore} implementations being managed by the repository
102      * </p>
103      */

104     private Map JavaDoc<String JavaDoc,VFSStore> stores;
105
106     /** <p>A cache of resources for the life of this transaction */
107     //private Map resourceCache = new HashMap();
108

109     private SessionInfo session;
110     
111     /**
112      * Constructor.
113      *
114      * @param session session
115      * @throws DAVBundleActionMessageException on any error
116      */

117     public VFSRepository(SessionInfo session) throws DAVBundleActionMessageException {
118         
119         this.session = session;
120         try {
121             fsManager = VFS.getManager();
122             ((DefaultFileSystemManager)fsManager).setBaseFile(new File JavaDoc(System.getProperty("user.dir")));
123             
124         } catch (FileSystemException e1) {
125             log.error(e1);
126             throw new DAVBundleActionMessageException(new BundleActionMessage("vfs", "vfs.fsManager.failed", e1.getMessage()));
127         }
128         
129         try {
130             stores = VFSProviderManager.getInstance().createStores(this);
131         } catch (Exception JavaDoc e) {
132             log.error(e);
133             throw new DAVBundleActionMessageException(new BundleActionMessage("vfs", "vfs.store.creation.failed"));
134         }
135     }
136     
137     /**
138      * Get the session the repository was created under.
139      *
140      * @return session
141      */

142     public SessionInfo getSession() {
143         return session;
144     }
145
146     /**
147      * Return the {@link VFSResource} for the path.
148      *
149      * @param launchSession launch session
150      * @param path an absolute or relative {@link String} identifying the
151      * resource.
152      * @param requestCredentials request credentials
153      * @return a <b>non-null</b> {@link VFSResource} instance.
154      * @throws IOException
155      * @throws DAVBundleActionMessageException
156      * @throws NoPermissionException
157      * @throws PolicyException
158      */

159     public VFSResource getResource(LaunchSession launchSession, String JavaDoc path, PasswordCredentials requestCredentials/*, DAVTransaction transaction*/) throws DAVBundleActionMessageException, IOException JavaDoc, PolicyException, NoPermissionException {
160
161         if (path == null) {
162             log.error("Cannot list store root.");
163             throw new DAVBundleActionMessageException(new BundleActionMessage("vfs", "vfs.store.root", path));
164         }
165         
166         if(launchSession == null) {
167             throw new IOException JavaDoc("Must have launch session.");
168         }
169         
170         path = DAVUtilities.stripLeadingSlash(path);
171         if(path.startsWith("fs")) {
172             path= DAVUtilities.stripLeadingSlash(path.substring(2));
173         }
174
175         String JavaDoc storeName = path;
176         VFSStore store;
177         String JavaDoc mountName = null;
178         VFSMount mount;
179
180         // Extract the store
181
int idx = path.indexOf('/');
182         if (idx != -1) {
183             storeName = storeName.substring(0, idx);
184             path = path.substring(idx + 1);
185         } else {
186             path = "";
187         }
188
189         if (storeName.equals("")) {
190             return getRepositoryResource();
191         } else {
192             store = (VFSStore) this.getStore(storeName);
193             if (store == null) {
194                 log.error("No store named \"" + storeName + "\".");
195                 throw new DAVException(404, "No store named \"" + storeName + "\".");
196             }
197         }
198
199         // Extract the mount
200
mountName = path;
201         idx = path.indexOf('/', 1);
202         if (idx != -1) {
203             mountName = mountName.substring(0, idx);
204             path = path.substring(idx + 1);
205         } else {
206             path = "";
207         }
208         if (mountName.length() == 0) {
209             return store.getStoreResource(/*transaction*/);
210         }
211         
212         // Check the launch session is valid
213
if(launchSession.isTracked())
214             launchSession.checkAccessRights(null, this.session);
215
216         //
217
try {
218             mount = store.getMountFromString(Util.urlDecode(mountName), launchSession);
219         }
220         catch(Exception JavaDoc e) {
221             log.error("Failed to get mount.", e);
222             mount = null;
223         }
224         if (mount == null || mount.equals("")) {
225             log.error("No mount named \"" + mountName + "\" for store \"" + storeName + "\".");
226             throw new DAVException(404, "No mount named \"" + mountName + "\" for store \"" + storeName + "\".");
227         }
228
229         
230         path = DAVUtilities.stripTrailingSlash(path);
231
232
233         return mount.getResource(path, requestCredentials);
234     }
235
236     /**
237      * Add a new {@link DAVListener} to the list of instances notified by this
238      * {@link VFSRepository}.
239      *
240      * @param listener listener to add
241      */

242     public void addListener(DAVListener listener) {
243         if (listener != null)
244             this.listeners.add(listener);
245     }
246
247     /**
248      * Remove a {@link DAVListener} from the list of instances notified by this
249      * {@link VFSRepository}.
250      *
251      * @param listener listener to remove
252      */

253     public void removeListener(DAVListener listener) {
254         if (listener != null)
255             this.listeners.remove(listener);
256     }
257
258     /**
259      * Notify all configured {@link DAVListener}s of an event.
260      *
261      * @param resource resource
262      * @param event event code
263      */

264     public void notify(VFSResource resource, int event) {
265         if (resource == null)
266             throw new NullPointerException JavaDoc("Null resource");
267         if (resource.getMount().getStore().getRepository() != this)
268             throw new IllegalArgumentException JavaDoc("Invalid resource");
269
270         Iterator JavaDoc iterator = this.listeners.iterator();
271         while (iterator.hasNext())
272             try {
273                 ((DAVListener) iterator.next()).notify(resource, event);
274             } catch (RuntimeException JavaDoc exception) {
275                 // Swallow any RuntimeException thrown by listeners.
276
}
277     }
278
279     /**
280      * Get the <i>Commons VFS</i> {@link FileSystemManager} instance.
281      *
282      * @return file system manager
283      */

284     public FileSystemManager getFileSystemManager() {
285         return fsManager;
286     }
287
288     /**
289      * Get a resource that represents the entire repository.
290      *
291      * @return resource repository
292      */

293     public VFSResource getRepositoryResource() {
294         try {
295             return new RepositoryResource(new URI JavaDoc(""));
296         }
297         catch(Exception JavaDoc e) {
298             // shouldn't happen
299
return null;
300         }
301     }
302
303     /**
304      * Get the object that caches used credentials.
305      *
306      * @return credentials cache
307      */

308     public DAVCredentialsCache getCredentialsCache(){
309         // get the credentials cashe
310
DAVCredentialsCache credentialsCashe = (DAVCredentialsCache) session.getHttpSession().getAttribute("CredentialsCashe");
311         // if there is not 1 make 1 then get the cashe
312
if (credentialsCashe == null){
313             session.getHttpSession().setAttribute("CredentialsCashe", new DAVCredentialsCache());
314             credentialsCashe = (DAVCredentialsCache) session.getHttpSession().getAttribute("CredentialsCashe");
315         }
316         return credentialsCashe;
317     }
318     
319     /**
320      * Create a {@link VFSRepository} repository for the given session. The
321      * repository will be placed in the users session and used for all VFS
322      * operations.
323      *
324      * @param session
325      * @return VFS repository
326      * @throws DAVBundleActionMessageException
327      * @throws Exception
328      */

329     public static VFSRepository getRepository(SessionInfo session) throws DAVBundleActionMessageException, Exception JavaDoc {
330         VFSRepository repository = (VFSRepository) session.getHttpSession().getAttribute(REPOSITORY_ATTR);
331         if (repository == null) {
332             repository = new VFSRepository(session);
333             
334             session.getHttpSession().setAttribute(REPOSITORY_ATTR, repository);
335             if (log.isInfoEnabled())
336                 log.info("Initialized repository");
337         }
338         return repository;
339     }
340     
341     /**
342      * Remove a {@link VFSRepository} repository from the given session.
343      * @param session
344      */

345     public static void removeRepository(SessionInfo session) {
346         HttpSession JavaDoc httpSession = session.getHttpSession();
347         if(httpSession != null) {
348             httpSession.removeAttribute(REPOSITORY_ATTR);
349             if (log.isInfoEnabled())
350                 log.info("Removed repository");
351         }
352     }
353     
354  
355     /**
356      * Get a store that will handle a given a scheme.
357      *
358      * @param scheme
359      * @return store
360      */

361     public VFSStore getStore(String JavaDoc scheme) {
362         for(Iterator JavaDoc i = stores.values().iterator(); i.hasNext(); ) {
363             VFSStore s = (VFSStore)i.next();
364             if(s.getProvider().willHandle(scheme)) {
365                 return s;
366             }
367         }
368         return null;
369     }
370     
371     class RepositoryResource extends AbstractVFSResource {
372
373         RepositoryResource(URI JavaDoc relativeUri) {
374             super(new LaunchSession(getSession()),
375                 relativeUri, true, "", null, VFSRepository.this);
376         }
377
378         public Iterator JavaDoc getChildren() {
379             List JavaDoc<VFSResource> l = new ArrayList JavaDoc<VFSResource>();
380             for(Iterator JavaDoc i = stores.values().iterator(); i.hasNext(); ) {
381                 l.add(((VFSStore)i.next()).getStoreResource());
382             }
383             return l.iterator();
384         }
385         
386     }
387 }
Popular Tags