1 package org.apache.archiva.webdav;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.beans.ManagedRepository;
23 import org.apache.archiva.audit.AuditEvent;
24 import org.apache.archiva.audit.AuditListener;
25 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
26 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
27 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
28 import org.apache.archiva.scheduler.repository.RepositoryTask;
29 import org.apache.archiva.webdav.util.IndexWriter;
30 import org.apache.archiva.webdav.util.MimeTypes;
31 import org.apache.commons.io.FileUtils;
32 import org.apache.commons.io.IOUtils;
33 import org.apache.jackrabbit.util.Text;
34 import org.apache.jackrabbit.webdav.DavException;
35 import org.apache.jackrabbit.webdav.DavResource;
36 import org.apache.jackrabbit.webdav.DavResourceFactory;
37 import org.apache.jackrabbit.webdav.DavResourceIterator;
38 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
39 import org.apache.jackrabbit.webdav.DavResourceLocator;
40 import org.apache.jackrabbit.webdav.DavServletResponse;
41 import org.apache.jackrabbit.webdav.DavSession;
42 import org.apache.jackrabbit.webdav.MultiStatusResponse;
43 import org.apache.jackrabbit.webdav.io.InputContext;
44 import org.apache.jackrabbit.webdav.io.OutputContext;
45 import org.apache.jackrabbit.webdav.lock.ActiveLock;
46 import org.apache.jackrabbit.webdav.lock.LockInfo;
47 import org.apache.jackrabbit.webdav.lock.LockManager;
48 import org.apache.jackrabbit.webdav.lock.Scope;
49 import org.apache.jackrabbit.webdav.lock.Type;
50 import org.apache.jackrabbit.webdav.property.DavProperty;
51 import org.apache.jackrabbit.webdav.property.DavPropertyName;
52 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
53 import org.apache.jackrabbit.webdav.property.DavPropertySet;
54 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
55 import org.apache.jackrabbit.webdav.property.ResourceType;
56 import org.joda.time.DateTime;
57 import org.joda.time.format.DateTimeFormatter;
58 import org.joda.time.format.ISODateTimeFormat;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 import javax.servlet.http.HttpServletResponse;
64 import java.io.FileInputStream;
65 import java.io.FileOutputStream;
66 import java.io.IOException;
67 import java.util.ArrayList;
68 import java.util.List;
72 public class ArchivaDavResource
73 implements DavResource
75 public static final String HIDDEN_PATH_PREFIX = ".";
77 private final ArchivaDavResourceLocator locator;
79 private final DavResourceFactory factory;
81 private final File localResource;
83 private final String logicalResource;
85 private DavPropertySet properties = null;
87 private LockManager lockManager;
89 private final DavSession session;
91 private String remoteAddr;
93 private final ManagedRepository repository;
95 private final MimeTypes mimeTypes;
97 private List<AuditListener> auditListeners;
99 private String principal;
101 public static final String COMPLIANCE_CLASS = "1, 2";
103 private ArchivaTaskScheduler scheduler;
105 private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
107 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepository repository,
108 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
109 MimeTypes mimeTypes, List<AuditListener> auditListeners,
110 RepositoryArchivaTaskScheduler scheduler )
112 this.localResource = new File( localResource );
113 this.logicalResource = logicalResource;
114 this.locator = locator;
115 this.factory = factory;
116 this.session = session;
118 // TODO: push into locator as well as moving any references out of the resource factory
119 this.repository = repository;
121 // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
122 this.mimeTypes = mimeTypes;
123 this.auditListeners = auditListeners;
124 this.scheduler = scheduler;
127 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepository repository,
128 String remoteAddr, String principal, DavSession session,
129 ArchivaDavResourceLocator locator, DavResourceFactory factory, MimeTypes mimeTypes,
130 List<AuditListener> auditListeners, RepositoryArchivaTaskScheduler scheduler )
132 this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
135 this.remoteAddr = remoteAddr;
136 this.principal = principal;
139 public String getComplianceClass()
141 return COMPLIANCE_CLASS;
144 public String getSupportedMethods()
149 public boolean exists()
151 return localResource.exists();
154 public boolean isCollection()
156 return localResource.isDirectory();
159 public String getDisplayName()
161 String resPath = getResourcePath();
162 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
165 public DavResourceLocator getLocator()
170 public File getLocalResource()
172 return localResource;
175 public String getResourcePath()
177 return locator.getResourcePath();
180 public String getHref()
182 return locator.getHref( isCollection() );
185 public long getModificationTime()
187 return localResource.lastModified();
190 public void spool( OutputContext outputContext )
193 if ( !isCollection() )
195 outputContext.setContentLength( localResource.length() );
196 outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
199 if ( !isCollection() && outputContext.hasStream() )
201 FileInputStream is = null;
204 // Write content to stream
205 is = new FileInputStream( localResource );
206 IOUtils.copy( is, outputContext.getOutputStream() );
210 IOUtils.closeQuietly( is );
213 else if ( outputContext.hasStream() )
215 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
216 writer.write( outputContext );
220 public DavPropertyName[] getPropertyNames()
222 return getProperties().getPropertyNames();
225 public DavProperty getProperty( DavPropertyName name )
227 return getProperties().get( name );
230 public DavPropertySet getProperties()
232 return initProperties();
235 public void setProperty( DavProperty property )
240 public void removeProperty( DavPropertyName propertyName )
245 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
251 @SuppressWarnings ("unchecked")
252 public MultiStatusResponse alterProperties( List changeList )
258 public DavResource getCollection()
260 DavResource parent = null;
261 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
263 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
264 if ( parentPath.equals( "" ) )
268 DavResourceLocator parentloc =
269 locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
272 parent = factory.createResource( parentloc, session );
274 catch ( DavException e )
282 public void addMember( DavResource resource, InputContext inputContext )
285 File localFile = new File( localResource, resource.getDisplayName() );
286 boolean exists = localFile.exists();
288 if ( isCollection() && inputContext.hasStream() ) // New File
290 FileOutputStream stream = null;
293 stream = new FileOutputStream( localFile );
294 IOUtils.copy( inputContext.getInputStream(), stream );
296 catch ( IOException e )
298 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
302 IOUtils.closeQuietly( stream );
305 // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
306 long expectedContentLength = inputContext.getContentLength();
307 long actualContentLength = localFile.length();
308 // length of -1 is given for a chunked request or unknown length, in which case we accept what was uploaded
309 if ( expectedContentLength >= 0 && expectedContentLength != actualContentLength )
311 String msg = "Content Header length was " + expectedContentLength + " but was " + actualContentLength;
312 log.debug( "Upload failed: {}", msg );
314 FileUtils.deleteQuietly( localFile );
315 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
318 queueRepositoryTask( localFile );
320 log.debug( "File '{}{}(current user '{}')", resource.getDisplayName(),
321 ( exists ? "' modified " : "' created " ), this.principal );
323 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
325 else if ( !inputContext.hasStream() && isCollection() ) // New directory
329 log.debug( "Directory '{}' (current user '{}')", resource.getDisplayName(), this.principal );
331 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
335 String msg = "Could not write member " + resource.getResourcePath() + " at " + getResourcePath()
336 + " as this is not a DAV collection";
338 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
342 public DavResourceIterator getMembers()
344 List<DavResource> list = new ArrayList<DavResource>();
345 if ( exists() && isCollection() )
347 for ( String item : localResource.list() )
351 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
353 String path = locator.getResourcePath() + '/' + item;
354 DavResourceLocator resourceLocator =
355 locator.getFactory().createResourceLocator( locator.getPrefix(), path );
356 DavResource resource = factory.createResource( resourceLocator, session );
358 if ( resource != null )
360 list.add( resource );
362 log.debug( "Resource '{}' retrieved by '{}'", item, this.principal );
365 catch ( DavException e )
371 return new DavResourceIteratorImpl( list );
374 public void removeMember( DavResource member )
377 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
379 if ( resource.exists() )
383 if ( resource.isDirectory() )
385 if ( !FileUtils.deleteQuietly( resource ) )
387 throw new IOException( "Could not remove directory" );
390 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
394 if ( !resource.delete() )
396 throw new IOException( "Could not remove file" );
399 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
402 log.debug( "{}{}' removed (current user '{}')", ( resource.isDirectory() ? "Directory '" : "File '" ),
403 member.getDisplayName(), this.principal );
406 catch ( IOException e )
408 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
413 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
417 private void triggerAuditEvent( DavResource member, String event )
420 String path = logicalResource + "/" + member.getDisplayName();
422 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( member );
423 AuditEvent auditEvent = new AuditEvent( locator.getRepositoryId(), resource.principal, path, event );
424 auditEvent.setRemoteIP( resource.remoteAddr );
426 for ( AuditListener listener : auditListeners )
428 listener.auditEvent( auditEvent );
432 public void move( DavResource destination )
437 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
442 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
443 if ( isCollection() )
445 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
447 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
451 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
453 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
456 log.debug( "{}{}' moved to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
457 getLocalResource().getName(), destination, this.principal );
460 catch ( IOException e )
462 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
466 public void copy( DavResource destination, boolean shallow )
471 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
474 if ( shallow && isCollection() )
476 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
481 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
482 if ( isCollection() )
484 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
486 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
490 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
492 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
495 log.debug( "{}{}' copied to '{}' (current user '{)')", ( isCollection() ? "Directory '" : "File '" ),
496 getLocalResource().getName(), destination, this.principal );
499 catch ( IOException e )
501 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
505 public boolean isLockable( Type type, Scope scope )
507 return Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope );
510 public boolean hasLock( Type type, Scope scope )
512 return getLock( type, scope ) != null;
515 public ActiveLock getLock( Type type, Scope scope )
517 ActiveLock lock = null;
518 if ( exists() && Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope ) )
520 lock = lockManager.getLock( type, scope, this );
525 public ActiveLock[] getLocks()
527 ActiveLock writeLock = getLock( Type.WRITE, Scope.EXCLUSIVE );
528 return ( writeLock != null ) ? new ActiveLock[]{ writeLock } : new ActiveLock[0];
531 public ActiveLock lock( LockInfo lockInfo )
534 ActiveLock lock = null;
535 if ( isLockable( lockInfo.getType(), lockInfo.getScope() ) )
537 lock = lockManager.createLock( lockInfo, this );
541 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope." );
546 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
551 throw new DavException( DavServletResponse.SC_NOT_FOUND );
553 ActiveLock lock = getLock( lockInfo.getType(), lockInfo.getScope() );
556 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED,
557 "No lock with the given type/scope present on resource " + getResourcePath() );
560 lock = lockManager.refreshLock( lockInfo, lockToken, this );
565 public void unlock( String lockToken )
568 ActiveLock lock = getLock( Type.WRITE, Scope.EXCLUSIVE );
571 throw new DavException( HttpServletResponse.SC_PRECONDITION_FAILED );
573 else if ( lock.isLockedByToken( lockToken ) )
575 lockManager.releaseLock( lockToken, this );
579 throw new DavException( DavServletResponse.SC_LOCKED );
583 public void addLockManager( LockManager lockManager )
585 this.lockManager = lockManager;
588 public DavResourceFactory getFactory()
593 public DavSession getSession()
599 * Fill the set of properties
601 protected DavPropertySet initProperties()
605 properties = new DavPropertySet();
608 if ( properties != null )
613 DavPropertySet properties = new DavPropertySet();
615 // set (or reset) fundamental properties
616 if ( getDisplayName() != null )
618 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
620 if ( isCollection() )
622 properties.add( new ResourceType( ResourceType.COLLECTION ) );
623 // Windows XP support
624 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
628 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
630 // Windows XP support
631 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
634 // Need to get the ISO8601 date for properties
635 DateTime dt = new DateTime( localResource.lastModified() );
636 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
637 String modifiedDate = fmt.print( dt );
639 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
641 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
643 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
645 this.properties = properties;
650 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
653 if ( !( resource instanceof ArchivaDavResource ) )
655 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
656 "DavResource is not instance of ArchivaDavResource" );
658 return (ArchivaDavResource) resource;
661 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
663 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
664 event.setRemoteIP( remoteIP );
666 for ( AuditListener listener : auditListeners )
668 listener.auditEvent( event );
672 private void queueRepositoryTask( File localFile )
674 RepositoryTask task = new RepositoryTask();
675 task.setRepositoryId( repository.getId() );
676 task.setResourceFile( localFile );
677 task.setUpdateRelatedArtifacts( false );
678 task.setScanAll( false );
682 scheduler.queueTask( task );
684 catch ( TaskQueueException e )
686 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()