KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.sslexplorer.vfs;
2
3 import java.io.IOException JavaDoc;
4 import java.net.URI JavaDoc;
5 import java.util.ArrayList JavaDoc;
6 import java.util.Date JavaDoc;
7 import java.util.Iterator JavaDoc;
8 import java.util.List JavaDoc;
9
10 import org.apache.commons.logging.Log;
11 import org.apache.commons.logging.LogFactory;
12 import org.apache.commons.vfs.FileObject;
13 import org.apache.commons.vfs.FileType;
14 import org.apache.commons.vfs.NameScope;
15
16 import com.sslexplorer.policyframework.LaunchSession;
17 import com.sslexplorer.security.PasswordCredentials;
18 import com.sslexplorer.vfs.webdav.DAVAuthenticationRequiredException;
19 import com.sslexplorer.vfs.webdav.DAVException;
20 import com.sslexplorer.vfs.webdav.DAVListener;
21 import com.sslexplorer.vfs.webdav.DAVMultiStatus;
22 import com.sslexplorer.vfs.webdav.DAVStatus;
23 import com.sslexplorer.vfs.webdav.DAVUtilities;
24 import com.sslexplorer.vfs.webdav.methods.GET;
25
26 /**
27  * <p>
28  * This class implements {@link com.sslexplorer.vfs.VFSResource} and and
29  * provides axcess to the file system.
30  *
31  * @author James D Robinson
32  *
33  * @mail <a HREF="mailto:james@3sp.com">&lt;james@3sp.com&gt;</a>
34  */

35 public class FileObjectVFSResource implements VFSResource {
36     final static Log log = LogFactory.getLog(VFSResource.class);
37
38     // Private instance variables
39

40     private VFSMount mount = null;
41     private FileObject file = null;
42     
43     // Protected instance variables
44
protected LaunchSession launchSession;
45     protected String JavaDoc relativePath;
46     protected VFSResource parent;
47     protected VFSRepository repository;
48     protected PasswordCredentials requestCredentials;
49
50     /**
51      * @param launchSession launch session
52      * @param mount The Mount acociated with this resource.
53      * @param parent parent
54      * @param relativePath path relative to root of mount
55      * @param repository repository
56      * @param requestCredentials request credentials
57      * @throws IOException on any error
58      */

59     public FileObjectVFSResource(LaunchSession launchSession, VFSMount mount, VFSResource parent, String JavaDoc relativePath,
60                                     VFSRepository repository, PasswordCredentials requestCredentials)
61         throws IOException JavaDoc {
62         if (mount == null)
63             throw new NullPointerException JavaDoc("Null mount");
64         this.launchSession = launchSession;
65         this.mount = mount;
66         this.parent = parent;
67         this.relativePath = relativePath;
68         this.repository = repository;
69         this.requestCredentials = requestCredentials;
70
71         // get the parent now if possible
72
if (this.parent == null) {
73             if (this.relativePath != null) {
74                 String JavaDoc parentPath = DAVUtilities.getParentPath(relativePath);
75                 if (parentPath == null) {
76                 } else {
77                     this.parent = mount.getResource(parentPath, requestCredentials /*, transaction */);
78                 }
79             }
80         }
81     }
82     
83     /*
84      * (non-Javadoc)
85      *
86      * @see java.lang.Object#hashCode()
87      */

88     public int hashCode() {
89         try {
90             return getFile().hashCode();
91         } catch (IOException JavaDoc e) {
92             return hashCode();
93         }
94     }
95
96     /* (non-Javadoc)
97      * @see com.sslexplorer.vfs.VFSResource#isMount()
98      */

99     public boolean isMount() {
100         return false;
101     }
102
103     /* (non-Javadoc)
104      * @see com.sslexplorer.vfs.VFSResource#getWebFolderPath()
105      */

106     public String JavaDoc getWebFolderPath() {
107         return "/fs/" + mount.getMountString()
108             + (mount.getMountString().endsWith("/") || relativePath.startsWith("/") ? "" : "/")
109             + relativePath;
110     }
111
112
113     /* (non-Javadoc)
114      * @see java.lang.Object#equals(java.lang.Object)
115      */

116     public boolean equals(Object JavaDoc object) {
117         if (object == null)
118             return (false);
119         if (object instanceof FileObjectVFSResource) {
120             FileObjectVFSResource resource = (FileObjectVFSResource) object;
121             try {
122                 boolean u = getFile().equals(resource.getFile());
123                 boolean r = this.getMount() == resource.mount;
124                 return (u && r);
125             } catch (IOException JavaDoc ioe) {
126                 return false;
127             }
128         } else {
129             return (false);
130         }
131     }
132
133     /* (non-Javadoc)
134      * @see java.lang.Comparable#compareTo(java.lang.Object)
135      */

136     public int compareTo(Object JavaDoc object) {
137         FileObjectVFSResource resource = (FileObjectVFSResource) object;
138         try {
139             return (getFile().getURL().toExternalForm().compareTo(resource.getFile().getURL().toExternalForm()));
140         } catch (IOException JavaDoc ioe) {
141             log.warn("Failed to compare two files.", ioe);
142             return -999;
143         }
144     }
145
146     /* (non-Javadoc)
147      * @see com.sslexplorer.vfs.VFSResource#verifyAccess()
148      */

149     public void verifyAccess() throws Exception JavaDoc, DAVAuthenticationRequiredException {
150         this.getFile().exists();
151     }
152
153     /* (non-Javadoc)
154      * @see com.sslexplorer.vfs.VFSResource#isNull()
155      */

156     public boolean isNull() throws IOException JavaDoc {
157         return !getFile().exists();
158     }
159
160     /* (non-Javadoc)
161      * @see com.sslexplorer.vfs.VFSResource#isCollection()
162      */

163     public boolean isCollection() throws IOException JavaDoc {
164         if (this.isNull())
165             return false;
166         try {
167             FileObject temp = getFile();
168             FileType type = temp.getType();
169             if (type == null) {
170                 type = temp.getName().getType();
171             }
172             return (type.equals(FileType.FOLDER));
173         } catch (IOException JavaDoc e) {
174             if (log.isDebugEnabled()) {
175                 log.warn("Failed to test if resource is a collection.", e);
176             } else {
177                 log.warn("Failed to test if resource is a collection : " + e.getMessage());
178             }
179             return false;
180         }
181     }
182
183     /* (non-Javadoc)
184      * @see com.sslexplorer.vfs.VFSResource#isResource()
185      */

186     public boolean isResource() throws IOException JavaDoc {
187         if (this.isNull()) {
188             return false;
189         } else {
190             return (!this.isCollection());
191         }
192     }
193
194     /* (non-Javadoc)
195      * @see com.sslexplorer.vfs.VFSResource#getFile()
196      */

197     public FileObject getFile() throws IOException JavaDoc {
198         if (file == null) {
199             FileObject root = getFileObject("");
200             String JavaDoc stripLeadingSlash = DAVUtilities.stripLeadingSlash(getRelativePath());
201             file = root.resolveFile(stripLeadingSlash, NameScope.DESCENDENT_OR_SELF);
202             if (file == null) {
203                 throw new IOException JavaDoc("Could not create file object.");
204             }
205         }
206         return file;
207     }
208     
209     private FileObject getFileObject(String JavaDoc relativePath) throws DAVAuthenticationRequiredException, IOException JavaDoc {
210         FileObject fileObject = mount.createAuthenticatedVFSFileObject(relativePath, requestCredentials);
211         return fileObject;
212     }
213
214     /* (non-Javadoc)
215      * @see com.sslexplorer.vfs.VFSResource#getMount()
216      */

217     public VFSMount getMount() {
218         return this.mount;
219     }
220
221     /* (non-Javadoc)
222      * @see com.sslexplorer.vfs.VFSResource#getDisplayName()
223      */

224     public String JavaDoc getDisplayName() {
225         try {
226             String JavaDoc name = getFile().getName().getBaseName();
227             if (this.isCollection())
228                 return (name + "/");
229             return name;
230         } catch (IOException JavaDoc ioe) {
231             return getBasename();
232         }
233     }
234
235     /* (non-Javadoc)
236      * @see com.sslexplorer.vfs.VFSResource#getBasename()
237      */

238     public String JavaDoc getBasename() {
239         String JavaDoc p = relativePath;
240         int idx = p.length() < 2 ? -1 : (p.lastIndexOf('/', p.endsWith("/") ? p.length() - 2 : p.length() - 1));
241         if (idx != 1) {
242             p = p.substring(idx + 1);
243         }
244         return p;
245     }
246
247     /* (non-Javadoc)
248      * @see com.sslexplorer.vfs.VFSResource#getRelativePath()
249      */

250     public String JavaDoc getRelativePath() {
251         return relativePath;
252     }
253
254     /* (non-Javadoc)
255      * @see com.sslexplorer.vfs.VFSResource#getRelativeURI()
256      */

257     public URI JavaDoc getRelativeURI() {
258         try {
259             return new URI JavaDoc(DAVUtilities.encodePath(getRelativePath()));
260         } catch (Exception JavaDoc e) {
261             log.warn("Failed to get the relativeURI for the resource", e);
262             e.printStackTrace();
263             return null;
264         }
265     }
266
267     /* (non-Javadoc)
268      * @see com.sslexplorer.vfs.VFSResource#getParent()
269      */

270     public VFSResource getParent() {
271         try {
272             if (parent == null) {
273                 String JavaDoc parentPath = DAVUtilities.stripLeadingSlash(DAVUtilities.getParentPath(getFullPath()));
274                 if (parentPath == null || parentPath.equals("/")) {
275                     return null;
276                 } else {
277                     return repository.getResource(getLaunchSession(), parentPath, requestCredentials/*
278                                                                                                      * ,
279                                                                                                      * transaction
280                                                                                                      */
);
281                 }
282             }
283         } catch (Throwable JavaDoc throwable) {
284             throwable.printStackTrace();
285         }
286         return parent;
287     }
288
289     /* (non-Javadoc)
290      * @see com.sslexplorer.vfs.VFSResource#getChildren()
291      */

292     public Iterator JavaDoc<VFSResource> getChildren() throws IOException JavaDoc {
293         if (!this.isCollection())
294             return null;
295
296         // this forces VFS to re cashe.
297
this.getFile().close();
298
299         FileObject children[] = this.getFile().getChildren();
300         List JavaDoc<VFSResource> resources = new ArrayList JavaDoc<VFSResource>(children.length);
301
302         for (int x = 0; x < children.length; x++) {
303             String JavaDoc fileName = children[x].getName().getBaseName();
304             if (fileName.startsWith(PREFIX) && fileName.endsWith(SUFFIX))
305                 continue;
306             if (!isCollection() && !isResource())
307                 continue;
308             try {
309                 /*
310                  * TODO BPS - I think we have a problem here.
311                  *
312                  * When getting children that require further authentication we
313                  * get a {@link DAVAuthenticationRequiredException} exception.
314                  * We do not want to throw an exception at this point but we do
315                  * want add the child. Its only when children of the child are
316                  * accessed that we want to throw the exception. Because
317                  * DAVMount.getResource() is the one that throws this, a
318                  * resource object can never be created.
319                  *
320                  * This will happen for example when listomg /fs/[store] and a
321                  * network place that requires auth. is hit.
322                  */

323
324                 VFSResource r = getMount().getResource(DAVUtilities.concatenatePaths(relativePath, fileName), requestCredentials/*
325                                                                                                                                  * ,
326                                                                                                                                  * transaction
327                                                                                                                                  */
);
328                 resources.add(r);
329             } catch (Exception JavaDoc e) {
330                 /*
331                  * NOTE - BPS - We cannot log this exception as it may have user
332                  * information in the URI.
333                  */

334                 // log.warn("Failed to get resource.", e);
335
}
336         }
337         return resources.iterator();
338     }
339
340     /* (non-Javadoc)
341      * @see com.sslexplorer.vfs.VFSResource#getContentType()
342      */

343     public String JavaDoc getContentType() throws IOException JavaDoc {
344         if (this.isNull())
345             return null;
346         if (this.isCollection())
347             return GET.COLLECTION_MIME_TYPE;
348         String JavaDoc mime = DAVUtilities.getMimeType(this.getDisplayName());
349         return mime == null ? "application/octet-stream" : mime;
350     }
351
352     /* (non-Javadoc)
353      * @see com.sslexplorer.vfs.VFSResource#getContentLength()
354      */

355     public Long JavaDoc getContentLength() throws IOException JavaDoc {
356         if (this.isNull() || this.isCollection())
357             return null;
358         try {
359             return new Long JavaDoc(getFile().getContent().getSize());
360         } catch (IOException JavaDoc e) {
361             log.error("Failed to get content length.", e);
362             return null;
363         }
364     }
365
366     /* (non-Javadoc)
367      * @see com.sslexplorer.vfs.VFSResource#getLastModified()
368      */

369     public Date JavaDoc getLastModified() throws IOException JavaDoc {
370         if (this.isNull())
371             return null;
372         try {
373             return new Date JavaDoc(getFile().getContent().getLastModifiedTime());
374         } catch (IOException JavaDoc e) {
375             log.error("Failed to get last modified date of resource.", e);
376             return null;
377         }
378     }
379
380     /* (non-Javadoc)
381      * @see com.sslexplorer.vfs.VFSResource#getEntityTag()
382      */

383     public String JavaDoc getEntityTag() throws IOException JavaDoc {
384         if (this.isNull())
385             return null;
386
387         String JavaDoc path = this.getRelativePath();
388         return DAVUtilities.getETAG(path, this.getLastModified());
389     }
390
391     /* (non-Javadoc)
392      * @see com.sslexplorer.vfs.VFSResource#delete()
393      */

394     public void delete() throws DAVMultiStatus, IOException JavaDoc {
395         if (this.isNull())
396             throw new DAVException(404, "Not found", this);
397
398         if (getMount().isReadOnly()) {
399             throw new DAVException(DAVStatus.SC_FORBIDDEN, "You cannot delete this file because the the mount is readonly!");
400         }
401
402         if (this.isResource()) {
403             try {
404                 if (!getFile().delete()) {
405                     throw new DAVException(403, "Can't delete resource '" + getRelativePath() + "'", this);
406                 } else {
407                     this.getMount().getStore().getRepository().notify(this, DAVListener.RESOURCE_REMOVED);
408                 }
409             } catch (IOException JavaDoc e) {
410                 log.error("Failed to delete resource.", e);
411                 throw new DAVException(403, "Can't delete resource. " + e.getMessage(), this);
412             }
413         } else if (this.isMount()) {
414             throw new DAVException(403, "Can't delete resource '" + getRelativePath()
415                 + "' as it is the root for the mount point "
416                 + this.getMount().getMountString(), this);
417         } else if (this.isCollection()) {
418
419             DAVMultiStatus multistatus = new DAVMultiStatus();
420
421             Iterator JavaDoc children = this.getChildren();
422             while (children.hasNext())
423                 try {
424                     ((VFSResource) children.next()).delete();
425                 } catch (DAVException exception) {
426                     multistatus.merge(exception);
427                 }
428
429             if (multistatus.size() > 0)
430                 throw multistatus;
431             try {
432                 if (!getFile().delete()) {
433                     throw new DAVException(403, "Can't delete collection", this);
434                 } else {
435                     this.getMount().getStore().getRepository().notify(this, DAVListener.COLLECTION_REMOVED);
436                 }
437             } catch (IOException JavaDoc e) {
438                 log.error("Failed to delete resource.", e);
439                 throw new DAVException(403, "Can't delete collection " + getRelativePath() + ". " + e.getMessage(), this);
440             }
441         }
442     }
443
444     /* (non-Javadoc)
445      * @see com.sslexplorer.vfs.VFSResource#copy(com.sslexplorer.vfs.VFSResource, boolean, boolean)
446      */

447     public void copy(VFSResource dest, boolean overwrite, boolean recursive) throws DAVMultiStatus, IOException JavaDoc {
448
449         /*
450          * NOTE: Since the COPY operation relies on other operation defined in
451          * this class (and in DAVOutputStream for resources) rather than on
452          * files temselves, notifications are sent elsewhere, not here.
453          */

454
455         if (this.isNull())
456             throw new DAVException(404, "Not found", this);
457
458         /* Check if the destination exists and delete if possible */
459         if (!dest.isNull()) {
460             if (!overwrite) {
461                 String JavaDoc msg = "Not overwriting existing destination";
462                 throw new DAVException(412, msg, dest);
463             }
464             dest.delete();
465         }
466
467         /* Copy a single resource (destination is null as we deleted it) */
468         if (this.isResource()) {
469             VFSInputStream in = this.getInputStream();
470             VFSOutputStream out = dest.getOutputStream();
471             byte buffer[] = new byte[4096];
472             int k = -1;
473             while ((k = in.read(buffer)) != -1)
474                 out.write(buffer, 0, k);
475             out.close();
476         }
477
478         /* Copy the collection and all nested members */
479         if (this.isCollection()) {
480             dest.makeCollection();
481             if (!recursive)
482                 return;
483
484             DAVMultiStatus multistatus = new DAVMultiStatus();
485             Iterator JavaDoc children = this.getChildren();
486             while (children.hasNext())
487                 try {
488                     FileObjectVFSResource childResource = (FileObjectVFSResource) children.next();
489                     try {
490                         FileObject child = ((FileObjectVFSResource) dest).getFile().resolveFile(childResource.getFile()
491                                         .getName()
492                                         .getBaseName());
493                         FileObjectVFSResource target = new FileObjectVFSResource(getLaunchSession(),
494                                         this.getMount(),
495                                         this, /* transaction, */
496                                         this.getMount().getMountString(),
497                                         repository,
498                                         requestCredentials);
499                         childResource.copy(target, overwrite, recursive);
500                     } catch (IOException JavaDoc e) {
501                         throw new DAVException(403, "Could not resolve child.", e);
502                     }
503                 } catch (DAVException exception) {
504                     multistatus.merge(exception);
505                 }
506             if (multistatus.size() > 0)
507                 throw multistatus;
508         }
509     }
510
511     /* (non-Javadoc)
512      * @see com.sslexplorer.vfs.VFSResource#move(com.sslexplorer.vfs.VFSResource, boolean)
513      */

514     public void move(VFSResource dest, boolean overwrite) throws DAVMultiStatus, IOException JavaDoc {
515
516         /*
517          * NOTE: Since the COPY operation relies on other operation defined in
518          * this class (and in DAVOutputStream for resources) rather than on
519          * files temselves, notifications are sent elsewhere, not here.
520          */

521
522         if (this.isNull())
523             throw new DAVException(404, "Not found", this);
524
525         /* Check read only */
526         if (getMount().isReadOnly()) {
527             throw new DAVException(DAVStatus.SC_FORBIDDEN, "You cannot move this file because the the mount is readonly!");
528         }
529
530         /* Check if the destination exists and delete if possible */
531         if (!dest.isNull()) {
532             if (!overwrite) {
533                 String JavaDoc msg = "Not overwriting existing destination";
534                 throw new DAVException(412, msg, dest);
535             }
536             dest.delete();
537         }
538
539         /* If the file system supports then move then just do it */
540         if (getFile().canRenameTo(dest.getFile())) {
541             getFile().moveTo(dest.getFile());
542             return;
543         }
544
545         /* Otherwise copy */
546         copy(dest, overwrite, true);
547     }
548
549     /* (non-Javadoc)
550      * @see com.sslexplorer.vfs.VFSResource#makeCollection()
551      */

552     public void makeCollection() throws IOException JavaDoc {
553         VFSResource parent = this.getParent();
554         if (!this.isNull())
555             throw new DAVException(405, "Resource exists", this);
556         if (parent.isNull())
557             throw new DAVException(409, "Parent does not not exist", this);
558         if (!parent.isCollection())
559             throw new DAVException(403, "Parent not a collection", this);
560
561         /* Check read only */
562         if (getMount().isReadOnly()) {
563             throw new DAVException(DAVStatus.SC_FORBIDDEN, "You cannot create a folder here because the the mount is readonly!");
564         }
565
566         try {
567             getFile().createFolder();
568             this.getMount().getStore().getRepository().notify(this, DAVListener.COLLECTION_CREATED);
569         } catch (IOException JavaDoc e) {
570             throw new DAVException(507, "Can't create collection", this);
571         }
572     }
573
574     /* (non-Javadoc)
575      * @see com.sslexplorer.vfs.VFSResource#getInputStream()
576      */

577     public VFSInputStream getInputStream() throws IOException JavaDoc {
578         if (this.isNull())
579             throw new DAVException(404, "Not found", this);
580         if (this.isCollection())
581             throw new DAVException(403, "Resource is collection", this);
582         return new VFSInputStream(this);
583     }
584
585     /* (non-Javadoc)
586      * @see com.sslexplorer.vfs.VFSResource#getOutputStream()
587      */

588     public VFSOutputStream getOutputStream() throws IOException JavaDoc {
589         if (this.isCollection())
590             throw new DAVException(409, "Can't write a collection", this);
591
592         if (getMount().isReadOnly()) {
593             throw new DAVException(DAVStatus.SC_FORBIDDEN, "You cannot create a write here because the the mount is readonly!");
594         }
595         return new VFSOutputStream(this);
596     }
597
598     /*
599      * (non-Javadoc)
600      *
601      * @see com.sslexplorer.vfs.VFSResource#getFullURI()
602      */

603     public URI JavaDoc getFullURI() {
604         VFSMount mount = getMount();
605         URI JavaDoc uri = URI.create(mount == null ? ("/" + getRelativeURI())
606             : ("/" + DAVUtilities.stripTrailingSlash(DAVUtilities.encodePath(mount.getMountString(), true)) + "/" + DAVUtilities.stripLeadingSlash(DAVUtilities.encodePath(getRelativePath(),
607                 true))));
608         return uri;
609     }
610
611     /*
612      * (non-Javadoc)
613      *
614      * @see com.sslexplorer.vfs.VFSResource#getFullPath()
615      */

616     public String JavaDoc getFullPath() {
617         VFSMount mount = getMount();
618         return mount == null ? ("/" + getRelativeURI()) : ("/" + mount.getMountString()
619             + (mount.getMountString().endsWith("/") || getRelativePath().startsWith("/") ? "" : "/") + getRelativePath());
620     }
621
622     /*
623      * (non-Javadoc)
624      *
625      * @see com.sslexplorer.vfs.VFSResource#getLaunchSession()
626      */

627     public LaunchSession getLaunchSession() {
628         return launchSession;
629     }
630 }
631
Popular Tags