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
23 import java.io.FileInputStream;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.List;
29 import javax.servlet.http.HttpServletResponse;
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.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
57 import org.apache.maven.archiva.repository.audit.AuditEvent;
58 import org.apache.maven.archiva.repository.audit.AuditListener;
59 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
60 import org.apache.maven.archiva.scheduled.tasks.RepositoryTask;
61 import org.apache.maven.archiva.scheduled.tasks.TaskCreator;
62 import org.apache.maven.archiva.webdav.util.IndexWriter;
63 import org.apache.maven.archiva.webdav.util.MimeTypes;
64 import org.codehaus.plexus.taskqueue.TaskQueueException;
65 import org.joda.time.DateTime;
66 import org.joda.time.format.DateTimeFormatter;
67 import org.joda.time.format.ISODateTimeFormat;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
73 public class ArchivaDavResource
74 implements DavResource
76 public static final String HIDDEN_PATH_PREFIX = ".";
78 private final ArchivaDavResourceLocator locator;
80 private final DavResourceFactory factory;
82 private final File localResource;
84 private final String logicalResource;
86 private DavPropertySet properties = null;
88 private LockManager lockManager;
90 private final DavSession session;
92 private String remoteAddr;
94 private final ManagedRepositoryConfiguration repository;
96 private final MimeTypes mimeTypes;
98 private List<AuditListener> auditListeners;
100 private String principal;
102 public static final String COMPLIANCE_CLASS = "1, 2";
104 private ArchivaTaskScheduler scheduler;
106 private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
108 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
109 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
110 MimeTypes mimeTypes, List<AuditListener> auditListeners,
111 ArchivaTaskScheduler scheduler )
113 this.localResource = new File( localResource );
114 this.logicalResource = logicalResource;
115 this.locator = locator;
116 this.factory = factory;
117 this.session = session;
119 // TODO: push into locator as well as moving any references out of the resource factory
120 this.repository = repository;
122 // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
123 this.mimeTypes = mimeTypes;
124 this.auditListeners = auditListeners;
125 this.scheduler = scheduler;
128 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
129 String remoteAddr, String principal, DavSession session, ArchivaDavResourceLocator locator,
130 DavResourceFactory factory, MimeTypes mimeTypes, List<AuditListener> auditListeners,
131 ArchivaTaskScheduler scheduler )
133 this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
136 this.remoteAddr = remoteAddr;
137 this.principal = principal;
140 public String getComplianceClass()
142 return COMPLIANCE_CLASS;
145 public String getSupportedMethods()
150 public boolean exists()
152 return localResource.exists();
155 public boolean isCollection()
157 return localResource.isDirectory();
160 public String getDisplayName()
162 String resPath = getResourcePath();
163 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
166 public DavResourceLocator getLocator()
171 public File getLocalResource()
173 return localResource;
176 public String getResourcePath()
178 return locator.getResourcePath();
181 public String getHref()
183 return locator.getHref( isCollection() );
186 public long getModificationTime()
188 return localResource.lastModified();
191 public void spool( OutputContext outputContext )
194 if ( !isCollection())
196 outputContext.setContentLength( localResource.length() );
197 outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
200 if ( !isCollection() && outputContext.hasStream() )
202 FileInputStream is = null;
205 // Write content to stream
206 is = new FileInputStream( localResource );
207 IOUtils.copy( is, outputContext.getOutputStream() );
211 IOUtils.closeQuietly( is );
214 else if (outputContext.hasStream())
216 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
217 writer.write( outputContext );
221 public DavPropertyName[] getPropertyNames()
223 return getProperties().getPropertyNames();
226 public DavProperty getProperty( DavPropertyName name )
228 return getProperties().get( name );
231 public DavPropertySet getProperties()
233 return initProperties();
236 public void setProperty( DavProperty property )
241 public void removeProperty( DavPropertyName propertyName )
246 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
252 @SuppressWarnings("unchecked")
253 public MultiStatusResponse alterProperties( List changeList )
259 public DavResource getCollection()
261 DavResource parent = null;
262 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
264 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
265 if ( parentPath.equals( "" ) )
269 DavResourceLocator parentloc = 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 if ( inputContext.getContentLength() != localFile.length() )
308 FileUtils.deleteQuietly( localFile );
310 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Content Header length was " +
311 inputContext.getContentLength() + " but was " + localFile.length() );
314 queueRepositoryTask( localFile );
316 log.debug( "File '" + resource.getDisplayName() + ( exists ? "' modified " : "' created ") + "(current user '" + this.principal + "')" );
318 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
320 else if ( !inputContext.hasStream() && isCollection() ) // New directory
324 log.debug( "Directory '" + resource.getDisplayName() + "' (current user '" + this.principal + "')" );
326 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
330 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Could not write member " +
331 resource.getResourcePath() + " at " + getResourcePath() );
335 public DavResourceIterator getMembers()
337 List<DavResource> list = new ArrayList<DavResource>();
338 if ( exists() && isCollection() )
340 for ( String item : localResource.list() )
344 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
346 String path = locator.getResourcePath() + '/' + item;
347 DavResourceLocator resourceLocator =
348 locator.getFactory().createResourceLocator( locator.getPrefix(), path );
349 DavResource resource = factory.createResource( resourceLocator, session );
351 if ( resource != null )
353 list.add( resource );
355 log.debug( "Resource '" + item + "' retrieved by '" + this.principal + "'" );
358 catch ( DavException e )
364 return new DavResourceIteratorImpl( list );
367 public void removeMember( DavResource member )
370 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
372 if ( resource.exists() )
376 if ( resource.isDirectory() )
378 FileUtils.deleteDirectory( resource );
380 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
384 if ( !resource.delete() )
386 throw new IOException( "Could not remove file" );
389 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
391 log.debug( ( resource.isDirectory() ? "Directory '" : "File '" ) + member.getDisplayName() + "' removed (current user '" + this.principal + "')" );
393 catch ( IOException e )
395 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
400 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
404 private void triggerAuditEvent( DavResource member, String event ) throws DavException
406 String path = logicalResource + "/" + member.getDisplayName();
408 triggerAuditEvent( checkDavResourceIsArchivaDavResource( member ).remoteAddr, locator.getRepositoryId(), path,
412 public void move( DavResource destination )
417 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
422 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
423 if ( isCollection() )
425 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
427 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
431 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
433 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
436 log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' moved to '" +
437 destination + "' (current user '" + this.principal + "')" );
439 catch ( IOException e )
441 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
445 public void copy( DavResource destination, boolean shallow )
450 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
453 if ( shallow && isCollection() )
455 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
460 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
461 if ( isCollection() )
463 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
465 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
469 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
471 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
473 log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' copied to '" +
474 destination + "' (current user '" + this.principal + "')" );
476 catch ( IOException e )
478 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
482 public boolean isLockable( Type type, Scope scope )
484 return Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope);
487 public boolean hasLock( Type type, Scope scope )
489 return getLock(type, scope) != null;
492 public ActiveLock getLock( Type type, Scope scope )
494 ActiveLock lock = null;
495 if (exists() && Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope))
497 lock = lockManager.getLock(type, scope, this);
502 public ActiveLock[] getLocks()
504 ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE);
505 return (writeLock != null) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
508 public ActiveLock lock( LockInfo lockInfo )
511 ActiveLock lock = null;
512 if (isLockable(lockInfo.getType(), lockInfo.getScope()))
514 lock = lockManager.createLock(lockInfo, this);
518 throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope.");
523 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
527 throw new DavException(DavServletResponse.SC_NOT_FOUND);
529 ActiveLock lock = getLock(lockInfo.getType(), lockInfo.getScope());
531 throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "No lock with the given type/scope present on resource " + getResourcePath());
534 lock = lockManager.refreshLock(lockInfo, lockToken, this);
539 public void unlock( String lockToken )
542 ActiveLock lock = getLock(Type.WRITE, Scope.EXCLUSIVE);
545 throw new DavException(HttpServletResponse.SC_PRECONDITION_FAILED);
547 else if (lock.isLockedByToken(lockToken))
549 lockManager.releaseLock(lockToken, this);
553 throw new DavException(DavServletResponse.SC_LOCKED);
557 public void addLockManager( LockManager lockManager )
559 this.lockManager = lockManager;
562 public DavResourceFactory getFactory()
567 public DavSession getSession()
573 * Fill the set of properties
575 protected DavPropertySet initProperties()
579 properties = new DavPropertySet();
582 if ( properties != null )
587 DavPropertySet properties = new DavPropertySet();
589 // set (or reset) fundamental properties
590 if ( getDisplayName() != null )
592 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
594 if ( isCollection() )
596 properties.add( new ResourceType( ResourceType.COLLECTION ) );
597 // Windows XP support
598 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
602 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
604 // Windows XP support
605 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
608 // Need to get the ISO8601 date for properties
609 DateTime dt = new DateTime( localResource.lastModified() );
610 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
611 String modifiedDate = fmt.print( dt );
613 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
615 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
617 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
619 this.properties = properties;
624 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
627 if ( !( resource instanceof ArchivaDavResource ) )
629 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
630 "DavResource is not instance of ArchivaDavResource" );
632 return (ArchivaDavResource) resource;
635 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
637 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
638 event.setRemoteIP( remoteIP );
640 for ( AuditListener listener : auditListeners )
642 listener.auditEvent( event );
646 private void queueRepositoryTask( File localFile )
648 RepositoryTask task = TaskCreator.createRepositoryTask( repository.getId(), localFile, false, true );
652 scheduler.queueRepositoryTask( task );
654 catch ( TaskQueueException e )
656 log.error( "Unable to queue repository task to execute consumers on resource file ['" +
657 localFile.getName() + "']." );