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