]> source.dussan.org Git - archiva.git/blob
113aba0e5cdd9f87c3c77d856ab78daa8fbb8e3d
[archiva.git] /
1 package org.apache.maven.archiva.webdav;
2
3 /*
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
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
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
19  * under the License.
20  */
21
22 import java.io.File;
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;
28
29 import javax.servlet.http.HttpServletResponse;
30
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;
70
71 /**
72  */
73 public class ArchivaDavResource
74     implements DavResource
75 {
76     public static final String HIDDEN_PATH_PREFIX = ".";
77
78     private final ArchivaDavResourceLocator locator;
79
80     private final DavResourceFactory factory;
81
82     private final File localResource;
83
84     private final String logicalResource;
85
86     private DavPropertySet properties = null;
87
88     private LockManager lockManager;
89     
90     private final DavSession session;
91     
92     private String remoteAddr;
93
94     private final ManagedRepositoryConfiguration repository;
95
96     private final MimeTypes mimeTypes;
97
98     private List<AuditListener> auditListeners;
99
100     private String principal;
101     
102     public static final String COMPLIANCE_CLASS = "1, 2";
103     
104     private ArchivaTaskScheduler scheduler;
105     
106     private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
107
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 )
112     {
113         this.localResource = new File( localResource ); 
114         this.logicalResource = logicalResource;
115         this.locator = locator;
116         this.factory = factory;
117         this.session = session;
118         
119         // TODO: push into locator as well as moving any references out of the resource factory
120         this.repository = repository;
121         
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;
126     }
127
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 )
132     {
133         this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
134               scheduler );
135
136         this.remoteAddr = remoteAddr;
137         this.principal = principal;
138     }
139
140     public String getComplianceClass()
141     {
142         return COMPLIANCE_CLASS;
143     }
144
145     public String getSupportedMethods()
146     {
147         return METHODS;
148     }
149
150     public boolean exists()
151     {
152         return localResource.exists();
153     }
154
155     public boolean isCollection()
156     {
157         return localResource.isDirectory();
158     }
159
160     public String getDisplayName()
161     {
162         String resPath = getResourcePath();
163         return ( resPath != null ) ? Text.getName( resPath ) : resPath;
164     }
165
166     public DavResourceLocator getLocator()
167     {
168         return locator;
169     }
170
171     public File getLocalResource()
172     {
173         return localResource;
174     }
175
176     public String getResourcePath()
177     {
178         return locator.getResourcePath();
179     }
180
181     public String getHref()
182     {
183         return locator.getHref( isCollection() );
184     }
185
186     public long getModificationTime()
187     {
188         return localResource.lastModified();
189     }
190
191     public void spool( OutputContext outputContext )
192         throws IOException
193     {
194         if ( !isCollection())
195         {
196             outputContext.setContentLength( localResource.length() );
197             outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
198         }
199         
200         if ( !isCollection() && outputContext.hasStream() )
201         {
202             FileInputStream is = null;
203             try
204             {
205                 // Write content to stream
206                 is = new FileInputStream( localResource );
207                 IOUtils.copy( is, outputContext.getOutputStream() );
208             }
209             finally
210             {
211                 IOUtils.closeQuietly( is );
212             }
213         }
214         else if (outputContext.hasStream())
215         {
216             IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
217             writer.write( outputContext );
218         }
219     }
220
221     public DavPropertyName[] getPropertyNames()
222     {
223         return getProperties().getPropertyNames();
224     }
225
226     public DavProperty getProperty( DavPropertyName name )
227     {
228         return getProperties().get( name );
229     }
230
231     public DavPropertySet getProperties()
232     {
233         return initProperties();
234     }
235
236     public void setProperty( DavProperty property )
237         throws DavException
238     {
239     }
240
241     public void removeProperty( DavPropertyName propertyName )
242         throws DavException
243     {
244     }
245
246     public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
247         throws DavException
248     {
249         return null;
250     }
251
252     @SuppressWarnings("unchecked")
253     public MultiStatusResponse alterProperties( List changeList )
254         throws DavException
255     {
256         return null;
257     }
258
259     public DavResource getCollection()
260     {
261         DavResource parent = null;
262         if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
263         {
264             String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
265             if ( parentPath.equals( "" ) )
266             {
267                 parentPath = "/";
268             }
269             DavResourceLocator parentloc = locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
270             try
271             {
272                 parent = factory.createResource( parentloc, session );
273             }
274             catch ( DavException e )
275             {
276                 // should not occur
277             }
278         }
279         return parent;
280     }
281
282     public void addMember( DavResource resource, InputContext inputContext )
283         throws DavException
284     {
285         File localFile = new File( localResource, resource.getDisplayName() );
286         boolean exists = localFile.exists();
287
288         if ( isCollection() && inputContext.hasStream() ) // New File
289         {
290             FileOutputStream stream = null;
291             try
292             {
293                 stream = new FileOutputStream( localFile );
294                 IOUtils.copy( inputContext.getInputStream(), stream );
295             }
296             catch ( IOException e )
297             {
298                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
299             }
300             finally
301             {
302                 IOUtils.closeQuietly( stream );
303             }
304             
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() )
307             {
308                 FileUtils.deleteQuietly( localFile );
309                 
310                 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Content Header length was " +
311                     inputContext.getContentLength() + " but was " + localFile.length() );
312             }
313             
314             queueRepositoryTask( localFile );           
315             
316             log.debug( "File '" + resource.getDisplayName() + ( exists ? "' modified " : "' created ") + "(current user '" + this.principal + "')" );
317             
318             triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
319         }
320         else if ( !inputContext.hasStream() && isCollection() ) // New directory
321         {
322             localFile.mkdir();
323             
324             log.debug( "Directory '" + resource.getDisplayName() + "' (current user '" + this.principal + "')" );
325             
326             triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
327         }
328         else
329         {            
330             throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Could not write member " +
331                 resource.getResourcePath() + " at " + getResourcePath() );
332         }
333     }
334
335     public DavResourceIterator getMembers()
336     {
337         List<DavResource> list = new ArrayList<DavResource>();
338         if ( exists() && isCollection() )
339         {
340             for ( String item : localResource.list() )
341             {
342                 try
343                 {
344                     if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
345                     {
346                         String path = locator.getResourcePath() + '/' + item;
347                         DavResourceLocator resourceLocator =
348                             locator.getFactory().createResourceLocator( locator.getPrefix(), path );
349                         DavResource resource = factory.createResource( resourceLocator, session );
350                         
351                         if ( resource != null )
352                         {
353                             list.add( resource );
354                         }
355                         log.debug( "Resource '" + item + "' retrieved by '" + this.principal + "'" );
356                     }
357                 }
358                 catch ( DavException e )
359                 {
360                     // Should not occur
361                 }
362             }
363         }
364         return new DavResourceIteratorImpl( list );
365     }
366
367     public void removeMember( DavResource member )
368         throws DavException
369     {
370         File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
371         
372         if ( resource.exists() )
373         {
374             try
375             {
376                 if ( resource.isDirectory() )
377                 {
378                     FileUtils.deleteDirectory( resource );
379
380                     triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
381                 }
382                 else
383                 {
384                     if ( !resource.delete() )
385                     {
386                         throw new IOException( "Could not remove file" );
387                     }
388
389                     triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
390                 }
391                 log.debug( ( resource.isDirectory() ? "Directory '" : "File '" ) + member.getDisplayName() + "' removed (current user '" + this.principal + "')" );
392             }
393             catch ( IOException e )
394             {
395                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
396             }
397         }
398         else
399         {
400             throw new DavException( HttpServletResponse.SC_NOT_FOUND );
401         }
402     }
403
404     private void triggerAuditEvent( DavResource member, String event ) throws DavException
405     {
406         String path = logicalResource + "/" + member.getDisplayName();
407         
408         triggerAuditEvent( checkDavResourceIsArchivaDavResource( member ).remoteAddr, locator.getRepositoryId(), path,
409                            event );
410     }
411
412     public void move( DavResource destination )
413         throws DavException
414     {
415         if ( !exists() )
416         {
417             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
418         }
419
420         try
421         {
422             ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
423             if ( isCollection() )
424             {
425                 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
426
427                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
428             }
429             else
430             {
431                 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
432
433                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
434             }
435             
436             log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' moved to '" +
437                            destination + "' (current user '" + this.principal + "')" );
438         }
439         catch ( IOException e )
440         {
441             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
442         }
443     }
444
445     public void copy( DavResource destination, boolean shallow )
446         throws DavException
447     {
448         if ( !exists() )
449         {
450             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
451         }
452
453         if ( shallow && isCollection() )
454         {
455             throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
456         }
457
458         try
459         {
460             ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
461             if ( isCollection() )
462             {
463                 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
464
465                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
466             }
467             else
468             {
469                 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
470
471                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
472             }
473             log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' copied to '" +
474                            destination + "' (current user '" + this.principal + "')" );
475         }
476         catch ( IOException e )
477         {
478             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
479         }
480     }
481
482     public boolean isLockable( Type type, Scope scope )
483     {
484         return Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope);
485     }
486
487     public boolean hasLock( Type type, Scope scope )
488     {
489         return getLock(type, scope) != null;
490     }
491
492     public ActiveLock getLock( Type type, Scope scope )
493     {
494         ActiveLock lock = null;
495         if (exists() && Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope)) 
496         {
497             lock = lockManager.getLock(type, scope, this);
498         }
499         return lock;
500     }
501
502     public ActiveLock[] getLocks()
503     {
504         ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE);
505         return (writeLock != null) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
506     }
507
508     public ActiveLock lock( LockInfo lockInfo )
509         throws DavException
510     {
511         ActiveLock lock = null;
512         if (isLockable(lockInfo.getType(), lockInfo.getScope())) 
513         {
514             lock = lockManager.createLock(lockInfo, this);
515         }
516         else 
517         {
518             throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope.");
519         }
520         return lock;
521     }
522
523     public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
524         throws DavException
525     {
526         if (!exists()) {
527             throw new DavException(DavServletResponse.SC_NOT_FOUND);
528         }
529         ActiveLock lock = getLock(lockInfo.getType(), lockInfo.getScope());
530         if (lock == null) {
531             throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "No lock with the given type/scope present on resource " + getResourcePath());
532         }
533
534         lock = lockManager.refreshLock(lockInfo, lockToken, this);
535
536         return lock;
537     }
538
539     public void unlock( String lockToken )
540         throws DavException
541     {
542         ActiveLock lock = getLock(Type.WRITE, Scope.EXCLUSIVE);
543         if (lock == null)
544         {
545             throw new DavException(HttpServletResponse.SC_PRECONDITION_FAILED);
546         }
547         else if (lock.isLockedByToken(lockToken))
548         {
549             lockManager.releaseLock(lockToken, this);
550         }
551         else
552         {
553             throw new DavException(DavServletResponse.SC_LOCKED);
554         }
555     }
556
557     public void addLockManager( LockManager lockManager )
558     {
559         this.lockManager = lockManager;
560     }
561
562     public DavResourceFactory getFactory()
563     {
564         return factory;
565     }
566
567     public DavSession getSession()
568     {
569         return session;
570     }
571
572     /**
573      * Fill the set of properties
574      */
575     protected DavPropertySet initProperties()
576     {
577         if ( !exists() )
578         {
579             properties = new DavPropertySet();
580         }
581         
582         if ( properties != null )
583         {
584             return properties;
585         }
586
587         DavPropertySet properties = new DavPropertySet();
588         
589         // set (or reset) fundamental properties
590         if ( getDisplayName() != null )
591         {
592             properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
593         }
594         if ( isCollection() )
595         {
596             properties.add( new ResourceType( ResourceType.COLLECTION ) );
597             // Windows XP support
598             properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
599         }
600         else
601         {
602             properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
603
604             // Windows XP support
605             properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
606         }
607
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 );
612
613         properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
614
615         properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
616
617         properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
618         
619         this.properties = properties;
620         
621         return properties;
622     }
623
624     private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
625         throws DavException
626     {
627         if ( !( resource instanceof ArchivaDavResource ) )
628         {
629             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
630                                     "DavResource is not instance of ArchivaDavResource" );
631         }
632         return (ArchivaDavResource) resource;
633     }
634
635     private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
636     {
637         AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
638         event.setRemoteIP( remoteIP );
639
640         for ( AuditListener listener : auditListeners )
641         {
642             listener.auditEvent( event );
643         }
644     }
645     
646     private void queueRepositoryTask( File localFile )
647     {        
648         RepositoryTask task = TaskCreator.createRepositoryTask( repository.getId(), localFile, false, true );
649         
650         try
651         {
652             scheduler.queueRepositoryTask( task );
653         }
654         catch ( TaskQueueException e )
655         {
656             log.error( "Unable to queue repository task to execute consumers on resource file ['" +
657                 localFile.getName() + "']." );
658         }
659     }
660 }