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.Calendar;
28 import java.util.List;
30 import javax.servlet.http.HttpServletResponse;
32 import org.apache.commons.io.FileUtils;
33 import org.apache.commons.io.IOUtils;
34 import org.apache.jackrabbit.util.Text;
35 import org.apache.jackrabbit.webdav.DavConstants;
36 import org.apache.jackrabbit.webdav.DavException;
37 import org.apache.jackrabbit.webdav.DavResource;
38 import org.apache.jackrabbit.webdav.DavResourceFactory;
39 import org.apache.jackrabbit.webdav.DavResourceIterator;
40 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
41 import org.apache.jackrabbit.webdav.DavResourceLocator;
42 import org.apache.jackrabbit.webdav.DavServletResponse;
43 import org.apache.jackrabbit.webdav.DavSession;
44 import org.apache.jackrabbit.webdav.MultiStatusResponse;
45 import org.apache.jackrabbit.webdav.io.InputContext;
46 import org.apache.jackrabbit.webdav.io.OutputContext;
47 import org.apache.jackrabbit.webdav.lock.ActiveLock;
48 import org.apache.jackrabbit.webdav.lock.LockInfo;
49 import org.apache.jackrabbit.webdav.lock.LockManager;
50 import org.apache.jackrabbit.webdav.lock.Scope;
51 import org.apache.jackrabbit.webdav.lock.Type;
52 import org.apache.jackrabbit.webdav.property.DavProperty;
53 import org.apache.jackrabbit.webdav.property.DavPropertyName;
54 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
55 import org.apache.jackrabbit.webdav.property.DavPropertySet;
56 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
57 import org.apache.jackrabbit.webdav.property.ResourceType;
58 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
59 import org.apache.maven.archiva.database.ArchivaAuditLogsDao;
60 import org.apache.maven.archiva.model.ArchivaAuditLogs;
61 import org.apache.maven.archiva.repository.audit.AuditEvent;
62 import org.apache.maven.archiva.repository.audit.AuditListener;
63 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
64 import org.apache.maven.archiva.scheduled.tasks.RepositoryTask;
65 import org.apache.maven.archiva.scheduled.tasks.TaskCreator;
66 import org.apache.maven.archiva.webdav.util.IndexWriter;
67 import org.apache.maven.archiva.webdav.util.MimeTypes;
68 import org.codehaus.plexus.taskqueue.TaskQueueException;
69 import org.joda.time.DateTime;
70 import org.joda.time.format.DateTimeFormatter;
71 import org.joda.time.format.ISODateTimeFormat;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
77 public class ArchivaDavResource
78 implements DavResource
80 public static final String HIDDEN_PATH_PREFIX = ".";
82 private final ArchivaDavResourceLocator locator;
84 private final DavResourceFactory factory;
86 private final File localResource;
88 private final String logicalResource;
90 private DavPropertySet properties = null;
92 private LockManager lockManager;
94 private final DavSession session;
96 private String remoteAddr;
98 private final ManagedRepositoryConfiguration repository;
100 private final MimeTypes mimeTypes;
102 private List<AuditListener> auditListeners;
104 private String principal;
106 public static final String COMPLIANCE_CLASS = "1, 2";
108 private ArchivaTaskScheduler scheduler;
110 private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
112 private ArchivaAuditLogsDao auditLogsDao;
114 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
115 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
116 MimeTypes mimeTypes, List<AuditListener> auditListeners,
117 ArchivaTaskScheduler scheduler, ArchivaAuditLogsDao auditLogsDao )
119 this.localResource = new File( localResource );
120 this.logicalResource = logicalResource;
121 this.locator = locator;
122 this.factory = factory;
123 this.session = session;
125 // TODO: push into locator as well as moving any references out of the resource factory
126 this.repository = repository;
128 // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
129 this.mimeTypes = mimeTypes;
130 this.auditListeners = auditListeners;
131 this.scheduler = scheduler;
132 this.auditLogsDao = auditLogsDao;
135 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
136 String remoteAddr, String principal, DavSession session, ArchivaDavResourceLocator locator,
137 DavResourceFactory factory, MimeTypes mimeTypes, List<AuditListener> auditListeners,
138 ArchivaTaskScheduler scheduler, ArchivaAuditLogsDao auditLogsDao )
140 this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
141 scheduler, auditLogsDao );
143 this.remoteAddr = remoteAddr;
144 this.principal = principal;
147 public String getComplianceClass()
149 return COMPLIANCE_CLASS;
152 public String getSupportedMethods()
157 public boolean exists()
159 return localResource.exists();
162 public boolean isCollection()
164 return localResource.isDirectory();
167 public String getDisplayName()
169 String resPath = getResourcePath();
170 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
173 public DavResourceLocator getLocator()
178 public File getLocalResource()
180 return localResource;
183 public String getResourcePath()
185 return locator.getResourcePath();
188 public String getHref()
190 return locator.getHref( isCollection() );
193 public long getModificationTime()
195 return localResource.lastModified();
198 public void spool( OutputContext outputContext )
201 if ( !isCollection() )
203 outputContext.setProperty( DavConstants.HEADER_CONTENT_LENGTH, Long.toString( localResource.length() ) );
204 outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
207 if ( !isCollection() && outputContext.hasStream() )
209 FileInputStream is = null;
212 // Write content to stream
213 is = new FileInputStream( localResource );
214 IOUtils.copy( is, outputContext.getOutputStream() );
218 IOUtils.closeQuietly( is );
221 else if ( outputContext.hasStream() )
223 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
224 writer.write( outputContext );
228 public DavPropertyName[] getPropertyNames()
230 return getProperties().getPropertyNames();
233 public DavProperty getProperty( DavPropertyName name )
235 return getProperties().get( name );
238 public DavPropertySet getProperties()
240 return initProperties();
243 public void setProperty( DavProperty property )
248 public void removeProperty( DavPropertyName propertyName )
253 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
259 @SuppressWarnings( "unchecked" )
260 public MultiStatusResponse alterProperties( List changeList )
266 public DavResource getCollection()
268 DavResource parent = null;
269 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
271 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
272 if ( parentPath.equals( "" ) )
276 DavResourceLocator parentloc = locator.getFactory().createResourceLocator( locator.getPrefix(),
280 parent = factory.createResource( parentloc, session );
282 catch ( DavException e )
290 public void addMember( DavResource resource, InputContext inputContext )
293 File localFile = new File( localResource, resource.getDisplayName() );
294 boolean exists = localFile.exists();
296 if ( isCollection() && inputContext.hasStream() ) // New File
298 FileOutputStream stream = null;
301 stream = new FileOutputStream( localFile );
302 IOUtils.copy( inputContext.getInputStream(), stream );
304 catch ( IOException e )
306 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
310 IOUtils.closeQuietly( stream );
313 // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
314 long expectedContentLength = Long.parseLong( inputContext.getProperty( DavConstants.HEADER_CONTENT_LENGTH ) );
315 long actualContentLength = localFile.length();
316 // length of -1 is given for a chunked request or unknown length, in which case we accept what was uploaded
317 if ( expectedContentLength >= 0 && expectedContentLength != actualContentLength )
320 "Content Header length was " + expectedContentLength + " but was " + actualContentLength;
321 log.debug( "Upload failed: " + msg );
323 FileUtils.deleteQuietly( localFile );
324 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
327 queueRepositoryTask( localFile );
330 "File '" + resource.getDisplayName() + ( exists ? "' modified " : "' created " ) + "(current user '" +
331 this.principal + "')" );
333 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
335 else if ( !inputContext.hasStream() && isCollection() ) // New directory
339 log.debug( "Directory '" + resource.getDisplayName() + "' (current user '" + this.principal + "')" );
341 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
345 String msg = "Could not write member " + resource.getResourcePath() + " at " + getResourcePath() +
346 " as this is not a DAV collection";
348 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
352 public DavResourceIterator getMembers()
354 List<DavResource> list = new ArrayList<DavResource>();
355 if ( exists() && isCollection() )
357 for ( String item : localResource.list() )
361 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
363 String path = locator.getResourcePath() + '/' + item;
364 DavResourceLocator resourceLocator = locator.getFactory().createResourceLocator(
365 locator.getPrefix(), path );
366 DavResource resource = factory.createResource( resourceLocator, session );
368 if ( resource != null )
370 list.add( resource );
372 log.debug( "Resource '" + item + "' retrieved by '" + this.principal + "'" );
375 catch ( DavException e )
381 return new DavResourceIteratorImpl( list );
384 public void removeMember( DavResource member )
387 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
389 if ( resource.exists() )
393 if ( resource.isDirectory() )
395 FileUtils.deleteDirectory( resource );
397 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
401 if ( !resource.delete() )
403 throw new IOException( "Could not remove file" );
406 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
408 log.debug( ( resource.isDirectory() ? "Directory '" : "File '" ) + member.getDisplayName() +
409 "' removed (current user '" + this.principal + "')" );
411 catch ( IOException e )
413 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
418 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
422 private void triggerAuditEvent( DavResource member, String event )
425 String path = logicalResource + "/" + member.getDisplayName();
427 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( member );
428 triggerAuditEvent( resource.remoteAddr, resource.principal, locator.getRepositoryId(), path,
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, principal, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
451 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
453 triggerAuditEvent( remoteAddr, principal, 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, principal, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
489 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
491 triggerAuditEvent( remoteAddr, principal, 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 principal, String repositoryId, String resource,
661 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
662 event.setRemoteIP( remoteIP );
664 for ( AuditListener listener : auditListeners )
666 listener.auditEvent( event );
669 // identify as artifact deployment/upload
670 if( action.equals( AuditEvent.CREATE_FILE ) )
672 action = AuditEvent.UPLOAD_FILE;
675 String user = principal;
676 if( principal == null )
681 ArchivaAuditLogs auditLogs = new ArchivaAuditLogs();
682 auditLogs.setArtifact( resource );
683 auditLogs.setEvent( action );
684 auditLogs.setEventDate( Calendar.getInstance().getTime() );
685 auditLogs.setRepositoryId( repositoryId );
686 auditLogs.setUsername( user );
688 auditLogsDao.saveAuditLogs( auditLogs );
691 private void queueRepositoryTask( File localFile )
693 RepositoryTask task = TaskCreator.createRepositoryTask( repository.getId(), localFile, false, true );
697 scheduler.queueRepositoryTask( task );
699 catch ( TaskQueueException e )
702 "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName() +