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.common.ArchivaException;
57 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
58 import org.apache.maven.archiva.repository.audit.AuditEvent;
59 import org.apache.maven.archiva.repository.audit.AuditListener;
60 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
61 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
62 import org.apache.maven.archiva.scheduled.DefaultArchivaTaskScheduler;
63 import org.apache.maven.archiva.scheduled.executors.ArchivaRepositoryScanningTaskExecutor;
64 import org.apache.maven.archiva.scheduled.tasks.ArchivaTask;
65 import org.apache.maven.archiva.scheduled.tasks.RepositoryTask;
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.codehaus.plexus.taskqueue.execution.TaskExecutor;
70 import org.joda.time.DateTime;
71 import org.joda.time.format.DateTimeFormatter;
72 import org.joda.time.format.ISODateTimeFormat;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
78 public class ArchivaDavResource
79 implements DavResource
81 public static final String HIDDEN_PATH_PREFIX = ".";
83 private final ArchivaDavResourceLocator locator;
85 private final DavResourceFactory factory;
87 private final File localResource;
89 private final String logicalResource;
91 private DavPropertySet properties = null;
93 private LockManager lockManager;
95 private final DavSession session;
97 private String remoteAddr;
99 private final ManagedRepositoryConfiguration repository;
101 private final RepositoryContentConsumers consumers;
103 private final MimeTypes mimeTypes;
105 private List<AuditListener> auditListeners;
107 private String principal;
109 public static final String COMPLIANCE_CLASS = "1, 2";
111 private ArchivaTaskScheduler scheduler;
113 private ArchivaRepositoryScanningTaskExecutor taskExecutor;
115 private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
117 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
118 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
119 MimeTypes mimeTypes, List<AuditListener> auditListeners,
120 RepositoryContentConsumers consumers, ArchivaTaskScheduler scheduler, TaskExecutor taskExecutor )
122 this.localResource = new File( localResource );
123 this.logicalResource = logicalResource;
124 this.locator = locator;
125 this.factory = factory;
126 this.session = session;
128 // TODO: push into locator as well as moving any references out of the resource factory
129 this.repository = repository;
131 // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
132 this.mimeTypes = mimeTypes;
133 this.consumers = consumers;
134 this.auditListeners = auditListeners;
135 this.scheduler = scheduler;
136 this.taskExecutor = ( ArchivaRepositoryScanningTaskExecutor ) taskExecutor;
139 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
140 String remoteAddr, String principal, DavSession session, ArchivaDavResourceLocator locator,
141 DavResourceFactory factory, MimeTypes mimeTypes, List<AuditListener> auditListeners,
142 RepositoryContentConsumers consumers, ArchivaTaskScheduler scheduler, TaskExecutor taskExecutor )
144 this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
145 consumers, scheduler, taskExecutor );
147 this.remoteAddr = remoteAddr;
148 this.principal = principal;
151 public String getComplianceClass()
153 return COMPLIANCE_CLASS;
156 public String getSupportedMethods()
161 public boolean exists()
163 return localResource.exists();
166 public boolean isCollection()
168 return localResource.isDirectory();
171 public String getDisplayName()
173 String resPath = getResourcePath();
174 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
177 public DavResourceLocator getLocator()
182 public File getLocalResource()
184 return localResource;
187 public String getResourcePath()
189 return locator.getResourcePath();
192 public String getHref()
194 return locator.getHref( isCollection() );
197 public long getModificationTime()
199 return localResource.lastModified();
202 public void spool( OutputContext outputContext )
205 if ( !isCollection())
207 outputContext.setContentLength( localResource.length() );
208 outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
211 if ( !isCollection() && outputContext.hasStream() )
213 FileInputStream is = null;
216 // Write content to stream
217 is = new FileInputStream( localResource );
218 IOUtils.copy( is, outputContext.getOutputStream() );
222 IOUtils.closeQuietly( is );
225 else if (outputContext.hasStream())
227 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
228 writer.write( outputContext );
232 public DavPropertyName[] getPropertyNames()
234 return getProperties().getPropertyNames();
237 public DavProperty getProperty( DavPropertyName name )
239 return getProperties().get( name );
242 public DavPropertySet getProperties()
244 return initProperties();
247 public void setProperty( DavProperty property )
252 public void removeProperty( DavPropertyName propertyName )
257 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
263 @SuppressWarnings("unchecked")
264 public MultiStatusResponse alterProperties( List changeList )
270 public DavResource getCollection()
272 DavResource parent = null;
273 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
275 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
276 if ( parentPath.equals( "" ) )
280 DavResourceLocator parentloc = locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
283 parent = factory.createResource( parentloc, session );
285 catch ( DavException e )
293 public void addMember( DavResource resource, InputContext inputContext )
296 File localFile = new File( localResource, resource.getDisplayName() );
297 boolean exists = localFile.exists();
299 if ( isCollection() && inputContext.hasStream() ) // New File
301 FileOutputStream stream = null;
304 stream = new FileOutputStream( localFile );
305 IOUtils.copy( inputContext.getInputStream(), stream );
307 catch ( IOException e )
309 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
313 IOUtils.closeQuietly( stream );
316 if ( inputContext.getContentLength() != localFile.length() )
318 FileUtils.deleteQuietly( localFile );
320 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Content Header length was " +
321 inputContext.getContentLength() + " but was " + localFile.length() );
324 executeConsumers( localFile );
326 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
328 else if ( !inputContext.hasStream() && isCollection() ) // New directory
332 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
336 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Could not write member " +
337 resource.getResourcePath() + " at " + getResourcePath() );
341 public DavResourceIterator getMembers()
343 List<DavResource> list = new ArrayList<DavResource>();
344 if ( exists() && isCollection() )
346 for ( String item : localResource.list() )
350 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
352 String path = locator.getResourcePath() + '/' + item;
353 DavResourceLocator resourceLocator =
354 locator.getFactory().createResourceLocator( locator.getPrefix(), path );
355 DavResource resource = factory.createResource( resourceLocator, session );
356 if ( resource != null )
358 list.add( resource );
362 catch ( DavException e )
368 return new DavResourceIteratorImpl( list );
371 public void removeMember( DavResource member )
374 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
376 if ( resource.exists() )
380 if ( resource.isDirectory() )
382 FileUtils.deleteDirectory( resource );
384 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
388 if ( !resource.delete() )
390 throw new IOException( "Could not remove file" );
393 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
396 catch ( IOException e )
398 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
403 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
407 private void triggerAuditEvent( DavResource member, String event ) throws DavException
409 String path = logicalResource + "/" + member.getDisplayName();
411 triggerAuditEvent( checkDavResourceIsArchivaDavResource( member ).remoteAddr, locator.getRepositoryId(), path,
415 public void move( DavResource destination )
420 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
425 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
426 if ( isCollection() )
428 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
430 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
434 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
436 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
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 );
474 catch ( IOException e )
476 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
480 public boolean isLockable( Type type, Scope scope )
482 return Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope);
485 public boolean hasLock( Type type, Scope scope )
487 return getLock(type, scope) != null;
490 public ActiveLock getLock( Type type, Scope scope )
492 ActiveLock lock = null;
493 if (exists() && Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope))
495 lock = lockManager.getLock(type, scope, this);
500 public ActiveLock[] getLocks()
502 ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE);
503 return (writeLock != null) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
506 public ActiveLock lock( LockInfo lockInfo )
509 ActiveLock lock = null;
510 if (isLockable(lockInfo.getType(), lockInfo.getScope()))
512 lock = lockManager.createLock(lockInfo, this);
516 throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope.");
521 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
525 throw new DavException(DavServletResponse.SC_NOT_FOUND);
527 ActiveLock lock = getLock(lockInfo.getType(), lockInfo.getScope());
529 throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "No lock with the given type/scope present on resource " + getResourcePath());
532 lock = lockManager.refreshLock(lockInfo, lockToken, this);
537 public void unlock( String lockToken )
540 ActiveLock lock = getLock(Type.WRITE, Scope.EXCLUSIVE);
543 throw new DavException(HttpServletResponse.SC_PRECONDITION_FAILED);
545 else if (lock.isLockedByToken(lockToken))
547 lockManager.releaseLock(lockToken, this);
551 throw new DavException(DavServletResponse.SC_LOCKED);
555 public void addLockManager( LockManager lockManager )
557 this.lockManager = lockManager;
560 public DavResourceFactory getFactory()
565 public DavSession getSession()
571 * Fill the set of properties
573 protected DavPropertySet initProperties()
577 properties = new DavPropertySet();
580 if ( properties != null )
585 DavPropertySet properties = new DavPropertySet();
587 // set (or reset) fundamental properties
588 if ( getDisplayName() != null )
590 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
592 if ( isCollection() )
594 properties.add( new ResourceType( ResourceType.COLLECTION ) );
595 // Windows XP support
596 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
600 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
602 // Windows XP support
603 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
606 // Need to get the ISO8601 date for properties
607 DateTime dt = new DateTime( localResource.lastModified() );
608 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
609 String modifiedDate = fmt.print( dt );
611 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
613 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
615 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
617 this.properties = properties;
622 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
625 if ( !( resource instanceof ArchivaDavResource ) )
627 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
628 "DavResource is not instance of ArchivaDavResource" );
630 return (ArchivaDavResource) resource;
633 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
635 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
636 event.setRemoteIP( remoteIP );
638 for ( AuditListener listener : auditListeners )
640 listener.auditEvent( event );
644 private void executeConsumers( File localFile )
648 RepositoryTask currentTaskInExecution = ( RepositoryTask ) taskExecutor.getCurrentTaskInExecution();
649 if( currentTaskInExecution != null || scheduler.isProcessingAnyRepositoryTask() )
651 // check if the repository is already queued to be scanned
652 if( scheduler.isProcessingRepositoryTaskWithName( DefaultArchivaTaskScheduler.REPOSITORY_JOB + ":" + repository.getId() )
653 || scheduler.isProcessingRepositoryTaskWithName( DefaultArchivaTaskScheduler.REPOSITORY_JOB + ":" + repository.getId() + ":" + localFile.getName() ) )
655 // no need to execute the consumers since repo is already queued
661 RepositoryTask task = new RepositoryTask();
662 task.setRepositoryId( repository.getId() );
663 task.setName( DefaultArchivaTaskScheduler.REPOSITORY_JOB + ":" + repository.getId() + ":" + localFile.getName() );
664 task.setQueuePolicy( ArchivaTask.QUEUE_POLICY_WAIT );
665 task.setResourceFile( localFile );
669 scheduler.queueRepositoryTask( task );
671 catch ( TaskQueueException e )
673 log.error( "Unable to queue repository task to execute consumers on resource file ['" +
674 localFile.getName() + "']." );
680 // Just-in-time update of the index and database by executing the consumers for this artifact
681 consumers.executeConsumers( repository, localFile );
684 catch ( ArchivaException e )
686 log.error( "Unable to queue repository task to execute consumers on resource file ['" +
687 localFile.getName() + "']." );