]> source.dussan.org Git - archiva.git/blob
4938561004d724aff096ea9ae7c530adba3fdc6c
[archiva.git] /
1 package org.apache.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 org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.beans.ManagedRepository;
24 import org.apache.archiva.admin.model.beans.RemoteRepository;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
27 import org.apache.archiva.audit.Auditable;
28 import org.apache.archiva.common.filelock.FileLockManager;
29 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
30 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
31 import org.apache.archiva.common.utils.PathUtil;
32 import org.apache.archiva.common.utils.VersionUtil;
33 import org.apache.archiva.configuration.ArchivaConfiguration;
34 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
35 import org.apache.archiva.indexer.merger.IndexMerger;
36 import org.apache.archiva.indexer.merger.IndexMergerException;
37 import org.apache.archiva.indexer.merger.IndexMergerRequest;
38 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTask;
39 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTaskRequest;
40 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
41 import org.apache.archiva.indexer.search.RepositorySearch;
42 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
43 import org.apache.archiva.metadata.model.facets.AuditEvent;
44 import org.apache.archiva.metadata.repository.storage.RelocationException;
45 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
46 import org.apache.archiva.model.ArchivaRepositoryMetadata;
47 import org.apache.archiva.model.ArtifactReference;
48 import org.apache.archiva.policies.ProxyDownloadException;
49 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
50 import org.apache.archiva.redback.authentication.AuthenticationException;
51 import org.apache.archiva.redback.authentication.AuthenticationResult;
52 import org.apache.archiva.redback.authorization.AuthorizationException;
53 import org.apache.archiva.redback.authorization.UnauthorizedException;
54 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
55 import org.apache.archiva.redback.policy.AccountLockedException;
56 import org.apache.archiva.redback.policy.MustChangePasswordException;
57 import org.apache.archiva.redback.system.SecuritySession;
58 import org.apache.archiva.redback.users.User;
59 import org.apache.archiva.redback.users.UserManager;
60 import org.apache.archiva.repository.ManagedRepositoryContent;
61 import org.apache.archiva.repository.RepositoryContentFactory;
62 import org.apache.archiva.repository.RepositoryException;
63 import org.apache.archiva.repository.RepositoryNotFoundException;
64 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
65 import org.apache.archiva.repository.events.AuditListener;
66 import org.apache.archiva.repository.layout.LayoutException;
67 import org.apache.archiva.repository.metadata.MetadataTools;
68 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
69 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
70 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
71 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
72 import org.apache.archiva.security.ServletAuthenticator;
73 import org.apache.archiva.webdav.util.MimeTypes;
74 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
75 import org.apache.archiva.webdav.util.WebdavMethodUtil;
76 import org.apache.archiva.xml.XMLException;
77 import org.apache.commons.io.FileUtils;
78 import org.apache.commons.io.FilenameUtils;
79 import org.apache.commons.lang.StringUtils;
80 import org.apache.commons.lang.SystemUtils;
81 import org.apache.jackrabbit.webdav.DavException;
82 import org.apache.jackrabbit.webdav.DavResource;
83 import org.apache.jackrabbit.webdav.DavResourceFactory;
84 import org.apache.jackrabbit.webdav.DavResourceLocator;
85 import org.apache.jackrabbit.webdav.DavServletRequest;
86 import org.apache.jackrabbit.webdav.DavServletResponse;
87 import org.apache.jackrabbit.webdav.DavSession;
88 import org.apache.jackrabbit.webdav.lock.LockManager;
89 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
90 import org.apache.maven.index.context.IndexingContext;
91 import org.codehaus.plexus.digest.ChecksumFile;
92 import org.codehaus.plexus.digest.Digester;
93 import org.codehaus.plexus.digest.DigesterException;
94 import org.slf4j.Logger;
95 import org.slf4j.LoggerFactory;
96 import org.slf4j.MarkerFactory;
97 import org.springframework.context.ApplicationContext;
98 import org.springframework.stereotype.Service;
99
100 import javax.annotation.PostConstruct;
101 import javax.inject.Inject;
102 import javax.inject.Named;
103 import javax.servlet.http.HttpServletResponse;
104 import javax.servlet.http.HttpSession;
105 import java.io.File;
106 import java.io.IOException;
107 import java.nio.file.Files;
108 import java.nio.file.Path;
109 import java.util.ArrayList;
110 import java.util.Date;
111 import java.util.HashMap;
112 import java.util.HashSet;
113 import java.util.List;
114 import java.util.Map;
115 import java.util.Set;
116
117 /**
118  *
119  */
120 @Service( "davResourceFactory#archiva" )
121 public class ArchivaDavResourceFactory
122     implements DavResourceFactory, Auditable
123 {
124     private static final String PROXIED_SUFFIX = " (proxied)";
125
126     private static final String HTTP_PUT_METHOD = "PUT";
127
128     private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
129
130     @Inject
131     private List<AuditListener> auditListeners = new ArrayList<>();
132
133     @Inject
134     private RepositoryContentFactory repositoryFactory;
135
136     private RepositoryRequest repositoryRequest;
137
138     @Inject
139     @Named( value = "repositoryProxyConnectors#default" )
140     private RepositoryProxyConnectors connectors;
141
142     @Inject
143     private MetadataTools metadataTools;
144
145     @Inject
146     private MimeTypes mimeTypes;
147
148     private ArchivaConfiguration archivaConfiguration;
149
150     @Inject
151     private ServletAuthenticator servletAuth;
152
153     @Inject
154     @Named( value = "httpAuthenticator#basic" )
155     private HttpAuthenticator httpAuth;
156
157     @Inject
158     private RemoteRepositoryAdmin remoteRepositoryAdmin;
159
160     @Inject
161     private ManagedRepositoryAdmin managedRepositoryAdmin;
162
163     @Inject
164     private IndexMerger indexMerger;
165
166     @Inject
167     private RepositorySearch repositorySearch;
168
169     /**
170      * Lock Manager - use simple implementation from JackRabbit
171      */
172     private final LockManager lockManager = new SimpleLockManager();
173
174     private ChecksumFile checksum;
175
176     private Digester digestSha1;
177
178     private Digester digestMd5;
179
180     @Inject
181     @Named( value = "archivaTaskScheduler#repository" )
182     private RepositoryArchivaTaskScheduler scheduler;
183
184     @Inject
185     @Named( value = "fileLockManager#default" )
186     private FileLockManager fileLockManager;
187
188     private ApplicationContext applicationContext;
189
190     @Inject
191     public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
192                                       ArchivaConfiguration archivaConfiguration )
193         throws PlexusSisuBridgeException
194     {
195         this.archivaConfiguration = archivaConfiguration;
196         this.applicationContext = applicationContext;
197         this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
198
199         this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
200         this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
201
202         // TODO remove this hard dependency on maven !!
203         repositoryRequest = new RepositoryRequest( );
204     }
205
206     @PostConstruct
207     public void initialize()
208     {
209         // no op
210     }
211
212     @Override
213     public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
214                                        final DavServletResponse response )
215         throws DavException
216     {
217         ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
218
219         RepositoryGroupConfiguration repoGroupConfig =
220             archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
221
222         String activePrincipal = getActivePrincipal( request );
223
224         List<String> resourcesInAbsolutePath = new ArrayList<>();
225
226         boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
227         DavResource resource;
228         if ( repoGroupConfig != null )
229         {
230             if ( !readMethod )
231             {
232                 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
233                                         "Write method not allowed for repository groups." );
234             }
235
236             log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
237
238             // handle browse requests for virtual repos
239             if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
240             {
241                 try
242                 {
243                     DavResource davResource =
244                         getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
245                                               repoGroupConfig );
246
247                     setHeaders( response, locator, davResource, true );
248
249                     return davResource;
250
251                 }
252                 catch ( RepositoryAdminException e )
253                 {
254                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
255                 }
256             }
257             else
258             {
259                 // make a copy to avoid potential concurrent modifications (eg. by configuration)
260                 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
261                 //  infrequent
262                 List<String> repositories = new ArrayList<>( repoGroupConfig.getRepositories() );
263                 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
264                                                    resourcesInAbsolutePath, repoGroupConfig );
265             }
266         }
267         else
268         {
269
270             try
271             {
272                 RemoteRepository remoteRepository =
273                     remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
274
275                 if ( remoteRepository != null )
276                 {
277                     String logicalResource = getLogicalResource( archivaLocator, null, false );
278                     IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
279                     File resourceFile = StringUtils.equals( logicalResource, "/" )
280                         ? new File( indexingContext.getIndexDirectoryFile().getParent() )
281                         : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
282                     resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), //
283                                                        locator.getResourcePath(), //
284                                                        null, //
285                                                        request.getRemoteAddr(), //
286                                                        activePrincipal, //
287                                                        request.getDavSession(), //
288                                                        archivaLocator, //
289                                                        this, //
290                                                        mimeTypes, //
291                                                        auditListeners, //
292                                                        scheduler, //
293                                                        fileLockManager );
294                     setHeaders( response, locator, resource, false );
295                     return resource;
296                 }
297             }
298             catch ( RepositoryAdminException e )
299             {
300                 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
301                            archivaLocator.getRepositoryId(), e.getMessage() );
302             }
303
304             ManagedRepositoryContent managedRepositoryContent = null;
305
306             try
307             {
308                 managedRepositoryContent =
309                     repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
310             }
311             catch ( RepositoryNotFoundException e )
312             {
313                 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
314                                         "Invalid repository: " + archivaLocator.getRepositoryId() );
315             }
316             catch ( RepositoryException e )
317             {
318                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
319             }
320
321             log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
322
323             try
324             {
325                 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
326                                               managedRepositoryAdmin.getManagedRepository(
327                                                   archivaLocator.getRepositoryId() ) );
328
329                 String logicalResource = getLogicalResource( archivaLocator, null, false );
330                 resourcesInAbsolutePath.add(
331                     new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
332
333             }
334             catch ( RepositoryAdminException e )
335             {
336                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
337             }
338         }
339
340         String requestedResource = request.getRequestURI();
341
342         // MRM-872 : merge all available metadata
343         // merge metadata only when requested via the repo group
344         if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
345             requestedResource ) ) && repoGroupConfig != null )
346         {
347             // this should only be at the project level not version level!
348             if ( isProjectReference( requestedResource ) )
349             {
350
351                 ArchivaDavResource res = (ArchivaDavResource) resource;
352                 String filePath =
353                     StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
354                                                      "/" );
355                 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
356
357                 // for MRM-872 handle checksums of the merged metadata files
358                 if ( repositoryRequest.isSupportFile( requestedResource ) )
359                 {
360                     File metadataChecksum =
361                         new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
362
363                     if ( metadataChecksum.exists() )
364                     {
365                         LogicalResource logicalResource =
366                             new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
367
368                         resource =
369                             new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
370                                                     request.getRemoteAddr(), activePrincipal, request.getDavSession(),
371                                                     archivaLocator, this, mimeTypes, auditListeners, scheduler,
372                                                     fileLockManager );
373                     }
374                 }
375                 else
376                 {
377                     if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
378                     {
379                         // merge the metadata of all repos under group
380                         ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
381                         for ( String resourceAbsPath : resourcesInAbsolutePath )
382                         {
383                             try
384                             {
385                                 File metadataFile = new File( resourceAbsPath );
386                                 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
387                                 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
388                             }
389                             catch ( XMLException e )
390                             {
391                                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
392                                                         "Error occurred while reading metadata file." );
393                             }
394                             catch ( RepositoryMetadataException r )
395                             {
396                                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
397                                                         "Error occurred while merging metadata file." );
398                             }
399                         }
400
401                         try
402                         {
403                             File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
404
405                             LogicalResource logicalResource =
406                                 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
407
408                             resource =
409                                 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
410                                                         request.getRemoteAddr(), activePrincipal,
411                                                         request.getDavSession(), archivaLocator, this, mimeTypes,
412                                                         auditListeners, scheduler, fileLockManager );
413                         }
414                         catch ( RepositoryMetadataException r )
415                         {
416                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
417                                                     "Error occurred while writing metadata file." );
418                         }
419                         catch ( IOException ie )
420                         {
421                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
422                                                     "Error occurred while generating checksum files." );
423                         }
424                         catch ( DigesterException de )
425                         {
426                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
427                                                     "Error occurred while generating checksum files."
428                                                         + de.getMessage() );
429                         }
430                     }
431                 }
432             }
433         }
434
435         setHeaders( response, locator, resource, false );
436
437         // compatibility with MRM-440 to ensure browsing the repository works ok
438         if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
439         {
440             throw new BrowserRedirectException( resource.getHref() );
441         }
442         resource.addLockManager( lockManager );
443         return resource;
444     }
445
446     private DavResource processRepositoryGroup( final DavServletRequest request,
447                                                 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
448                                                 String activePrincipal, List<String> resourcesInAbsolutePath,
449                                                 RepositoryGroupConfiguration repoGroupConfig )
450         throws DavException
451     {
452         DavResource resource = null;
453         List<DavException> storedExceptions = new ArrayList<>();
454
455         String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
456
457         String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
458
459         if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
460         {
461             // we are in the case of index file request
462             String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
463             File temporaryIndexDirectory =
464                 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
465
466             File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
467             resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
468                                                request.getRemoteAddr(), activePrincipal, request.getDavSession(),
469                                                archivaLocator, this, mimeTypes, auditListeners, scheduler,
470                                                fileLockManager );
471
472         }
473         else
474         {
475             for ( String repositoryId : repositories )
476             {
477                 ManagedRepositoryContent managedRepositoryContent;
478                 try
479                 {
480                     managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
481                 }
482                 catch ( RepositoryNotFoundException e )
483                 {
484                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
485                 }
486                 catch ( RepositoryException e )
487                 {
488                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
489                 }
490
491                 try
492                 {
493                     ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
494                     DavResource updatedResource =
495                         processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
496                                            managedRepository );
497                     if ( resource == null )
498                     {
499                         resource = updatedResource;
500                     }
501
502                     String logicalResource = getLogicalResource( archivaLocator, null, false );
503                     if ( logicalResource.endsWith( "/" ) )
504                     {
505                         logicalResource = logicalResource.substring( 1 );
506                     }
507                     resourcesInAbsolutePath.add(
508                         new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
509                 }
510                 catch ( DavException e )
511                 {
512                     storedExceptions.add( e );
513                 }
514                 catch ( RepositoryAdminException e )
515                 {
516                     storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
517                 }
518             }
519         }
520         if ( resource == null )
521         {
522             if ( !storedExceptions.isEmpty() )
523             {
524                 // MRM-1232
525                 for ( DavException e : storedExceptions )
526                 {
527                     if ( 401 == e.getErrorCode() )
528                     {
529                         throw e;
530                     }
531                 }
532
533                 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
534             }
535             else
536             {
537                 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
538             }
539         }
540         return resource;
541     }
542
543     private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
544                                        boolean useOrigResourcePath )
545     {
546         // FIXME remove this hack
547         // but currently managedRepository can be null in case of group
548         String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
549         RepositoryStorage repositoryStorage =
550             this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
551         String path = repositoryStorage.getFilePath(
552             useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
553             managedRepository );
554         log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
555                    archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
556                    layout );
557         return path;
558     }
559
560     private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator, //
561                                             ManagedRepositoryContent managedRepositoryContent, //
562                                             String contextPath )
563         throws DavException
564     {
565         String layout = managedRepositoryContent.getRepository() == null
566             ? new ManagedRepository().getLayout()
567             : managedRepositoryContent.getRepository().getLayout();
568         RepositoryStorage repositoryStorage =
569             this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
570         try
571         {
572             return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(), //
573                                                              managedRepositoryContent );
574         }
575         catch ( RelocationException e )
576         {
577             String path = e.getPath();
578             log.debug( "Relocation to {}", path );
579
580             throw new BrowserRedirectException( addHrefPrefix( contextPath, path ), e.getRelocationType() );
581         }
582         catch ( XMLException e )
583         {
584             log.error( e.getMessage(), e );
585             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
586         }
587     }
588
589     private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
590                                            String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
591                                            ManagedRepository managedRepository )
592         throws DavException
593     {
594         DavResource resource = null;
595         if ( isAuthorized( request, managedRepositoryContent.getId() ) )
596         {
597             boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
598             // Maven Centric part ask evaluation if -SNAPSHOT
599             // MRM-1846 test if read method to prevent issue with maven 2.2.1 and uniqueVersion false
600
601             String path = readMethod
602                 ? evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() )
603                 : getLogicalResource( archivaLocator, managedRepository, false );
604             if ( path.startsWith( "/" ) )
605             {
606                 path = path.substring( 1 );
607             }
608             LogicalResource logicalResource = new LogicalResource( path );
609             File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
610             resource =
611                 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
612                                         request.getRemoteAddr(), activePrincipal, request.getDavSession(),
613                                         archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
614
615             if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
616             {
617                 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
618                 {
619                     // force a resource not found
620                     throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
621                 }
622                 else
623                 {
624                     if ( !resource.isCollection() )
625                     {
626                         boolean previouslyExisted = resourceFile.exists();
627
628                         boolean fromProxy = fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
629
630                         // At this point the incoming request can either be in default or
631                         // legacy layout format.
632                         try
633                         {
634                             // Perform an adjustment of the resource to the managed
635                             // repository expected path.
636                             String localResourcePath =
637                                 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
638                             resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
639                             resource =
640                                 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
641                                                         managedRepositoryContent.getRepository(),
642                                                         request.getRemoteAddr(), activePrincipal,
643                                                         request.getDavSession(), archivaLocator, this, mimeTypes,
644                                                         auditListeners, scheduler, fileLockManager );
645                         }
646                         catch ( LayoutException e )
647                         {
648                             if ( !resourceFile.exists() )
649                             {
650                                 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
651                             }
652                         }
653
654                         if ( fromProxy )
655                         {
656                             String action = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
657                                 + PROXIED_SUFFIX;
658
659                             log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
660                                        resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
661
662                             triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
663                                                logicalResource.getPath(), action, activePrincipal );
664                         }
665
666                         if ( !resourceFile.exists() )
667                         {
668                             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
669                         }
670                     }
671                 }
672             }
673
674             if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
675             {
676                 String resourcePath = logicalResource.getPath();
677
678                 // check if target repo is enabled for releases
679                 // we suppose that release-artifacts can be deployed only to repos enabled for releases
680                 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
681                     resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
682                 {
683                     ArtifactReference artifact = null;
684                     try
685                     {
686                         artifact = managedRepositoryContent.toArtifactReference( resourcePath );
687
688                         if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
689                         {
690                             // check if artifact already exists and if artifact re-deployment to the repository is allowed
691                             if ( managedRepositoryContent.hasContent( artifact )
692                                 && managedRepositoryContent.getRepository().isBlockRedeployments() )
693                             {
694                                 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
695                                           managedRepositoryContent.getId() );
696                                 throw new DavException( HttpServletResponse.SC_CONFLICT,
697                                                         "Overwriting released artifacts is not allowed." );
698                             }
699                         }
700                     }
701                     catch ( LayoutException e )
702                     {
703                         log.warn( "Artifact path '{}' is invalid.", resourcePath );
704                     }
705                 }
706
707                 /*
708                  * Create parent directories that don't exist when writing a file This actually makes this
709                  * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
710                  * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
711                  * create the collections themselves.
712                  */
713
714                 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
715                 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
716
717                 if ( !destDir.exists() )
718                 {
719                     destDir.mkdirs();
720                     String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
721
722                     log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
723                                activePrincipal );
724
725                     triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
726                                        AuditEvent.CREATE_DIR, activePrincipal );
727                 }
728             }
729         }
730         return resource;
731     }
732
733     @Override
734     public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
735         throws DavException
736     {
737         ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
738
739         ManagedRepositoryContent managedRepositoryContent;
740         try
741         {
742             managedRepositoryContent =
743                 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
744         }
745         catch ( RepositoryNotFoundException e )
746         {
747             throw new DavException( HttpServletResponse.SC_NOT_FOUND,
748                                     "Invalid repository: " + archivaLocator.getRepositoryId() );
749         }
750         catch ( RepositoryException e )
751         {
752             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
753         }
754
755         DavResource resource = null;
756         try
757         {
758             String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
759                 archivaLocator.getRepositoryId() ), false );
760             if ( logicalResource.startsWith( "/" ) )
761             {
762                 logicalResource = logicalResource.substring( 1 );
763             }
764             File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
765             resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
766                                                managedRepositoryContent.getRepository(), davSession, archivaLocator,
767                                                this, mimeTypes, auditListeners, scheduler, fileLockManager );
768
769             resource.addLockManager( lockManager );
770         }
771         catch ( RepositoryAdminException e )
772         {
773             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
774         }
775         return resource;
776     }
777
778     private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
779                                              LogicalResource resource )
780         throws DavException
781     {
782         String path = resource.getPath();
783         if ( repositoryRequest.isSupportFile( path ) )
784         {
785             Path proxiedFile = connectors.fetchFromProxies( managedRepository, path );
786
787             return ( proxiedFile != null );
788         }
789
790         // Is it a Metadata resource?
791         if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
792         {
793             return connectors.fetchMetadataFromProxies( managedRepository, path ).isModified();
794         }
795
796         // Is it an Archetype Catalog?
797         if ( repositoryRequest.isArchetypeCatalog( path ) )
798         {
799             // FIXME we must implement a merge of remote archetype catalog from remote servers.
800             Path proxiedFile = connectors.fetchFromProxies( managedRepository, path );
801
802             return ( proxiedFile != null );
803         }
804
805         // Not any of the above? Then it's gotta be an artifact reference.
806         try
807         {
808             // Get the artifact reference in a layout neutral way.
809             ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
810
811             if ( artifact != null )
812             {
813                 String repositoryLayout = managedRepository.getRepository().getLayout();
814
815                 RepositoryStorage repositoryStorage =
816                     this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
817                 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
818
819                 Path proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
820
821                 resource.setPath( managedRepository.toPath( artifact ) );
822
823                 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
824                            artifact.getVersion() );
825
826                 return ( proxiedFile != null );
827             }
828         }
829         catch ( LayoutException e )
830         {
831             /* eat it */
832         }
833         catch ( ProxyDownloadException e )
834         {
835             log.error( e.getMessage(), e );
836             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
837                                     "Unable to fetch artifact resource." );
838         }
839         return false;
840     }
841
842     // TODO: remove?
843
844     private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
845                                     String principal )
846     {
847         AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
848         event.setRemoteIP( remoteIP );
849
850         for ( AuditListener listener : auditListeners )
851         {
852             listener.auditEvent( event );
853         }
854     }
855
856     @Override
857     public void addAuditListener( AuditListener listener )
858     {
859         this.auditListeners.add( listener );
860     }
861
862     @Override
863     public void clearAuditListeners()
864     {
865         this.auditListeners.clear();
866     }
867
868     @Override
869     public void removeAuditListener( AuditListener listener )
870     {
871         this.auditListeners.remove( listener );
872     }
873
874     private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource,
875                              boolean group )
876     {
877         // [MRM-503] - Metadata file need Pragma:no-cache response
878         // header.
879         if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || ( resource instanceof ArchivaDavResource
880             && ( ArchivaDavResource.class.cast( resource ).getLocalResource().isDirectory() ) ) )
881         {
882             response.setHeader( "Pragma", "no-cache" );
883             response.setHeader( "Cache-Control", "no-cache" );
884             response.setDateHeader( "Last-Modified", new Date().getTime() );
885         }
886         // if the resource is a directory don't cache it as new groupId deployed will be available
887         // without need of refreshing browser
888         else if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || (
889             resource instanceof ArchivaVirtualDavResource && ( new File(
890                 ArchivaVirtualDavResource.class.cast( resource ).getLogicalResource() ).isDirectory() ) ) )
891         {
892             response.setHeader( "Pragma", "no-cache" );
893             response.setHeader( "Cache-Control", "no-cache" );
894             response.setDateHeader( "Last-Modified", new Date().getTime() );
895         }
896         else if ( group )
897         {
898             if ( resource instanceof ArchivaVirtualDavResource )
899             {
900                 //MRM-1854 here we have a directory so force "Last-Modified"
901                 response.setDateHeader( "Last-Modified", new Date().getTime() );
902             }
903         }
904         else
905         {
906             // We need to specify this so connecting wagons can work correctly
907             response.setDateHeader( "Last-Modified", resource.getModificationTime() );
908         }
909         // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
910     }
911
912     private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
913         throws DavException
914     {
915         if ( !( locator instanceof ArchivaDavResourceLocator ) )
916         {
917             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
918                                     "Locator does not implement RepositoryLocator" );
919         }
920
921         // Hidden paths
922         if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
923         {
924             throw new DavException( HttpServletResponse.SC_NOT_FOUND );
925         }
926
927         ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
928
929         // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
930         if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
931         {
932             throw new DavException( HttpServletResponse.SC_NO_CONTENT );
933         }
934         return archivaLocator;
935     }
936
937     private String addHrefPrefix( String contextPath, String path ) {
938         String prefix = archivaConfiguration.getConfiguration().getWebapp().getUi().getApplicationUrl();
939         if (prefix == null || prefix.isEmpty()) {
940             prefix = contextPath;
941         }
942         return prefix + ( StringUtils.startsWith( path, "/" ) ? "" :
943                         ( StringUtils.endsWith( prefix, "/" ) ? "" : "/" ) )
944                       + path;
945     }
946
947     private static class LogicalResource
948     {
949         private String path;
950
951         public LogicalResource( String path )
952         {
953             this.path = path;
954         }
955
956         public String getPath()
957         {
958             return path;
959         }
960
961         public void setPath( String path )
962         {
963             this.path = path;
964         }
965     }
966
967     protected boolean isAuthorized( DavServletRequest request, String repositoryId )
968         throws DavException
969     {
970         try
971         {
972             AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
973             SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
974
975             return servletAuth.isAuthenticated( request, result ) //
976                 && servletAuth.isAuthorized( request, securitySession, repositoryId, //
977                                              WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
978         }
979         catch ( AuthenticationException e )
980         {
981             // safety check for MRM-911
982             String guest = UserManager.GUEST_USERNAME;
983             try
984             {
985                 if ( servletAuth.isAuthorized( guest,
986                                                ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
987                                                WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
988                 {
989                     return true;
990                 }
991             }
992             catch ( UnauthorizedException ae )
993             {
994                 throw new UnauthorizedDavException( repositoryId,
995                                                     "You are not authenticated and authorized to access any repository." );
996             }
997
998             throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
999         }
1000         catch ( MustChangePasswordException e )
1001         {
1002             throw new UnauthorizedDavException( repositoryId, "You must change your password." );
1003         }
1004         catch ( AccountLockedException e )
1005         {
1006             throw new UnauthorizedDavException( repositoryId, "User account is locked." );
1007         }
1008         catch ( AuthorizationException e )
1009         {
1010             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1011                                     "Fatal Authorization Subsystem Error." );
1012         }
1013         catch ( UnauthorizedException e )
1014         {
1015             throw new UnauthorizedDavException( repositoryId, e.getMessage() );
1016         }
1017     }
1018
1019     private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
1020                                               ArchivaDavResourceLocator locator,
1021                                               RepositoryGroupConfiguration repositoryGroupConfiguration )
1022         throws DavException, RepositoryAdminException
1023     {
1024         if ( repositoryGroupConfiguration.getRepositories() == null
1025             || repositoryGroupConfiguration.getRepositories().isEmpty() )
1026         {
1027             File file =
1028                 new File( System.getProperty( "appserver.base" ), "groups/" + repositoryGroupConfiguration.getId() );
1029
1030             return new ArchivaDavResource( file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
1031                                            request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler,
1032                                            fileLockManager );
1033         }
1034         List<File> mergedRepositoryContents = new ArrayList<>();
1035         // multiple repo types so we guess they are all the same type
1036         // so use the first one
1037         // FIXME add a method with group in the repository storage
1038         String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 0 );
1039
1040         String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
1041         if ( path.startsWith( "/" ) )
1042         {
1043             path = path.substring( 1 );
1044         }
1045         LogicalResource logicalResource = new LogicalResource( path );
1046
1047         // flow:
1048         // if the current user logged in has permission to any of the repositories, allow user to
1049         // browse the repo group but displaying only the repositories which the user has permission to access.
1050         // otherwise, prompt for authentication.
1051
1052         String activePrincipal = getActivePrincipal( request );
1053
1054         boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1055
1056         // remove last /
1057         String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1058
1059         if ( allow )
1060         {
1061
1062             if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1063             {
1064                 File mergedRepoDir =
1065                     buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1066                 mergedRepositoryContents.add( mergedRepoDir );
1067             }
1068             else
1069             {
1070                 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1071                 {
1072                     File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1073                                                   repositoryGroupConfiguration.getId() + "/"
1074                                                       + repositoryGroupConfiguration.getMergedIndexPath() );
1075                     if ( !tmpDirectory.exists() )
1076                     {
1077                         synchronized ( tmpDirectory.getAbsolutePath() )
1078                         {
1079                             if ( !tmpDirectory.exists() )
1080                             {
1081                                 tmpDirectory.mkdirs();
1082                             }
1083                         }
1084                     }
1085                     mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1086                 }
1087                 for ( String repository : repositories )
1088                 {
1089                     ManagedRepositoryContent managedRepository = null;
1090
1091                     try
1092                     {
1093                         managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1094                     }
1095                     catch ( RepositoryNotFoundException e )
1096                     {
1097                         throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1098                                                 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1099                     }
1100                     catch ( RepositoryException e )
1101                     {
1102                         throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1103                                                 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1104                     }
1105
1106                     File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1107                     if ( resourceFile.exists() )
1108                     {
1109                         // in case of group displaying index directory doesn't have sense !!
1110                         String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1111                         if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1112                         {
1113                             if ( !new File( repoIndexDirectory ).isAbsolute() )
1114                             {
1115                                 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1116                                                                StringUtils.isEmpty( repoIndexDirectory )
1117                                                                    ? ".indexer"
1118                                                                    : repoIndexDirectory ).getAbsolutePath();
1119                             }
1120                         }
1121                         if ( StringUtils.isEmpty( repoIndexDirectory ) )
1122                         {
1123                             repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1124                                                            ".indexer" ).getAbsolutePath();
1125                         }
1126
1127                         if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1128                                                   FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1129                         {
1130                             // for prompted authentication
1131                             if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1132                             {
1133                                 try
1134                                 {
1135                                     if ( isAuthorized( request, repository ) )
1136                                     {
1137                                         mergedRepositoryContents.add( resourceFile );
1138                                         log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1139                                     }
1140                                 }
1141                                 catch ( DavException e )
1142                                 {
1143                                     // TODO: review exception handling
1144
1145                                     log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1146                                                activePrincipal, e.getMessage() );
1147
1148                                 }
1149
1150                             }
1151                             else
1152                             {
1153                                 // for the current user logged in
1154                                 try
1155                                 {
1156                                     if ( servletAuth.isAuthorized( activePrincipal, repository,
1157                                                                    WebdavMethodUtil.getMethodPermission(
1158                                                                        request.getMethod() ) ) )
1159                                     {
1160                                         mergedRepositoryContents.add( resourceFile );
1161                                         log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1162                                     }
1163                                 }
1164                                 catch ( UnauthorizedException e )
1165                                 {
1166                                     // TODO: review exception handling
1167
1168                                     log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1169                                                activePrincipal, e.getMessage() );
1170
1171                                 }
1172                             }
1173                         }
1174                     }
1175                 }
1176             }
1177         }
1178         else
1179         {
1180             throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1181         }
1182
1183         ArchivaVirtualDavResource resource =
1184             new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1185                                            this );
1186
1187         // compatibility with MRM-440 to ensure browsing the repository group works ok
1188         if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1189         {
1190             throw new BrowserRedirectException( resource.getHref() );
1191         }
1192
1193         return resource;
1194     }
1195
1196     protected String getActivePrincipal( DavServletRequest request )
1197     {
1198         User sessionUser = httpAuth.getSessionUser( request.getSession() );
1199         return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1200     }
1201
1202     /**
1203      * Check if the current user is authorized to access any of the repos
1204      *
1205      * @param request
1206      * @param repositories
1207      * @param activePrincipal
1208      * @return
1209      */
1210     private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1211     {
1212         // when no repositories configured it's impossible to browse nothing !
1213         // at least make possible to see nothing :-)
1214         if ( repositories == null || repositories.isEmpty() )
1215         {
1216             return true;
1217         }
1218
1219         boolean allow = false;
1220
1221         // if securitySession != null, it means that the user was prompted for authentication
1222         if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1223         {
1224             for ( String repository : repositories )
1225             {
1226                 try
1227                 {
1228                     if ( isAuthorized( request, repository ) )
1229                     {
1230                         allow = true;
1231                         break;
1232                     }
1233                 }
1234                 catch ( DavException e )
1235                 {
1236                     continue;
1237                 }
1238             }
1239         }
1240         else
1241         {
1242             for ( String repository : repositories )
1243             {
1244                 try
1245                 {
1246                     if ( servletAuth.isAuthorized( activePrincipal, repository,
1247                                                    WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1248                     {
1249                         allow = true;
1250                         break;
1251                     }
1252                 }
1253                 catch ( UnauthorizedException e )
1254                 {
1255                     continue;
1256                 }
1257             }
1258         }
1259
1260         return allow;
1261     }
1262
1263     private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1264         throws RepositoryMetadataException, DigesterException, IOException
1265     {
1266         File outputFile = new File( outputFilename );
1267         if ( outputFile.exists() )
1268         {
1269             FileUtils.deleteQuietly( outputFile );
1270         }
1271
1272         outputFile.getParentFile().mkdirs();
1273         RepositoryMetadataWriter.write( mergedMetadata, outputFile.toPath() );
1274
1275         createChecksumFile( outputFilename, digestSha1 );
1276         createChecksumFile( outputFilename, digestMd5 );
1277
1278         return outputFile;
1279     }
1280
1281     private void createChecksumFile( String path, Digester digester )
1282         throws DigesterException, IOException
1283     {
1284         File checksumFile = new File( path + digester.getFilenameExtension() );
1285         if ( !checksumFile.exists() )
1286         {
1287             FileUtils.deleteQuietly( checksumFile );
1288             checksum.createChecksum( new File( path ), digester );
1289         }
1290         else if ( !checksumFile.isFile() )
1291         {
1292             log.error( "Checksum file is not a file." );
1293         }
1294     }
1295
1296     private boolean isProjectReference( String requestedResource )
1297     {
1298         try
1299         {
1300             metadataTools.toVersionedReference( requestedResource );
1301             return false;
1302         }
1303         catch ( RepositoryMetadataException re )
1304         {
1305             return true;
1306         }
1307     }
1308
1309     protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1310                                               DavServletRequest request,
1311                                               RepositoryGroupConfiguration repositoryGroupConfiguration )
1312         throws DavException
1313     {
1314
1315         try
1316         {
1317             HttpSession session = request.getSession();
1318
1319             Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1320                 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1321                     TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1322             if ( temporaryGroupIndexMap == null )
1323             {
1324                 temporaryGroupIndexMap = new HashMap<>();
1325             }
1326
1327             TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1328
1329             if ( tmp != null && tmp.getDirectory() != null && Files.exists(tmp.getDirectory()))
1330             {
1331                 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1332                     repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1333                 {
1334                     log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1335                                "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1336                     indexMerger.cleanTemporaryGroupIndex( tmp );
1337                 }
1338                 else
1339                 {
1340                     log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1341                                "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1342                     return tmp.getDirectory().toFile();
1343                 }
1344             }
1345
1346             Set<String> authzRepos = new HashSet<String>();
1347
1348             String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1349
1350             for ( String repository : repositories )
1351             {
1352                 try
1353                 {
1354                     if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1355                     {
1356                         authzRepos.add( repository );
1357                         authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1358                     }
1359                 }
1360                 catch ( UnauthorizedException e )
1361                 {
1362                     // TODO: review exception handling
1363
1364                     log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1365                                e.getMessage() );
1366                 }
1367             }
1368             log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1369                       repositoryGroupConfiguration.getId(), authzRepos );
1370
1371             File tempRepoFile = Files.createTempDirectory( "temp" ).toFile();
1372             tempRepoFile.deleteOnExit();
1373
1374             IndexMergerRequest indexMergerRequest =
1375                 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1376                                         repositoryGroupConfiguration.getMergedIndexPath(),
1377                                         repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory(
1378                     tempRepoFile.toPath() ).temporary( true );
1379
1380             MergedRemoteIndexesTaskRequest taskRequest =
1381                 new MergedRemoteIndexesTaskRequest( indexMergerRequest, indexMerger );
1382
1383             MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1384
1385             IndexingContext indexingContext = job.execute().getIndexingContext();
1386
1387             File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1388             TemporaryGroupIndex temporaryGroupIndex =
1389                 new TemporaryGroupIndex( mergedRepoDir.toPath(), indexingContext.getId(), repositoryGroupConfiguration.getId(),
1390                                          repositoryGroupConfiguration.getMergedIndexTtl() ) //
1391                     .setCreationTime( new Date().getTime() );
1392             temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1393             session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1394                                   temporaryGroupIndexMap );
1395             return mergedRepoDir;
1396         }
1397         catch ( RepositoryAdminException e )
1398         {
1399             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1400         }
1401         catch ( IndexMergerException e )
1402         {
1403             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1404         }
1405         catch ( IOException e )
1406         {
1407             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1408         }
1409     }
1410
1411
1412     public void setServletAuth( ServletAuthenticator servletAuth )
1413     {
1414         this.servletAuth = servletAuth;
1415     }
1416
1417     public void setHttpAuth( HttpAuthenticator httpAuth )
1418     {
1419         this.httpAuth = httpAuth;
1420     }
1421
1422     public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1423     {
1424         this.scheduler = scheduler;
1425     }
1426
1427     public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1428     {
1429         this.archivaConfiguration = archivaConfiguration;
1430     }
1431
1432     public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1433     {
1434         this.repositoryFactory = repositoryFactory;
1435     }
1436
1437     public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1438     {
1439         this.repositoryRequest = repositoryRequest;
1440     }
1441
1442     public void setConnectors( RepositoryProxyConnectors connectors )
1443     {
1444         this.connectors = connectors;
1445     }
1446
1447     public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1448     {
1449         return remoteRepositoryAdmin;
1450     }
1451
1452     public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1453     {
1454         this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1455     }
1456
1457     public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1458     {
1459         return managedRepositoryAdmin;
1460     }
1461
1462     public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1463     {
1464         this.managedRepositoryAdmin = managedRepositoryAdmin;
1465     }
1466 }