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.DavException;
36 import org.apache.jackrabbit.webdav.DavResource;
37 import org.apache.jackrabbit.webdav.DavResourceFactory;
38 import org.apache.jackrabbit.webdav.DavResourceIterator;
39 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
40 import org.apache.jackrabbit.webdav.DavResourceLocator;
41 import org.apache.jackrabbit.webdav.DavServletResponse;
42 import org.apache.jackrabbit.webdav.DavSession;
43 import org.apache.jackrabbit.webdav.MultiStatusResponse;
44 import org.apache.jackrabbit.webdav.io.InputContext;
45 import org.apache.jackrabbit.webdav.io.OutputContext;
46 import org.apache.jackrabbit.webdav.lock.ActiveLock;
47 import org.apache.jackrabbit.webdav.lock.LockInfo;
48 import org.apache.jackrabbit.webdav.lock.LockManager;
49 import org.apache.jackrabbit.webdav.lock.Scope;
50 import org.apache.jackrabbit.webdav.lock.Type;
51 import org.apache.jackrabbit.webdav.property.DavProperty;
52 import org.apache.jackrabbit.webdav.property.DavPropertyName;
53 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
54 import org.apache.jackrabbit.webdav.property.DavPropertySet;
55 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
56 import org.apache.jackrabbit.webdav.property.ResourceType;
57 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
58 import org.apache.maven.archiva.database.ArchivaAuditLogsDao;
59 import org.apache.maven.archiva.model.ArchivaAuditLogs;
60 import org.apache.maven.archiva.repository.audit.AuditEvent;
61 import org.apache.maven.archiva.repository.audit.AuditListener;
62 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
63 import org.apache.maven.archiva.scheduled.tasks.RepositoryTask;
64 import org.apache.maven.archiva.scheduled.tasks.TaskCreator;
65 import org.apache.maven.archiva.webdav.util.IndexWriter;
66 import org.apache.maven.archiva.webdav.util.MimeTypes;
67 import org.codehaus.plexus.taskqueue.TaskQueueException;
68 import org.joda.time.DateTime;
69 import org.joda.time.format.DateTimeFormatter;
70 import org.joda.time.format.ISODateTimeFormat;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
76 public class ArchivaDavResource
77 implements DavResource
79 public static final String HIDDEN_PATH_PREFIX = ".";
81 private final ArchivaDavResourceLocator locator;
83 private final DavResourceFactory factory;
85 private final File localResource;
87 private final String logicalResource;
89 private DavPropertySet properties = null;
91 private LockManager lockManager;
93 private final DavSession session;
95 private String remoteAddr;
97 private final ManagedRepositoryConfiguration repository;
99 private final MimeTypes mimeTypes;
101 private List<AuditListener> auditListeners;
103 private String principal;
105 public static final String COMPLIANCE_CLASS = "1, 2";
107 private ArchivaTaskScheduler scheduler;
109 private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
111 private ArchivaAuditLogsDao auditLogsDao;
113 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
114 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
115 MimeTypes mimeTypes, List<AuditListener> auditListeners,
116 ArchivaTaskScheduler scheduler, ArchivaAuditLogsDao auditLogsDao )
118 this.localResource = new File( localResource );
119 this.logicalResource = logicalResource;
120 this.locator = locator;
121 this.factory = factory;
122 this.session = session;
124 // TODO: push into locator as well as moving any references out of the resource factory
125 this.repository = repository;
127 // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
128 this.mimeTypes = mimeTypes;
129 this.auditListeners = auditListeners;
130 this.scheduler = scheduler;
131 this.auditLogsDao = auditLogsDao;
134 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
135 String remoteAddr, String principal, DavSession session, ArchivaDavResourceLocator locator,
136 DavResourceFactory factory, MimeTypes mimeTypes, List<AuditListener> auditListeners,
137 ArchivaTaskScheduler scheduler, ArchivaAuditLogsDao auditLogsDao )
139 this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
140 scheduler, auditLogsDao );
142 this.remoteAddr = remoteAddr;
143 this.principal = principal;
146 public String getComplianceClass()
148 return COMPLIANCE_CLASS;
151 public String getSupportedMethods()
156 public boolean exists()
158 return localResource.exists();
161 public boolean isCollection()
163 return localResource.isDirectory();
166 public String getDisplayName()
168 String resPath = getResourcePath();
169 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
172 public DavResourceLocator getLocator()
177 public File getLocalResource()
179 return localResource;
182 public String getResourcePath()
184 return locator.getResourcePath();
187 public String getHref()
189 return locator.getHref( isCollection() );
192 public long getModificationTime()
194 return localResource.lastModified();
197 public void spool( OutputContext outputContext )
200 if ( !isCollection())
202 outputContext.setContentLength( localResource.length() );
203 outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
206 if ( !isCollection() && outputContext.hasStream() )
208 FileInputStream is = null;
211 // Write content to stream
212 is = new FileInputStream( localResource );
213 IOUtils.copy( is, outputContext.getOutputStream() );
217 IOUtils.closeQuietly( is );
220 else if (outputContext.hasStream())
222 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
223 writer.write( outputContext );
227 public DavPropertyName[] getPropertyNames()
229 return getProperties().getPropertyNames();
232 public DavProperty getProperty( DavPropertyName name )
234 return getProperties().get( name );
237 public DavPropertySet getProperties()
239 return initProperties();
242 public void setProperty( DavProperty property )
247 public void removeProperty( DavPropertyName propertyName )
252 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
258 @SuppressWarnings("unchecked")
259 public MultiStatusResponse alterProperties( List changeList )
265 public DavResource getCollection()
267 DavResource parent = null;
268 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
270 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
271 if ( parentPath.equals( "" ) )
275 DavResourceLocator parentloc = locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
278 parent = factory.createResource( parentloc, session );
280 catch ( DavException e )
288 public void addMember( DavResource resource, InputContext inputContext )
291 File localFile = new File( localResource, resource.getDisplayName() );
292 boolean exists = localFile.exists();
294 if ( isCollection() && inputContext.hasStream() ) // New File
296 FileOutputStream stream = null;
299 stream = new FileOutputStream( localFile );
300 IOUtils.copy( inputContext.getInputStream(), stream );
302 catch ( IOException e )
304 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
308 IOUtils.closeQuietly( stream );
311 // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
312 if ( inputContext.getContentLength() != localFile.length() )
314 FileUtils.deleteQuietly( localFile );
316 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Content Header length was " +
317 inputContext.getContentLength() + " but was " + localFile.length() );
320 queueRepositoryTask( localFile );
322 log.debug( "File '" + resource.getDisplayName() + ( exists ? "' modified " : "' created ") + "(current user '" + this.principal + "')" );
324 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
326 else if ( !inputContext.hasStream() && isCollection() ) // New directory
330 log.debug( "Directory '" + resource.getDisplayName() + "' (current user '" + this.principal + "')" );
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 );
357 if ( resource != null )
359 list.add( resource );
361 log.debug( "Resource '" + item + "' retrieved by '" + this.principal + "'" );
364 catch ( DavException e )
370 return new DavResourceIteratorImpl( list );
373 public void removeMember( DavResource member )
376 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
378 if ( resource.exists() )
382 if ( resource.isDirectory() )
384 FileUtils.deleteDirectory( resource );
386 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
390 if ( !resource.delete() )
392 throw new IOException( "Could not remove file" );
395 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
397 log.debug( ( resource.isDirectory() ? "Directory '" : "File '" ) + member.getDisplayName() + "' removed (current user '" + this.principal + "')" );
399 catch ( IOException e )
401 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
406 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
410 private void triggerAuditEvent( DavResource member, String event ) throws DavException
412 String path = logicalResource + "/" + member.getDisplayName();
414 triggerAuditEvent( checkDavResourceIsArchivaDavResource( member ).remoteAddr, locator.getRepositoryId(), path,
418 public void move( DavResource destination )
423 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
428 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
429 if ( isCollection() )
431 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
433 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
437 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
439 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
442 log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' moved to '" +
443 destination + "' (current user '" + this.principal + "')" );
445 catch ( IOException e )
447 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
451 public void copy( DavResource destination, boolean shallow )
456 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
459 if ( shallow && isCollection() )
461 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
466 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
467 if ( isCollection() )
469 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
471 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
475 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
477 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
479 log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' copied to '" +
480 destination + "' (current user '" + this.principal + "')" );
482 catch ( IOException e )
484 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
488 public boolean isLockable( Type type, Scope scope )
490 return Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope);
493 public boolean hasLock( Type type, Scope scope )
495 return getLock(type, scope) != null;
498 public ActiveLock getLock( Type type, Scope scope )
500 ActiveLock lock = null;
501 if (exists() && Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope))
503 lock = lockManager.getLock(type, scope, this);
508 public ActiveLock[] getLocks()
510 ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE);
511 return (writeLock != null) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
514 public ActiveLock lock( LockInfo lockInfo )
517 ActiveLock lock = null;
518 if (isLockable(lockInfo.getType(), lockInfo.getScope()))
520 lock = lockManager.createLock(lockInfo, this);
524 throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope.");
529 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
533 throw new DavException(DavServletResponse.SC_NOT_FOUND);
535 ActiveLock lock = getLock(lockInfo.getType(), lockInfo.getScope());
537 throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "No lock with the given type/scope present on resource " + getResourcePath());
540 lock = lockManager.refreshLock(lockInfo, lockToken, this);
545 public void unlock( String lockToken )
548 ActiveLock lock = getLock(Type.WRITE, Scope.EXCLUSIVE);
551 throw new DavException(HttpServletResponse.SC_PRECONDITION_FAILED);
553 else if (lock.isLockedByToken(lockToken))
555 lockManager.releaseLock(lockToken, this);
559 throw new DavException(DavServletResponse.SC_LOCKED);
563 public void addLockManager( LockManager lockManager )
565 this.lockManager = lockManager;
568 public DavResourceFactory getFactory()
573 public DavSession getSession()
579 * Fill the set of properties
581 protected DavPropertySet initProperties()
585 properties = new DavPropertySet();
588 if ( properties != null )
593 DavPropertySet properties = new DavPropertySet();
595 // set (or reset) fundamental properties
596 if ( getDisplayName() != null )
598 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
600 if ( isCollection() )
602 properties.add( new ResourceType( ResourceType.COLLECTION ) );
603 // Windows XP support
604 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
608 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
610 // Windows XP support
611 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
614 // Need to get the ISO8601 date for properties
615 DateTime dt = new DateTime( localResource.lastModified() );
616 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
617 String modifiedDate = fmt.print( dt );
619 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
621 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
623 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
625 this.properties = properties;
630 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
633 if ( !( resource instanceof ArchivaDavResource ) )
635 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
636 "DavResource is not instance of ArchivaDavResource" );
638 return (ArchivaDavResource) resource;
641 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
643 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
644 event.setRemoteIP( remoteIP );
646 for ( AuditListener listener : auditListeners )
648 listener.auditEvent( event );
651 // identify as artifact deployment/upload
652 if( action.equals( AuditEvent.CREATE_FILE ) )
654 action = AuditEvent.UPLOAD_FILE;
657 String user = principal;
658 if( principal == null )
663 ArchivaAuditLogs auditLogs = new ArchivaAuditLogs();
664 auditLogs.setArtifact( resource );
665 auditLogs.setEvent( action );
666 auditLogs.setEventDate( Calendar.getInstance().getTime() );
667 auditLogs.setRepositoryId( repositoryId );
668 auditLogs.setUsername( user );
670 auditLogsDao.saveAuditLogs( auditLogs );
673 private void queueRepositoryTask( File localFile )
675 RepositoryTask task = TaskCreator.createRepositoryTask( repository.getId(), localFile, false, true );
679 scheduler.queueRepositoryTask( task );
681 catch ( TaskQueueException e )
683 log.error( "Unable to queue repository task to execute consumers on resource file ['" +
684 localFile.getName() + "']." );