]> source.dussan.org Git - archiva.git/blob
39e21c38f6e051bbe5136398cf06c2236ff435ff
[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.FileNotFoundException;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.servlet.http.HttpServletResponse;
32
33 import org.apache.commons.io.FileUtils;
34 import org.apache.commons.lang.StringUtils;
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.DavResourceLocator;
39 import org.apache.jackrabbit.webdav.DavServletRequest;
40 import org.apache.jackrabbit.webdav.DavServletResponse;
41 import org.apache.jackrabbit.webdav.DavSession;
42 import org.apache.jackrabbit.webdav.lock.LockManager;
43 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
44 import org.apache.maven.archiva.common.utils.PathUtil;
45 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
46 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
47 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
48 import org.apache.maven.archiva.model.ArtifactReference;
49 import org.apache.maven.archiva.model.ProjectReference;
50 import org.apache.maven.archiva.model.VersionedReference;
51 import org.apache.maven.archiva.policies.ProxyDownloadException;
52 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
53 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
54 import org.apache.maven.archiva.repository.RepositoryContentFactory;
55 import org.apache.maven.archiva.repository.RepositoryException;
56 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
57 import org.apache.maven.archiva.repository.audit.AuditEvent;
58 import org.apache.maven.archiva.repository.audit.AuditListener;
59 import org.apache.maven.archiva.repository.audit.Auditable;
60 import org.apache.maven.archiva.repository.content.RepositoryRequest;
61 import org.apache.maven.archiva.repository.layout.LayoutException;
62 import org.apache.maven.archiva.repository.metadata.MetadataTools;
63 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
64 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
65 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
66 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
67 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
68 import org.apache.maven.archiva.security.ArchivaXworkUser;
69 import org.apache.maven.archiva.security.ServletAuthenticator;
70 import org.apache.maven.archiva.webdav.util.MimeTypes;
71 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
72 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
73 import org.apache.maven.model.DistributionManagement;
74 import org.apache.maven.model.Model;
75 import org.apache.maven.model.Relocation;
76 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
77 import org.codehaus.plexus.digest.ChecksumFile;
78 import org.codehaus.plexus.digest.Digester;
79 import org.codehaus.plexus.digest.DigesterException;
80 import org.codehaus.plexus.redback.authentication.AuthenticationException;
81 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
82 import org.codehaus.plexus.redback.authorization.AuthorizationException;
83 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
84 import org.codehaus.plexus.redback.policy.AccountLockedException;
85 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
86 import org.codehaus.plexus.redback.system.SecuritySession;
87 import org.codehaus.plexus.redback.system.SecuritySystemConstants;
88 import org.codehaus.plexus.redback.xwork.filter.authentication.HttpAuthenticator;
89 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
92
93 import com.opensymphony.xwork.ActionContext;
94
95 /**
96  * @author <a href="mailto:james@atlassian.com">James William Dumay</a>
97  * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
98  */
99 public class ArchivaDavResourceFactory
100     implements DavResourceFactory, Auditable
101 {   
102     private static final String PROXIED_SUFFIX = " (proxied)";
103
104     private static final String HTTP_PUT_METHOD = "PUT";
105
106     private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
107
108     /**
109      * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
110      */
111     private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
112
113     /**
114      * @plexus.requirement
115      */
116     private RepositoryContentFactory repositoryFactory;
117
118     /**
119      * @plexus.requirement
120      */
121     private RepositoryRequest repositoryRequest;
122
123     /**
124      * @plexus.requirement role-hint="default"
125      */
126     private RepositoryProxyConnectors connectors;
127
128     /**
129      * @plexus.requirement
130      */
131     private MetadataTools metadataTools;
132
133     /**
134      * @plexus.requirement
135      */
136     private MimeTypes mimeTypes;
137
138     /**
139      * @plexus.requirement
140      */
141     private ArchivaConfiguration archivaConfiguration;
142
143     /**
144      * @plexus.requirement
145      */
146     private ServletAuthenticator servletAuth;
147
148     /**
149      * @plexus.requirement role-hint="basic"
150      */
151     private HttpAuthenticator httpAuth;
152
153     /**
154      * Lock Manager - use simple implementation from JackRabbit
155      */
156     private final LockManager lockManager = new SimpleLockManager();
157
158     /** 
159      * @plexus.requirement 
160      */
161     private RepositoryContentConsumers consumers;
162     
163     /**
164      * @plexus.requirement
165      */
166     private ChecksumFile checksum;
167         
168     /**
169      * @plexus.requirement role-hint="sha1"
170      */
171     private Digester digestSha1;
172
173     /**
174      * @plexus.requirement role-hint="md5";
175      */
176     private Digester digestMd5;
177         
178     public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
179                                        final DavServletResponse response )
180         throws DavException
181     {
182         checkLocatorIsInstanceOfRepositoryLocator( locator );
183         ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
184
185         RepositoryGroupConfiguration repoGroupConfig =
186             archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
187         List<String> repositories = new ArrayList<String>();
188
189         boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
190         boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
191
192         if ( repoGroupConfig != null )
193         {
194             if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
195             {
196                 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
197                                         "Write method not allowed for repository groups." );
198             }
199             repositories.addAll( repoGroupConfig.getRepositories() );
200
201             // handle browse requests for virtual repos
202             if ( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ).endsWith( "/" ) )
203             {
204                 return getResource( request, repositories, archivaLocator );
205             }
206         }
207         else
208         {
209             repositories.add( archivaLocator.getRepositoryId() );
210         }
211
212         //MRM-419 - Windows Webdav support. Should not 404 if there is no content.
213         if (StringUtils.isEmpty(archivaLocator.getRepositoryId()))
214         {
215             throw new DavException(HttpServletResponse.SC_NO_CONTENT);
216         }
217
218         List<DavResource> availableResources = new ArrayList<DavResource>();
219         List<String> resourcesInAbsolutePath = new ArrayList<String>();
220         DavException e = null;
221         
222         for ( String repositoryId : repositories )
223         {
224             ManagedRepositoryContent managedRepository = null;
225
226             try
227             {
228                 managedRepository = getManagedRepository( repositoryId );
229             }
230             catch ( DavException de )
231             {
232                 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
233                     repositoryId + ">" );
234             }
235             
236             DavResource resource = null;
237             
238             if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
239             {
240                 if ( managedRepository != null )
241                 {
242                     try
243                     {
244                         if( isAuthorized( request, repositoryId ) )
245                         {
246                             LogicalResource logicalResource =
247                                 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
248
249                             if ( isGet )
250                             {
251                                 resource = doGet( managedRepository, request, archivaLocator, logicalResource );
252                             }
253
254                             if ( isPut )
255                             {
256                                 resource = doPut( managedRepository, request, archivaLocator, logicalResource );
257                             }
258                         }
259                     }
260                     catch ( DavException de ) 
261                     {
262                         e = de;
263                         continue;
264                     }
265
266                     if( resource == null )
267                     {
268                         e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
269                     }
270                     else
271                     {   
272                         availableResources.add( resource );
273
274                         String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
275                         resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
276                     }
277                 }
278                 else
279                 {
280                     e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Repository does not exist" );
281                 }
282             }
283         }        
284         
285         if ( availableResources.isEmpty() )
286         {
287             throw e;
288         }
289         
290         String requestedResource = request.getRequestURI();
291         
292         // MRM-872 : merge all available metadata
293         // merge metadata only when requested via the repo group        
294         if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) ) &&
295             repoGroupConfig != null )
296         {   
297             // this should only be at the project level not version level!
298             if( isProjectReference( requestedResource ) )
299             {
300                 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
301                 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
302                 
303                 ArchivaDavResource res = ( ArchivaDavResource ) availableResources.get( 0 );
304                 String filePath = StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );                                
305                 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
306                 
307                 // for MRM-872 handle checksums of the merged metadata files 
308                 if( repositoryRequest.isSupportFile( requestedResource ) )
309                 {
310                     File metadataChecksum = new File( filePath + "." 
311                               + StringUtils.substringAfterLast( requestedResource, "." ) );                    
312                     if( metadataChecksum.exists() )
313                     {
314                         LogicalResource logicalResource =
315                             new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
316                                         
317                         ArchivaDavResource metadataChecksumResource =
318                             new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
319                                                     request.getRemoteAddr(), request.getDavSession(), archivaLocator, this,
320                                                     mimeTypes, auditListeners, consumers );
321                         availableResources.add( 0, metadataChecksumResource );
322                     }
323                 }
324                 else
325                 {   // merge the metadata of all repos under group
326                     ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
327                     for ( String resourceAbsPath : resourcesInAbsolutePath )    
328                     {   
329                         try
330                         {   
331                             File metadataFile = new File( resourceAbsPath );
332                             ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
333                             mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
334                         }
335                         catch ( RepositoryMetadataException r )
336                         {
337                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
338                                                     "Error occurred while reading metadata file." );
339                         }                
340                     }        
341                     
342                     try
343                     {   
344                         File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );   
345                         
346                         LogicalResource logicalResource =
347                             new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
348                                         
349                         ArchivaDavResource metadataResource =
350                             new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
351                                                     request.getRemoteAddr(), request.getDavSession(), archivaLocator, this,
352                                                     mimeTypes, auditListeners, consumers );
353                         availableResources.add( 0, metadataResource );
354                     }
355                     catch ( RepositoryMetadataException r )
356                     {                
357                         throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
358                                                 "Error occurred while writing metadata file." );
359                     }
360                     catch ( IOException ie )
361                     {
362                         throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
363                             "Error occurred while generating checksum files." );
364                     }
365                     catch ( DigesterException de )
366                     {
367                         throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
368                             "Error occurred while generating checksum files." );
369                     }
370                 }
371             }
372         }
373                 
374         DavResource resource = availableResources.get( 0 );               
375         setHeaders(response, locator, resource );
376
377         // compatibility with MRM-440 to ensure browsing the repository works ok
378         if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
379         {
380             throw new BrowserRedirectException( resource.getHref() );
381         }
382         resource.addLockManager(lockManager);
383         return resource;
384     }
385
386     public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
387         throws DavException
388     {
389         checkLocatorIsInstanceOfRepositoryLocator( locator );
390         ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
391
392         DavResource resource = null;
393         if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
394         {
395             ManagedRepositoryContent managedRepository = getManagedRepository( archivaLocator.getRepositoryId() );
396             String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
397             File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
398             resource =
399                 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
400                                         managedRepository.getRepository(), davSession, archivaLocator, this, mimeTypes,
401                                         auditListeners, consumers );
402         }
403         resource.addLockManager(lockManager);
404         return resource;
405     }
406
407     private DavResource doGet( ManagedRepositoryContent managedRepository, DavServletRequest request,
408                                ArchivaDavResourceLocator locator, LogicalResource logicalResource )
409         throws DavException
410     {
411         File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
412         ArchivaDavResource resource =
413             new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
414                                     managedRepository.getRepository(), request.getRemoteAddr(),
415                                     request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
416
417         if ( !resource.isCollection() )
418         {
419             boolean previouslyExisted = resourceFile.exists();
420
421             // At this point the incoming request can either be in default or
422             // legacy layout format.
423             boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
424
425             try
426             {
427                 // Perform an adjustment of the resource to the managed
428                 // repository expected path.
429                 String localResourcePath =
430                     repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
431                 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
432             }
433             catch ( LayoutException e )
434             {
435                 if ( previouslyExisted )
436                 {
437                     return resource;
438                 }
439                 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
440             }
441
442             // Attempt to fetch the resource from any defined proxy.
443             if ( fromProxy )
444             {
445                 String repositoryId = locator.getRepositoryId();
446                 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) + PROXIED_SUFFIX;
447                 triggerAuditEvent( request.getRemoteAddr(), repositoryId, logicalResource.getPath(), event );
448             }
449
450             if ( !resourceFile.exists() )
451             {
452                 resource = null;
453             }
454             else
455             {
456                 resource =
457                     new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
458                                             managedRepository.getRepository(), request.getRemoteAddr(),
459                                             request.getDavSession(), locator, this, mimeTypes, auditListeners,
460                                             consumers );
461             }
462         }
463         return resource;
464     }
465
466     private DavResource doPut( ManagedRepositoryContent managedRepository, DavServletRequest request,
467                                ArchivaDavResourceLocator locator, LogicalResource logicalResource )
468         throws DavException
469     {
470         /*
471          * Create parent directories that don't exist when writing a file This actually makes this implementation not
472          * compliant to the WebDAV RFC - but we have enough knowledge about how the collection is being used to do this
473          * reasonably and some versions of Maven's WebDAV don't correctly create the collections themselves.
474          */
475
476         File rootDirectory = new File( managedRepository.getRepoRoot() );
477         File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
478         if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
479         {
480             destDir.mkdirs();
481             String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
482             triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR );
483         }
484
485         File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
486
487         return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
488                                        managedRepository.getRepository(), request.getRemoteAddr(),
489                                        request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
490     }
491
492     private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
493                                              LogicalResource resource )
494         throws DavException
495     {
496         if ( repositoryRequest.isSupportFile( resource.getPath() ) )
497         {
498             // Checksums are fetched with artifact / metadata.
499
500             // Need to adjust the path for the checksum resource.
501             return false;
502         }
503
504         // Is it a Metadata resource?
505         if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
506         {
507             return fetchMetadataFromProxies( managedRepository, request, resource );
508         }
509
510         // Not any of the above? Then it's gotta be an artifact reference.
511         try
512         {
513             // Get the artifact reference in a layout neutral way.
514             ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
515
516             if ( artifact != null )
517             {
518                 applyServerSideRelocation( managedRepository, artifact );
519
520                 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
521
522                 resource.setPath( managedRepository.toPath( artifact ) );
523
524                 return ( proxiedFile != null );
525             }
526         }
527         catch ( LayoutException e )
528         {
529             /* eat it */
530         }
531         catch ( ProxyDownloadException e )
532         {
533             log.error( e.getMessage(), e );
534             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
535         }
536         return false;
537     }
538
539     private boolean fetchMetadataFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
540                                               LogicalResource resource )
541         throws DavException
542     {
543         ProjectReference project;
544         VersionedReference versioned;
545
546         try
547         {
548
549             versioned = metadataTools.toVersionedReference( resource.getPath() );
550             if ( versioned != null )
551             {
552                 connectors.fetchFromProxies( managedRepository, versioned );
553                 return true;
554             }
555         }
556         catch ( RepositoryMetadataException e )
557         {
558             /* eat it */
559         }
560
561         try
562         {
563             project = metadataTools.toProjectReference( resource.getPath() );
564             if ( project != null )
565             {
566                 connectors.fetchFromProxies( managedRepository, project );
567                 return true;
568             }
569         }
570         catch ( RepositoryMetadataException e )
571         {
572             /* eat it */
573         }
574
575         return false;
576     }
577
578     /**
579      * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
580      * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
581      * metadatas.
582      * <p>
583      * For such clients, archiva does server-side relocation by reading itself the &lt;relocation&gt; element in
584      * metadatas and serving the expected artifact.
585      */
586     protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
587         throws ProxyDownloadException
588     {
589         if ( "pom".equals( artifact.getType() ) )
590         {
591             return;
592         }
593
594         // Build the artifact POM reference
595         ArtifactReference pomReference = new ArtifactReference();
596         pomReference.setGroupId( artifact.getGroupId() );
597         pomReference.setArtifactId( artifact.getArtifactId() );
598         pomReference.setVersion( artifact.getVersion() );
599         pomReference.setType( "pom" );
600
601         // Get the artifact POM from proxied repositories if needed
602         connectors.fetchFromProxies( managedRepository, pomReference );
603
604         // Open and read the POM from the managed repo
605         File pom = managedRepository.toFile( pomReference );
606
607         if ( !pom.exists() )
608         {
609             return;
610         }
611
612         try
613         {
614             Model model = new MavenXpp3Reader().read( new FileReader( pom ) );
615             DistributionManagement dist = model.getDistributionManagement();
616             if ( dist != null )
617             {
618                 Relocation relocation = dist.getRelocation();
619                 if ( relocation != null )
620                 {
621                     // artifact is relocated : update the repositoryPath
622                     if ( relocation.getGroupId() != null )
623                     {
624                         artifact.setGroupId( relocation.getGroupId() );
625                     }
626                     if ( relocation.getArtifactId() != null )
627                     {
628                         artifact.setArtifactId( relocation.getArtifactId() );
629                     }
630                     if ( relocation.getVersion() != null )
631                     {
632                         artifact.setVersion( relocation.getVersion() );
633                     }
634                 }
635             }
636         }
637         catch ( FileNotFoundException e )
638         {
639             // Artifact has no POM in repo : ignore
640         }
641         catch ( IOException e )
642         {
643             // Unable to read POM : ignore.
644         }
645         catch ( XmlPullParserException e )
646         {
647             // Invalid POM : ignore
648         }
649     }
650
651     // TODO: remove?
652     private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
653     {
654         String activePrincipal = ArchivaXworkUser.getActivePrincipal( ActionContext.getContext().getSession() );
655         AuditEvent event = new AuditEvent( repositoryId, activePrincipal, resource, action );
656         event.setRemoteIP( remoteIP );
657
658         for ( AuditListener listener : auditListeners )
659         {
660             listener.auditEvent( event );
661         }
662     }
663
664     public void addAuditListener( AuditListener listener )
665     {
666         this.auditListeners.add( listener );
667     }
668
669     public void clearAuditListeners()
670     {
671         this.auditListeners.clear();
672     }
673
674     public void removeAuditListener( AuditListener listener )
675     {
676         this.auditListeners.remove( listener );
677     }
678
679     private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
680     {
681         // [MRM-503] - Metadata file need Pragma:no-cache response
682         // header.
683         if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
684         {
685             response.addHeader( "Pragma", "no-cache" );
686             response.addHeader( "Cache-Control", "no-cache" );
687         }
688
689         //We need to specify this so connecting wagons can work correctly
690         response.addDateHeader("last-modified", resource.getModificationTime());
691
692         // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
693     }
694
695     private ManagedRepositoryContent getManagedRepository( String respositoryId )
696         throws DavException
697     {
698         if ( respositoryId != null )
699         {
700             try
701             {
702                 return repositoryFactory.getManagedRepositoryContent( respositoryId );
703             }
704             catch ( RepositoryNotFoundException e )
705             {
706                 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
707             }
708             catch ( RepositoryException e )
709             {
710                 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
711             }
712         }
713         return null;
714     }
715
716     private void checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
717         throws DavException
718     {
719         if ( !( locator instanceof RepositoryLocator ) )
720         {
721             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
722                                     "Locator does not implement RepositoryLocator" );
723         }
724     }
725
726     class LogicalResource
727     {
728         private String path;
729
730         public LogicalResource( String path )
731         {
732             this.path = path;
733         }
734
735         public String getPath()
736         {
737             return path;
738         }
739
740         public void setPath( String path )
741         {
742             this.path = path;
743         }
744     }
745
746     protected boolean isAuthorized( DavServletRequest request, String repositoryId )
747         throws DavException
748     {
749         try
750         {
751             AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
752             SecuritySession securitySession = httpAuth.getSecuritySession();
753
754             return servletAuth.isAuthenticated( request, result ) &&
755                 servletAuth.isAuthorized( request, securitySession, repositoryId,
756                                           WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
757         }
758         catch ( AuthenticationException e )
759         {
760             throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
761         }
762         catch ( MustChangePasswordException e )
763         {
764             throw new UnauthorizedDavException( repositoryId, "You must change your password." );
765         }
766         catch ( AccountLockedException e )
767         {
768             throw new UnauthorizedDavException( repositoryId, "User account is locked." );
769         }
770         catch ( AuthorizationException e )
771         {
772             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
773                                     "Fatal Authorization Subsystem Error." );
774         }
775         catch ( UnauthorizedException e )
776         {
777             throw new UnauthorizedDavException( repositoryId, e.getMessage() );
778         }
779     }
780
781     private DavResource getResource( DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator )
782         throws DavException
783     {
784         List<File> mergedRepositoryContents = new ArrayList<File>();
785         LogicalResource logicalResource =
786             new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
787
788         // flow:
789         // if the current user logged in has permission to any of the repositories, allow user to
790         // browse the repo group but displaying only the repositories which the user has permission to access.
791         // otherwise, prompt for authentication.
792
793         // put the current session in the session map which will be passed to ArchivaXworkUser
794         Map<String, Object> sessionMap = new HashMap<String, Object>();
795         if( request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) != null )
796         {
797             sessionMap.put( SecuritySystemConstants.SECURITY_SESSION_KEY,
798                             request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) );
799         }
800
801         String activePrincipal = ArchivaXworkUser.getActivePrincipal( sessionMap );
802         boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
803
804         if( allow )
805         {
806             for( String repository : repositories )
807             {
808                 // for prompted authentication
809                 if( httpAuth.getSecuritySession() != null )
810                 {
811                     try
812                     {
813                         if( isAuthorized( request, repository ) )
814                         {
815                             getResource( locator, mergedRepositoryContents, logicalResource, repository );
816                         }
817                     }
818                     catch ( DavException e )
819                     {
820                         continue;
821                     }
822                 }
823                 else
824                 {
825                     // for the current user logged in
826                     try
827                     {
828                         if( servletAuth.isAuthorizedToAccessVirtualRepository( activePrincipal, repository ) )
829                         {
830                             getResource( locator, mergedRepositoryContents, logicalResource, repository );
831                         }
832                     }
833                     catch ( UnauthorizedException e )
834                     {
835                         continue;
836                     }
837                 }
838             }
839         }
840         else
841         {
842             throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
843         }
844
845         ArchivaVirtualDavResource resource =
846             new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this );
847
848         // compatibility with MRM-440 to ensure browsing the repository group works ok
849         if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
850         {
851             throw new BrowserRedirectException( resource.getHref() );
852         }
853
854         return resource;
855     }
856
857     private void getResource( ArchivaDavResourceLocator locator, List<File> mergedRepositoryContents,
858                               LogicalResource logicalResource, String repository )
859         throws DavException
860     {
861         ManagedRepositoryContent managedRepository = null;
862
863         try
864         {
865             managedRepository = getManagedRepository( repository );
866         }
867         catch ( DavException de )
868         {
869             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
870                 repository + ">" );
871         }
872
873         if ( !locator.getResourcePath().startsWith( ArchivaVirtualDavResource.HIDDEN_PATH_PREFIX ) )
874         {
875             if( managedRepository != null )
876             {
877                 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
878                 if( resourceFile.exists() )
879                 {
880                     mergedRepositoryContents.add( resourceFile );
881                 }
882             }
883         }
884     }
885
886     /**
887      * Check if the current user is authorized to access any of the repos
888      *
889      * @param request
890      * @param repositories
891      * @param activePrincipal
892      * @return
893      */
894     private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
895     {
896         boolean allow = false;
897
898
899         // if securitySession != null, it means that the user was prompted for authentication
900         if( httpAuth.getSecuritySession() != null )
901         {
902             for( String repository : repositories )
903             {
904                 try
905                 {
906                     if( isAuthorized( request, repository ) )
907                     {
908                         allow = true;
909                         break;
910                     }
911                 }
912                 catch( DavException e )
913                 {
914                     continue;
915                 }
916             }
917         }
918         else
919         {
920             for( String repository : repositories )
921             {
922                 try
923                 {
924                     if( servletAuth.isAuthorizedToAccessVirtualRepository( activePrincipal, repository ) )
925                     {
926                         allow = true;
927                         break;
928                     }
929                 }
930                 catch ( UnauthorizedException e )
931                 {
932                     continue;
933                 }
934             }
935         }
936
937         return allow;
938     }
939
940     private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
941         throws RepositoryMetadataException, DigesterException, IOException
942     {  
943         File outputFile = new File( outputFilename );        
944         if( outputFile.exists() )
945         {
946             FileUtils.deleteQuietly( outputFile );
947         }
948         
949         outputFile.getParentFile().mkdirs();
950         RepositoryMetadataWriter.write( mergedMetadata, outputFile );
951         
952         createChecksumFile( outputFilename, digestSha1 );
953         createChecksumFile( outputFilename, digestMd5 );
954         
955         return outputFile;
956     }
957     
958     private void createChecksumFile( String path, Digester digester )
959         throws DigesterException, IOException
960     {   
961         File checksumFile = new File( path + digester.getFilenameExtension() );        
962         if ( !checksumFile.exists() )
963         {
964             FileUtils.deleteQuietly( checksumFile );
965             checksum.createChecksum( new File( path ), digester );            
966         }
967         else if ( !checksumFile.isFile() )
968         {
969             log.error( "Checksum file is not a file." );
970         }
971     }
972     
973     private boolean isProjectReference( String requestedResource )
974     {  
975        try
976        {           
977            VersionedReference versionRef = metadataTools.toVersionedReference( requestedResource );           
978            return false;
979        }
980        catch ( RepositoryMetadataException re )
981        {
982            return true;
983        }
984     }
985 }