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