KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > networkplaces > AbstractNetworkPlaceMount


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.networkplaces;
21
22 import java.io.IOException JavaDoc;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.apache.commons.vfs.FileObject;
27
28 import com.sslexplorer.boot.Util;
29 import com.sslexplorer.core.CoreEvent;
30 import com.sslexplorer.core.CoreServlet;
31 import com.sslexplorer.core.stringreplacement.VariableReplacement;
32 import com.sslexplorer.policyframework.LaunchSession;
33 import com.sslexplorer.properties.Property;
34 import com.sslexplorer.properties.impl.systemconfig.SystemConfigKey;
35 import com.sslexplorer.security.AuthenticationScheme;
36 import com.sslexplorer.security.Constants;
37 import com.sslexplorer.security.LogonControllerFactory;
38 import com.sslexplorer.security.PasswordCredentials;
39 import com.sslexplorer.security.SessionInfo;
40 import com.sslexplorer.vfs.VFSMount;
41 import com.sslexplorer.vfs.VFSProvider;
42 import com.sslexplorer.vfs.VFSResource;
43 import com.sslexplorer.vfs.VFSStore;
44 import com.sslexplorer.vfs.utils.URI;
45 import com.sslexplorer.vfs.utils.URI.MalformedURIException;
46 import com.sslexplorer.vfs.webdav.DAVAuthenticationRequiredException;
47 import com.sslexplorer.vfs.webdav.DAVTransaction;
48 import com.sslexplorer.vfs.webdav.DAVUtilities;
49
50 /**
51  * An abstract implementation of a {@link VFSMount} that is based upon a
52  * configured <i>Network Place</i>.
53  * <p>
54  * The URI provided in the network place is used as the root for the mount.
55  * <p>
56  * The {@link VFSResource} instances returned by this mount use the SSL-Explorer
57  * extensions to <i>Commons VFS</i> as the underlying file system.
58  *
59  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
60  * @see NetworkPlace
61  */

62 public abstract class AbstractNetworkPlaceMount implements VFSMount {
63     final static Log log = LogFactory.getLog(AbstractNetworkPlaceMount.class);
64
65     // Private instance variables
66

67     private VFSStore store;
68     private boolean readOnly;
69     private boolean tryCurrentUser, tryGuest;
70     private LaunchSession launchSession;
71
72     /**
73      * Constructor.
74      *
75      * @param launchSession launch session
76      * @param store store
77      */

78     public AbstractNetworkPlaceMount(LaunchSession launchSession, VFSStore store) {
79         this.store = store;
80         this.launchSession = launchSession;
81         this.readOnly = getNetworkPlace().isReadOnly();
82         try {
83             tryCurrentUser = Property.getPropertyBoolean(new SystemConfigKey("fileBrowsing.auth.tryCurrentUser"));
84             tryGuest = Property.getPropertyBoolean(new SystemConfigKey("fileBrowsing.auth.tryGuest"));
85
86         } catch (Exception JavaDoc e) {
87         }
88     }
89
90     /**
91      * Get the launch session
92      *
93      * @return launch session
94      */

95     public LaunchSession getLaunchSession() {
96         return launchSession;
97     }
98
99     /**
100      * Set whether this mount is read-only. By default this is determined by the
101      * network place resource object.
102      *
103      * @param readOnly read only
104      */

105     public void setReadOnly(boolean readOnly) {
106         this.readOnly = readOnly;
107     }
108
109     /**
110      * Get whether this mount is read-only. By default this is determined by the
111      * network place resource object.
112      *
113      * @return read only
114      */

115     public boolean isReadOnly() {
116         return readOnly;
117     }
118
119     /**
120      * Create
121      *
122      * @param path path
123      * @param credentials credentials
124      * @return resource
125      * @throws IOException on any error
126      * @throws DAVAuthenticationRequiredException if resources requires
127      * authentication
128      */

129     protected abstract FileObject createVFSFileObject(String JavaDoc path, PasswordCredentials credentials) throws IOException JavaDoc,
130                     DAVAuthenticationRequiredException;
131
132     /*
133      * (non-Javadoc)
134      *
135      * @see com.sslexplorer.vfs.webdav.DAVMount#getStore()
136      */

137     public VFSStore getStore() {
138         return store;
139     }
140
141     /*
142      * (non-Javadoc)
143      *
144      * @see com.sslexplorer.vfs.webdav.DAVMount#getResource(java.lang.String,
145      * com.sslexplorer.vfs.webdav.DAVTransaction)
146      */

147     public VFSResource getResource(String JavaDoc path, PasswordCredentials requestCredentials) throws IOException JavaDoc,
148                     DAVAuthenticationRequiredException {
149         VFSResource parent = null;
150         if(path.equals("")) {
151             parent = store.getStoreResource();
152         }
153         return new NetworkPlaceVFSResource(getLaunchSession(), this,
154                         parent,
155                         path,
156                         store.getRepository(),
157                         requestCredentials);
158     }
159
160     /*
161      * (non-Javadoc)
162      *
163      * @see com.sslexplorer.vfs.webdav.DAVMount#getMountString()
164      */

165     public String JavaDoc getMountString() {
166         return this.getStore().getName() + "/" + this.getNetworkPlace().getResourceName();
167     }
168
169     /*
170      * (non-Javadoc)
171      *
172      * @see com.sslexplorer.vfs.VFSMount#resourceCopy(com.sslexplorer.vfs.VFSResource,
173      * com.sslexplorer.vfs.VFSResource,
174      * com.sslexplorer.vfs.webdav.DAVTransaction, java.lang.Throwable)
175      */

176     public void resourceCopy(VFSResource resource, VFSResource destination, DAVTransaction transaction, Throwable JavaDoc exception) {
177         if (getStore().getProvider().isFireEvents()) {
178             CoreEvent evt = NetworkPlaceResourceType.getResourceAccessPasteEvent(this,
179                 launchSession,
180                 transaction.getRequest(),
181                 resource.getFullURI().getPath(),
182                 getResourceURI(resource),
183                 exception);
184             if (destination != null) {
185                 NetworkPlaceResourceType.addFileAttribute(evt, destination.getDisplayName(), 1);
186             }
187             NetworkPlaceResourceType.addOperationType(evt, false);
188             CoreServlet.getServlet().fireCoreEvent(evt);
189         }
190     }
191
192     /*
193      * (non-Javadoc)
194      *
195      * @see com.sslexplorer.vfs.VFSMount#resourceDelete(com.sslexplorer.vfs.VFSResource,
196      * com.sslexplorer.vfs.webdav.DAVTransaction, java.lang.Throwable)
197      */

198     public void resourceDelete(VFSResource resource, DAVTransaction transaction, Throwable JavaDoc exception) {
199         if (getStore().getProvider().isFireEvents()) {
200             CoreServlet.getServlet().fireCoreEvent(NetworkPlaceResourceType.getResourceAccessDeleteEvent(this,
201                 launchSession,
202                 transaction.getRequest(),
203                 resource.getFullURI().getPath(),
204                 getResourceURI(resource),
205                 resource.getDisplayName(),
206                 exception));
207         }
208     }
209
210     /*
211      * (non-Javadoc)
212      *
213      * @see com.sslexplorer.vfs.VFSMount#resourceUpload(com.sslexplorer.vfs.VFSResource,
214      * com.sslexplorer.vfs.webdav.DAVTransaction, java.lang.Throwable)
215      */

216     public void resourceUpload(VFSResource resource, DAVTransaction transaction, Throwable JavaDoc exception) {
217         if (getStore().getProvider().isFireEvents()) {
218             CoreServlet.getServlet().fireCoreEvent(NetworkPlaceResourceType.getResourceAccessUploadEvent(this,
219                 launchSession,
220                 transaction.getRequest(),
221                 resource.getFullPath(),
222                 getResourceURI(resource),
223                 resource.getDisplayName(),
224                 null));
225         }
226     }
227
228     /*
229      * (non-Javadoc)
230      *
231      * @see com.sslexplorer.vfs.VFSMount#resourceAccessList(com.sslexplorer.vfs.VFSResource,
232      * com.sslexplorer.vfs.webdav.DAVTransaction, java.lang.Throwable)
233      */

234     public void resourceAccessList(VFSResource resource, DAVTransaction transaction, Throwable JavaDoc exception) {
235         if (getStore().getProvider().isFireEvents()) {
236             CoreServlet.getServlet().fireCoreEvent(NetworkPlaceResourceType.getResourceAccessListEvent(this,
237                 launchSession,
238                 transaction.getRequest(),
239                 resource.getFullURI().getPath(),
240                 getResourceURI(resource),
241                 exception));
242         }
243     }
244
245     /*
246      * (non-Javadoc)
247      *
248      * @see com.sslexplorer.vfs.VFSMount#resourceCollectionCreated(com.sslexplorer.vfs.VFSResource,
249      * com.sslexplorer.vfs.webdav.DAVTransaction, java.lang.Throwable)
250      */

251     public void resourceCollectionCreated(VFSResource resource, DAVTransaction transaction, Throwable JavaDoc exception) {
252         if (getStore().getProvider().isFireEvents()) {
253             CoreServlet.getServlet().fireCoreEvent(NetworkPlaceResourceType.getResourceAccessMkDirEvent(this,
254                 launchSession,
255                 transaction.getRequest(),
256                 resource.getFullURI().getPath(),
257                 getResourceURI(resource),
258                 exception));
259
260         }
261     }
262
263     /*
264      * (non-Javadoc)
265      *
266      * @see com.sslexplorer.vfs.VFSMount#resourceMoved(com.sslexplorer.vfs.VFSResource,
267      * com.sslexplorer.vfs.VFSResource,
268      * com.sslexplorer.vfs.webdav.DAVTransaction, java.lang.Throwable)
269      */

270     public void resourceMoved(VFSResource resource, VFSResource destination, DAVTransaction transaction, Throwable JavaDoc exception) {
271         if (getStore().getProvider().isFireEvents()) {
272             CoreEvent evt = NetworkPlaceResourceType.getResourceAccessPasteEvent(this,
273                 launchSession,
274                 transaction.getRequest(),
275                 resource.getFullURI().getPath(),
276                 getResourceURI(resource),
277                 exception);
278             if (destination != null) {
279                 NetworkPlaceResourceType.addFileAttribute(evt, destination.getDisplayName(), 1);
280             }
281             NetworkPlaceResourceType.addOperationType(evt, true);
282             CoreServlet.getServlet().fireCoreEvent(evt);
283         }
284     }
285
286     /*
287      * (non-Javadoc)
288      *
289      * @see com.sslexplorer.vfs.VFSMount#resourceAccessDownloading(com.sslexplorer.vfs.VFSResource,
290      * com.sslexplorer.vfs.webdav.DAVTransaction)
291      */

292     public void resourceAccessDownloading(VFSResource resource, DAVTransaction transaction) {
293         if (getStore().getProvider().isFireEvents()) {
294             CoreServlet.getServlet().fireCoreEvent(NetworkPlaceResourceType.getResourceAccessDownloadStartedEvent(this,
295                 launchSession,
296                 transaction.getRequest(),
297                 resource.getRelativePath(),
298                 resource.getRelativeURI().toString()));
299         }
300     }
301
302     /*
303      * (non-Javadoc)
304      *
305      * @see com.sslexplorer.vfs.VFSMount#resourceAccessDownloadComplete(com.sslexplorer.vfs.VFSResource,
306      * com.sslexplorer.vfs.webdav.DAVTransaction, java.lang.Throwable)
307      */

308     public void resourceAccessDownloadComplete(VFSResource resource, DAVTransaction transaction, Throwable JavaDoc exception) {
309         if (getStore().getProvider().isFireEvents()) {
310             if (exception != null) {
311                 CoreServlet.getServlet().fireCoreEvent(NetworkPlaceResourceType.getResourceAccessDownloadFailedEvent(this,
312                     launchSession,
313                     transaction.getRequest(),
314                     resource.getRelativePath(),
315                     resource.getRelativeURI().toString(),
316                     exception));
317             } else {
318                 CoreServlet.getServlet().fireCoreEvent(NetworkPlaceResourceType.getResourceAccessDownloadCompleteEvent(this,
319                     launchSession,
320                     transaction.getRequest(),
321                     resource.getRelativePath(),
322                     resource.getRelativeURI().toString()));
323             }
324         }
325     }
326
327     /**
328      * Get the network place that backs this mount.
329      *
330      * @return network place
331      */

332     public NetworkPlace getNetworkPlace() {
333         return (NetworkPlace)launchSession.getResource();
334     }
335
336     /**
337      * Get the root VFS URI for the current network place. By default this
338      * assumes the path contains a full URI. It is up to the individual mount
339      * implementations to overide this method and return a correct URI if they
340      * support paths other than URIs (<i>file</i> for example supports local
341      * file paths)
342      *
343      * @param charset character set
344      * @return uri
345      * @throws MalformedURIException
346      */

347     public URI getRootVFSURI(String JavaDoc charset) throws MalformedURIException {
348         
349         /* This is where the details from a network place get turned into
350          * a URI.
351          *
352          * This is the *only* place replacement and encoding of the network
353          * place URI elements should occur as it is the only time when we
354          * have all the supporting objects (Session, Policy, Resource).
355          */

356         
357         VariableReplacement r = new VariableReplacement();
358         r.setLaunchSession(getLaunchSession());
359         
360         // User info. Encoded
361
String JavaDoc userinfo = null;
362         if(!Util.isNullOrTrimmedBlank(getNetworkPlace().getUsername())) {
363             String JavaDoc username = r.replace(getNetworkPlace().getUsername());
364             String JavaDoc password = null;
365             if(!Util.isNullOrTrimmedBlank(getNetworkPlace().getPassword())) {
366                 password = r.replace(getNetworkPlace().getPassword());
367             }
368             userinfo = DAVUtilities.encodeURIUserInfo(username + (password == null ? "" : ":" + password));
369         }
370         
371         // Host. TODO check host only contains SPACE,a-z,A-Z and - and doesn't begin with -
372
String JavaDoc host = null;
373         if(getStore().getProvider().getHostRequirement() == VFSProvider.ELEMENT_REQUIRED) {
374             host = r.replace(getNetworkPlace().getHost());
375         }
376
377         // Port. Integer. A port of -1 signifies default (0 means default in network place)
378
int port = -1;
379         if(getStore().getProvider().getPortRequirement() == VFSProvider.ELEMENT_REQUIRED && getNetworkPlace().getPort() > 0) {
380             port = getNetworkPlace().getPort();
381         }
382
383         // Path. Always required. Replaced and encoded.
384
String JavaDoc path = DAVUtilities.encodePath(r.replace(getNetworkPlace().getPath().replace('\\', '/')), charset);
385         if(!Util.isNullOrTrimmedBlank(path) && !path.startsWith("/") && !path.startsWith("./")) {
386             path = "/" + path;
387         }
388         
389         // Query String. TODO we need to support
390
String JavaDoc queryString = null;
391         
392         // Fragment. TODO we need to support
393
String JavaDoc fragment = null;
394
395         // Create the URI
396
URI uri = new URI(getNetworkPlace().getScheme(), userinfo, host, port, path, queryString, fragment);
397         if(log.isDebugEnabled())
398             log.debug("Creating URI " + uri);
399         return uri;
400     }
401
402     /**
403      * Get the root VFS URI encoded as UTF-8
404      *
405      * @return root VFS URI as UTF-8
406      * @throws MalformedURIException
407      */

408     public URI getRootVFSURI() throws MalformedURIException {
409         return getRootVFSURI("UTF-8");
410     }
411
412     /* (non-Javadoc)
413      * @see com.sslexplorer.vfs.VFSMount#createAuthenticatedVFSFileObject(java.lang.String, com.sslexplorer.security.PasswordCredentials)
414      */

415     public FileObject createAuthenticatedVFSFileObject(String JavaDoc path, PasswordCredentials requestCredentials) throws IOException JavaDoc, DAVAuthenticationRequiredException {
416         // 0 = Current
417
// 1 = URI
418
// 2 = HTTP authentication response
419
// 3 = Current users credentials
420
// 4 = Guest
421
// 5 = Prompt
422
int type = 0;
423         DAVAuthenticationRequiredException dave = null;
424         PasswordCredentials credentials = null;
425         boolean hasCachedCredentials = false;
426
427         if (log.isDebugEnabled())
428             log.debug("Trying all available credentials for " + getMountString() + path);
429
430         while (true) {
431
432             // If no credentials are currently set, try those in the cache
433
// first
434

435             if (type == 0) {
436                 credentials = getStore().getRepository().getCredentialsCache().getDAVCredentials(getStore().getName(),
437                     getMountString());
438                 if (credentials == null) {
439                     type++;
440                 } else {
441                     if (log.isDebugEnabled())
442                         log.debug("Trying cached credentials for " + getMountString() + path);
443
444                     hasCachedCredentials = true;
445                 }
446             }
447
448             // User info from URI
449
if (type == 1) {
450                 URI uri = getRootVFSURI(store.getEncoding());
451                 String JavaDoc userInfo = uri.getUserinfo();
452                 if (userInfo == null || userInfo.equals("")) {
453                     type++;
454                 } else {
455                     String JavaDoc username = null;
456                     char[] pw = null;
457                     userInfo = Util.urlDecode(userInfo);
458                     int idx = userInfo.indexOf(":");
459                     username = userInfo;
460                     if (idx != -1) {
461                         username = userInfo.substring(0, idx);
462                         pw = userInfo.substring(idx + 1).toCharArray();
463                     }
464                     credentials = new PasswordCredentials(username, pw);
465
466                     if (log.isDebugEnabled()) {
467                         log.debug("Trying URI credentials for " + getMountString() + path);
468                     }
469                 }
470             }
471
472             // HTTP authentication response
473

474             if (type == 2) {
475                 credentials = requestCredentials;
476                 if (credentials == null) {
477                     type++;
478                 } else if (log.isDebugEnabled()) {
479                     log.debug("Trying Request credentials for " + getMountString() + path);
480                 }
481             }
482
483             // Current user creds
484
if (type == 3) {
485                 if (!tryCurrentUser) {
486                     type++;
487                 } else {
488
489                     SessionInfo inf = getStore().getRepository().getSession();
490
491                     char[] pw = LogonControllerFactory.getInstance()
492                                     .getPasswordFromCredentials((AuthenticationScheme) inf.getHttpSession()
493                                                     .getAttribute(Constants.AUTH_SESSION));
494
495                     if (pw == null) {
496                         if (log.isDebugEnabled())
497                             log.debug("No password available from current session");
498                         type++;
499                     } else {
500                         credentials = new PasswordCredentials(inf.getUser().getPrincipalName(), pw);
501
502                         if (log.isDebugEnabled()) {
503                             log.debug("Trying current session credentials for " + "/" + getMountString() + path);
504                         }
505                     }
506                 }
507             }
508
509             // Guest creds
510

511             if (type == 4) {
512                 if (!tryGuest) {
513                     type++;
514                 } else {
515                     String JavaDoc guestAccount = getStore().getGuestUsername();
516                     if (guestAccount == null) {
517                         type++;
518                     } else {
519                         credentials = new PasswordCredentials(guestAccount, getStore().getGuestPassword());
520
521                         if (log.isDebugEnabled()) {
522                             log.debug("Trying guest credentials for " + getMountString() + path);
523                         }
524                     }
525                 }
526             }
527
528             // Throw exception. Servlet will then request HTTP
529
// authentication
530
if (type > 4 && dave != null) {
531                 throw dave;
532             }
533
534             try {
535                 FileObject file = createVFSFileObject(path, credentials);
536
537                 if (file == null) {
538                     throw new IOException JavaDoc("Could not create file object.");
539                 }
540
541                 // Cache authentication
542
if (credentials != null) {
543
544                     if (!hasCachedCredentials) {
545                         if (log.isDebugEnabled()) {
546                             log.debug("Caching credentials for " + getMountString());
547                         }
548                         getStore().getRepository().getCredentialsCache().addCredentials(getStore().getName(),
549                             getMountString(),
550                             credentials);
551                     }
552                 }
553
554                 return file;
555             } catch (DAVAuthenticationRequiredException dare) {
556                 dave = dare;
557                 type++;
558             }
559         }
560     }
561
562     String JavaDoc getResourceURI(VFSResource resource) {
563         String JavaDoc uri = "Could not retrieve path";
564         try {
565             uri = resource.getFile().getName().getURI();
566         } catch (Exception JavaDoc e) {
567         }
568         return uri;
569     }
570 }
Popular Tags