]> source.dussan.org Git - archiva.git/blob
524de1be63ae4458689a14e1e5712d476f0dcc1f
[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             triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
317         }
318         else if ( !inputContext.hasStream() && isCollection() ) // New directory
319         {
320             localFile.mkdir();
321             
322             triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
323         }
324         else
325         {            
326             throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Could not write member " +
327                 resource.getResourcePath() + " at " + getResourcePath() );
328         }
329     }
330
331     public DavResourceIterator getMembers()
332     {
333         List<DavResource> list = new ArrayList<DavResource>();
334         if ( exists() && isCollection() )
335         {
336             for ( String item : localResource.list() )
337             {
338                 try
339                 {
340                     if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
341                     {
342                         String path = locator.getResourcePath() + '/' + item;
343                         DavResourceLocator resourceLocator =
344                             locator.getFactory().createResourceLocator( locator.getPrefix(), path );
345                         DavResource resource = factory.createResource( resourceLocator, session );
346                         if ( resource != null )
347                         {
348                             list.add( resource );
349                         }
350                     }
351                 }
352                 catch ( DavException e )
353                 {
354                     // Should not occur
355                 }
356             }
357         }
358         return new DavResourceIteratorImpl( list );
359     }
360
361     public void removeMember( DavResource member )
362         throws DavException
363     {
364         File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
365         
366         if ( resource.exists() )
367         {
368             try
369             {
370                 if ( resource.isDirectory() )
371                 {
372                     FileUtils.deleteDirectory( resource );
373
374                     triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
375                 }
376                 else
377                 {
378                     if ( !resource.delete() )
379                     {
380                         throw new IOException( "Could not remove file" );
381                     }
382
383                     triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
384                 }
385             }
386             catch ( IOException e )
387             {
388                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
389             }
390         }
391         else
392         {
393             throw new DavException( HttpServletResponse.SC_NOT_FOUND );
394         }
395     }
396
397     private void triggerAuditEvent( DavResource member, String event ) throws DavException
398     {
399         String path = logicalResource + "/" + member.getDisplayName();
400         
401         triggerAuditEvent( checkDavResourceIsArchivaDavResource( member ).remoteAddr, locator.getRepositoryId(), path,
402                            event );
403     }
404
405     public void move( DavResource destination )
406         throws DavException
407     {
408         if ( !exists() )
409         {
410             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
411         }
412
413         try
414         {
415             ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
416             if ( isCollection() )
417             {
418                 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
419
420                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
421             }
422             else
423             {
424                 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
425
426                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
427             }
428         }
429         catch ( IOException e )
430         {
431             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
432         }
433     }
434
435     public void copy( DavResource destination, boolean shallow )
436         throws DavException
437     {
438         if ( !exists() )
439         {
440             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
441         }
442
443         if ( shallow && isCollection() )
444         {
445             throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
446         }
447
448         try
449         {
450             ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
451             if ( isCollection() )
452             {
453                 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
454
455                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
456             }
457             else
458             {
459                 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
460
461                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
462             }
463         }
464         catch ( IOException e )
465         {
466             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
467         }
468     }
469
470     public boolean isLockable( Type type, Scope scope )
471     {
472         return Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope);
473     }
474
475     public boolean hasLock( Type type, Scope scope )
476     {
477         return getLock(type, scope) != null;
478     }
479
480     public ActiveLock getLock( Type type, Scope scope )
481     {
482         ActiveLock lock = null;
483         if (exists() && Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope)) 
484         {
485             lock = lockManager.getLock(type, scope, this);
486         }
487         return lock;
488     }
489
490     public ActiveLock[] getLocks()
491     {
492         ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE);
493         return (writeLock != null) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
494     }
495
496     public ActiveLock lock( LockInfo lockInfo )
497         throws DavException
498     {
499         ActiveLock lock = null;
500         if (isLockable(lockInfo.getType(), lockInfo.getScope())) 
501         {
502             lock = lockManager.createLock(lockInfo, this);
503         }
504         else 
505         {
506             throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope.");
507         }
508         return lock;
509     }
510
511     public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
512         throws DavException
513     {
514         if (!exists()) {
515             throw new DavException(DavServletResponse.SC_NOT_FOUND);
516         }
517         ActiveLock lock = getLock(lockInfo.getType(), lockInfo.getScope());
518         if (lock == null) {
519             throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "No lock with the given type/scope present on resource " + getResourcePath());
520         }
521
522         lock = lockManager.refreshLock(lockInfo, lockToken, this);
523
524         return lock;
525     }
526
527     public void unlock( String lockToken )
528         throws DavException
529     {
530         ActiveLock lock = getLock(Type.WRITE, Scope.EXCLUSIVE);
531         if (lock == null)
532         {
533             throw new DavException(HttpServletResponse.SC_PRECONDITION_FAILED);
534         }
535         else if (lock.isLockedByToken(lockToken))
536         {
537             lockManager.releaseLock(lockToken, this);
538         }
539         else
540         {
541             throw new DavException(DavServletResponse.SC_LOCKED);
542         }
543     }
544
545     public void addLockManager( LockManager lockManager )
546     {
547         this.lockManager = lockManager;
548     }
549
550     public DavResourceFactory getFactory()
551     {
552         return factory;
553     }
554
555     public DavSession getSession()
556     {
557         return session;
558     }
559
560     /**
561      * Fill the set of properties
562      */
563     protected DavPropertySet initProperties()
564     {
565         if ( !exists() )
566         {
567             properties = new DavPropertySet();
568         }
569         
570         if ( properties != null )
571         {
572             return properties;
573         }
574
575         DavPropertySet properties = new DavPropertySet();
576         
577         // set (or reset) fundamental properties
578         if ( getDisplayName() != null )
579         {
580             properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
581         }
582         if ( isCollection() )
583         {
584             properties.add( new ResourceType( ResourceType.COLLECTION ) );
585             // Windows XP support
586             properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
587         }
588         else
589         {
590             properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
591
592             // Windows XP support
593             properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
594         }
595
596         // Need to get the ISO8601 date for properties
597         DateTime dt = new DateTime( localResource.lastModified() );
598         DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
599         String modifiedDate = fmt.print( dt );
600
601         properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
602
603         properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
604
605         properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
606         
607         this.properties = properties;
608         
609         return properties;
610     }
611
612     private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
613         throws DavException
614     {
615         if ( !( resource instanceof ArchivaDavResource ) )
616         {
617             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
618                                     "DavResource is not instance of ArchivaDavResource" );
619         }
620         return (ArchivaDavResource) resource;
621     }
622
623     private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
624     {
625         AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
626         event.setRemoteIP( remoteIP );
627
628         for ( AuditListener listener : auditListeners )
629         {
630             listener.auditEvent( event );
631         }
632     }
633     
634     private void queueRepositoryTask(  File localFile )
635     {        
636         RepositoryTask task = TaskCreator.createRepositoryTask( repository.getId(), localFile.getName(), localFile, false );
637         
638         try
639         {
640             scheduler.queueRepositoryTask( task );
641         }
642         catch ( TaskQueueException e )
643         {
644             log.error( "Unable to queue repository task to execute consumers on resource file ['" +
645                 localFile.getName() + "']." );
646         }
647     }
648 }