1 package org.apache.maven.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.scheduler.ArchivaTaskScheduler;
23 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
24 import org.apache.archiva.scheduler.repository.RepositoryTask;
25 import org.apache.commons.io.FileUtils;
26 import org.apache.commons.io.IOUtils;
27 import org.apache.jackrabbit.util.Text;
28 import org.apache.jackrabbit.webdav.DavException;
29 import org.apache.jackrabbit.webdav.DavResource;
30 import org.apache.jackrabbit.webdav.DavResourceFactory;
31 import org.apache.jackrabbit.webdav.DavResourceIterator;
32 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
33 import org.apache.jackrabbit.webdav.DavResourceLocator;
34 import org.apache.jackrabbit.webdav.DavServletResponse;
35 import org.apache.jackrabbit.webdav.DavSession;
36 import org.apache.jackrabbit.webdav.MultiStatusResponse;
37 import org.apache.jackrabbit.webdav.io.InputContext;
38 import org.apache.jackrabbit.webdav.io.OutputContext;
39 import org.apache.jackrabbit.webdav.lock.ActiveLock;
40 import org.apache.jackrabbit.webdav.lock.LockInfo;
41 import org.apache.jackrabbit.webdav.lock.LockManager;
42 import org.apache.jackrabbit.webdav.lock.Scope;
43 import org.apache.jackrabbit.webdav.lock.Type;
44 import org.apache.jackrabbit.webdav.property.DavProperty;
45 import org.apache.jackrabbit.webdav.property.DavPropertyName;
46 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
47 import org.apache.jackrabbit.webdav.property.DavPropertySet;
48 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
49 import org.apache.jackrabbit.webdav.property.ResourceType;
50 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
51 import org.apache.maven.archiva.repository.audit.AuditEvent;
52 import org.apache.maven.archiva.repository.audit.AuditListener;
53 import org.apache.maven.archiva.webdav.util.IndexWriter;
54 import org.apache.maven.archiva.webdav.util.MimeTypes;
55 import org.codehaus.plexus.taskqueue.TaskQueueException;
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;
63 import java.io.FileInputStream;
64 import java.io.FileOutputStream;
65 import java.io.IOException;
66 import java.util.ArrayList;
67 import java.util.List;
68 import javax.servlet.http.HttpServletResponse;
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 ManagedRepositoryConfiguration 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, ManagedRepositoryConfiguration 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, ManagedRepositoryConfiguration 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 = locator.getFactory().createResourceLocator( locator.getPrefix(),
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 )
312 "Content Header length was " + expectedContentLength + " but was " + actualContentLength;
313 log.debug( "Upload failed: " + msg );
315 FileUtils.deleteQuietly( localFile );
316 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
319 queueRepositoryTask( localFile );
322 "File '" + resource.getDisplayName() + ( exists ? "' modified " : "' created " ) + "(current user '" +
323 this.principal + "')" );
325 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
327 else if ( !inputContext.hasStream() && isCollection() ) // New directory
331 log.debug( "Directory '" + resource.getDisplayName() + "' (current user '" + this.principal + "')" );
333 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
337 String msg = "Could not write member " + resource.getResourcePath() + " at " + getResourcePath() +
338 " as this is not a DAV collection";
340 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
344 public DavResourceIterator getMembers()
346 List<DavResource> list = new ArrayList<DavResource>();
347 if ( exists() && isCollection() )
349 for ( String item : localResource.list() )
353 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
355 String path = locator.getResourcePath() + '/' + item;
356 DavResourceLocator resourceLocator = locator.getFactory().createResourceLocator(
357 locator.getPrefix(), path );
358 DavResource resource = factory.createResource( resourceLocator, session );
360 if ( resource != null )
362 list.add( resource );
364 log.debug( "Resource '" + item + "' retrieved by '" + this.principal + "'" );
367 catch ( DavException e )
373 return new DavResourceIteratorImpl( list );
376 public void removeMember( DavResource member )
379 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
381 if ( resource.exists() )
385 if ( resource.isDirectory() )
387 FileUtils.deleteDirectory( resource );
389 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
393 if ( !resource.delete() )
395 throw new IOException( "Could not remove file" );
398 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
400 log.debug( ( resource.isDirectory() ? "Directory '" : "File '" ) + member.getDisplayName() +
401 "' removed (current user '" + this.principal + "')" );
403 catch ( IOException e )
405 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
410 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
414 private void triggerAuditEvent( DavResource member, String event )
417 String path = logicalResource + "/" + member.getDisplayName();
419 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( member );
420 AuditEvent auditEvent = new AuditEvent( locator.getRepositoryId(), resource.principal, path, event );
421 auditEvent.setRemoteIP( resource.remoteAddr );
423 for ( AuditListener listener : auditListeners )
425 listener.auditEvent( auditEvent );
429 public void move( DavResource destination )
434 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
439 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
440 if ( isCollection() )
442 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
444 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
448 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
450 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
453 log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' moved to '" +
454 destination + "' (current user '" + this.principal + "')" );
456 catch ( IOException e )
458 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
462 public void copy( DavResource destination, boolean shallow )
467 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
470 if ( shallow && isCollection() )
472 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
477 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
478 if ( isCollection() )
480 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
482 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
486 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
488 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
490 log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' copied to '" +
491 destination + "' (current user '" + this.principal + "')" );
493 catch ( IOException e )
495 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
499 public boolean isLockable( Type type, Scope scope )
501 return Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope );
504 public boolean hasLock( Type type, Scope scope )
506 return getLock( type, scope ) != null;
509 public ActiveLock getLock( Type type, Scope scope )
511 ActiveLock lock = null;
512 if ( exists() && Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope ) )
514 lock = lockManager.getLock( type, scope, this );
519 public ActiveLock[] getLocks()
521 ActiveLock writeLock = getLock( Type.WRITE, Scope.EXCLUSIVE );
522 return ( writeLock != null ) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
525 public ActiveLock lock( LockInfo lockInfo )
528 ActiveLock lock = null;
529 if ( isLockable( lockInfo.getType(), lockInfo.getScope() ) )
531 lock = lockManager.createLock( lockInfo, this );
535 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope." );
540 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
545 throw new DavException( DavServletResponse.SC_NOT_FOUND );
547 ActiveLock lock = getLock( lockInfo.getType(), lockInfo.getScope() );
550 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED,
551 "No lock with the given type/scope present on resource " + getResourcePath() );
554 lock = lockManager.refreshLock( lockInfo, lockToken, this );
559 public void unlock( String lockToken )
562 ActiveLock lock = getLock( Type.WRITE, Scope.EXCLUSIVE );
565 throw new DavException( HttpServletResponse.SC_PRECONDITION_FAILED );
567 else if ( lock.isLockedByToken( lockToken ) )
569 lockManager.releaseLock( lockToken, this );
573 throw new DavException( DavServletResponse.SC_LOCKED );
577 public void addLockManager( LockManager lockManager )
579 this.lockManager = lockManager;
582 public DavResourceFactory getFactory()
587 public DavSession getSession()
593 * Fill the set of properties
595 protected DavPropertySet initProperties()
599 properties = new DavPropertySet();
602 if ( properties != null )
607 DavPropertySet properties = new DavPropertySet();
609 // set (or reset) fundamental properties
610 if ( getDisplayName() != null )
612 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
614 if ( isCollection() )
616 properties.add( new ResourceType( ResourceType.COLLECTION ) );
617 // Windows XP support
618 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
622 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
624 // Windows XP support
625 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
628 // Need to get the ISO8601 date for properties
629 DateTime dt = new DateTime( localResource.lastModified() );
630 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
631 String modifiedDate = fmt.print( dt );
633 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
635 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
637 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
639 this.properties = properties;
644 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
647 if ( !( resource instanceof ArchivaDavResource ) )
649 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
650 "DavResource is not instance of ArchivaDavResource" );
652 return (ArchivaDavResource) resource;
655 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
657 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
658 event.setRemoteIP( remoteIP );
660 for ( AuditListener listener : auditListeners )
662 listener.auditEvent( event );
666 private void queueRepositoryTask( File localFile )
668 RepositoryTask task = new RepositoryTask();
669 task.setRepositoryId( repository.getId() );
670 task.setResourceFile( localFile );
671 task.setUpdateRelatedArtifacts( false );
672 task.setScanAll( true );
676 scheduler.queueTask( task );
678 catch ( TaskQueueException e )
681 "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName() +