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.audit.AuditEvent;
23 import org.apache.archiva.audit.AuditListener;
24 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
25 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
26 import org.apache.archiva.scheduler.repository.RepositoryTask;
27 import org.apache.commons.io.FileUtils;
28 import org.apache.commons.io.IOUtils;
29 import org.apache.jackrabbit.util.Text;
30 import org.apache.jackrabbit.webdav.DavException;
31 import org.apache.jackrabbit.webdav.DavResource;
32 import org.apache.jackrabbit.webdav.DavResourceFactory;
33 import org.apache.jackrabbit.webdav.DavResourceIterator;
34 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
35 import org.apache.jackrabbit.webdav.DavResourceLocator;
36 import org.apache.jackrabbit.webdav.DavServletResponse;
37 import org.apache.jackrabbit.webdav.DavSession;
38 import org.apache.jackrabbit.webdav.MultiStatusResponse;
39 import org.apache.jackrabbit.webdav.io.InputContext;
40 import org.apache.jackrabbit.webdav.io.OutputContext;
41 import org.apache.jackrabbit.webdav.lock.ActiveLock;
42 import org.apache.jackrabbit.webdav.lock.LockInfo;
43 import org.apache.jackrabbit.webdav.lock.LockManager;
44 import org.apache.jackrabbit.webdav.lock.Scope;
45 import org.apache.jackrabbit.webdav.lock.Type;
46 import org.apache.jackrabbit.webdav.property.DavProperty;
47 import org.apache.jackrabbit.webdav.property.DavPropertyName;
48 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
49 import org.apache.jackrabbit.webdav.property.DavPropertySet;
50 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
51 import org.apache.jackrabbit.webdav.property.ResourceType;
52 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
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 if ( !FileUtils.deleteQuietly( resource ) )
389 throw new IOException( "Could not remove directory" );
392 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
396 if ( !resource.delete() )
398 throw new IOException( "Could not remove file" );
401 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
403 log.debug( ( resource.isDirectory() ? "Directory '" : "File '" ) + member.getDisplayName() +
404 "' removed (current user '" + 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( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' moved to '" +
457 destination + "' (current user '" + this.principal + "')" );
459 catch ( IOException e )
461 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
465 public void copy( DavResource destination, boolean shallow )
470 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
473 if ( shallow && isCollection() )
475 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
480 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
481 if ( isCollection() )
483 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
485 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
489 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
491 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
493 log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' copied to '" +
494 destination + "' (current user '" + this.principal + "')" );
496 catch ( IOException e )
498 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
502 public boolean isLockable( Type type, Scope scope )
504 return Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope );
507 public boolean hasLock( Type type, Scope scope )
509 return getLock( type, scope ) != null;
512 public ActiveLock getLock( Type type, Scope scope )
514 ActiveLock lock = null;
515 if ( exists() && Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope ) )
517 lock = lockManager.getLock( type, scope, this );
522 public ActiveLock[] getLocks()
524 ActiveLock writeLock = getLock( Type.WRITE, Scope.EXCLUSIVE );
525 return ( writeLock != null ) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
528 public ActiveLock lock( LockInfo lockInfo )
531 ActiveLock lock = null;
532 if ( isLockable( lockInfo.getType(), lockInfo.getScope() ) )
534 lock = lockManager.createLock( lockInfo, this );
538 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope." );
543 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
548 throw new DavException( DavServletResponse.SC_NOT_FOUND );
550 ActiveLock lock = getLock( lockInfo.getType(), lockInfo.getScope() );
553 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED,
554 "No lock with the given type/scope present on resource " + getResourcePath() );
557 lock = lockManager.refreshLock( lockInfo, lockToken, this );
562 public void unlock( String lockToken )
565 ActiveLock lock = getLock( Type.WRITE, Scope.EXCLUSIVE );
568 throw new DavException( HttpServletResponse.SC_PRECONDITION_FAILED );
570 else if ( lock.isLockedByToken( lockToken ) )
572 lockManager.releaseLock( lockToken, this );
576 throw new DavException( DavServletResponse.SC_LOCKED );
580 public void addLockManager( LockManager lockManager )
582 this.lockManager = lockManager;
585 public DavResourceFactory getFactory()
590 public DavSession getSession()
596 * Fill the set of properties
598 protected DavPropertySet initProperties()
602 properties = new DavPropertySet();
605 if ( properties != null )
610 DavPropertySet properties = new DavPropertySet();
612 // set (or reset) fundamental properties
613 if ( getDisplayName() != null )
615 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
617 if ( isCollection() )
619 properties.add( new ResourceType( ResourceType.COLLECTION ) );
620 // Windows XP support
621 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
625 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
627 // Windows XP support
628 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
631 // Need to get the ISO8601 date for properties
632 DateTime dt = new DateTime( localResource.lastModified() );
633 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
634 String modifiedDate = fmt.print( dt );
636 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
638 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
640 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
642 this.properties = properties;
647 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
650 if ( !( resource instanceof ArchivaDavResource ) )
652 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
653 "DavResource is not instance of ArchivaDavResource" );
655 return (ArchivaDavResource) resource;
658 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
660 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
661 event.setRemoteIP( remoteIP );
663 for ( AuditListener listener : auditListeners )
665 listener.auditEvent( event );
669 private void queueRepositoryTask( File localFile )
671 RepositoryTask task = new RepositoryTask();
672 task.setRepositoryId( repository.getId() );
673 task.setResourceFile( localFile );
674 task.setUpdateRelatedArtifacts( false );
675 task.setScanAll( true );
679 scheduler.queueTask( task );
681 catch ( TaskQueueException e )
684 "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName() +