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