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