1 package org.apache.maven.archiva.webdav;
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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
23 import java.io.FileNotFoundException;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.List;
29 import javax.servlet.http.HttpServletResponse;
31 import org.apache.commons.io.FileUtils;
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.jackrabbit.webdav.DavException;
34 import org.apache.jackrabbit.webdav.DavResource;
35 import org.apache.jackrabbit.webdav.DavResourceFactory;
36 import org.apache.jackrabbit.webdav.DavResourceLocator;
37 import org.apache.jackrabbit.webdav.DavServletRequest;
38 import org.apache.jackrabbit.webdav.DavServletResponse;
39 import org.apache.jackrabbit.webdav.DavSession;
40 import org.apache.jackrabbit.webdav.lock.LockManager;
41 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
42 import org.apache.maven.archiva.common.utils.PathUtil;
43 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
44 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
45 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
46 import org.apache.maven.archiva.model.ArtifactReference;
47 import org.apache.maven.archiva.policies.ProxyDownloadException;
48 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
49 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
50 import org.apache.maven.archiva.repository.RepositoryContentFactory;
51 import org.apache.maven.archiva.repository.RepositoryException;
52 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
53 import org.apache.maven.archiva.repository.audit.AuditEvent;
54 import org.apache.maven.archiva.repository.audit.AuditListener;
55 import org.apache.maven.archiva.repository.audit.Auditable;
56 import org.apache.maven.archiva.repository.content.RepositoryRequest;
57 import org.apache.maven.archiva.repository.layout.LayoutException;
58 import org.apache.maven.archiva.repository.metadata.MetadataTools;
59 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
60 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
61 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
62 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
63 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
64 import org.apache.maven.archiva.security.ServletAuthenticator;
65 import org.apache.maven.archiva.webdav.util.MimeTypes;
66 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
67 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
68 import org.apache.maven.model.DistributionManagement;
69 import org.apache.maven.model.Model;
70 import org.apache.maven.model.Relocation;
71 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
72 import org.codehaus.plexus.digest.ChecksumFile;
73 import org.codehaus.plexus.digest.Digester;
74 import org.codehaus.plexus.digest.DigesterException;
75 import org.codehaus.plexus.redback.authentication.AuthenticationException;
76 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
77 import org.codehaus.plexus.redback.authorization.AuthorizationException;
78 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
79 import org.codehaus.plexus.redback.policy.AccountLockedException;
80 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
81 import org.codehaus.plexus.redback.system.SecuritySession;
82 import org.codehaus.plexus.redback.users.User;
83 import org.codehaus.plexus.redback.users.UserManager;
84 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
85 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
90 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
92 public class ArchivaDavResourceFactory
93 implements DavResourceFactory, Auditable
95 private static final String PROXIED_SUFFIX = " (proxied)";
97 private static final String HTTP_PUT_METHOD = "PUT";
99 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
102 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
104 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
107 * @plexus.requirement
109 private RepositoryContentFactory repositoryFactory;
112 * @plexus.requirement
114 private RepositoryRequest repositoryRequest;
117 * @plexus.requirement role-hint="default"
119 private RepositoryProxyConnectors connectors;
122 * @plexus.requirement
124 private MetadataTools metadataTools;
127 * @plexus.requirement
129 private MimeTypes mimeTypes;
132 * @plexus.requirement
134 private ArchivaConfiguration archivaConfiguration;
137 * @plexus.requirement
139 private ServletAuthenticator servletAuth;
142 * @plexus.requirement role-hint="basic"
144 private HttpAuthenticator httpAuth;
147 * Lock Manager - use simple implementation from JackRabbit
149 private final LockManager lockManager = new SimpleLockManager();
152 * @plexus.requirement
154 private RepositoryContentConsumers consumers;
157 * @plexus.requirement
159 private ChecksumFile checksum;
162 * @plexus.requirement role-hint="sha1"
164 private Digester digestSha1;
167 * @plexus.requirement role-hint="md5";
169 private Digester digestMd5;
171 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
172 final DavServletResponse response )
175 checkLocatorIsInstanceOfRepositoryLocator( locator );
176 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
178 RepositoryGroupConfiguration repoGroupConfig =
179 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
180 List<String> repositories = new ArrayList<String>();
182 boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
183 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
185 if ( repoGroupConfig != null )
187 if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
189 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
190 "Write method not allowed for repository groups." );
192 repositories.addAll( repoGroupConfig.getRepositories() );
194 // handle browse requests for virtual repos
195 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
197 return getResource( request, repositories, archivaLocator );
202 repositories.add( archivaLocator.getRepositoryId() );
205 //MRM-419 - Windows Webdav support. Should not 404 if there is no content.
206 if (StringUtils.isEmpty(archivaLocator.getRepositoryId()))
208 throw new DavException(HttpServletResponse.SC_NO_CONTENT);
211 List<DavResource> availableResources = new ArrayList<DavResource>();
212 List<String> resourcesInAbsolutePath = new ArrayList<String>();
213 DavException e = null;
215 for ( String repositoryId : repositories )
217 ManagedRepositoryContent managedRepository = null;
221 managedRepository = getManagedRepository( repositoryId );
223 catch ( DavException de )
225 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
226 repositoryId + ">" );
229 DavResource resource = null;
231 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
233 if ( managedRepository != null )
237 if( isAuthorized( request, repositoryId ) )
239 LogicalResource logicalResource =
240 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
244 resource = doGet( managedRepository, request, archivaLocator, logicalResource );
249 resource = doPut( managedRepository, request, archivaLocator, logicalResource );
253 catch ( DavException de )
259 if( resource == null )
261 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
265 availableResources.add( resource );
267 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
268 resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
273 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Repository does not exist" );
278 if ( availableResources.isEmpty() )
283 String requestedResource = request.getRequestURI();
285 // MRM-872 : merge all available metadata
286 // merge metadata only when requested via the repo group
287 if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) ) &&
288 repoGroupConfig != null )
290 // this should only be at the project level not version level!
291 if( isProjectReference( requestedResource ) )
293 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
294 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
296 ArchivaDavResource res = ( ArchivaDavResource ) availableResources.get( 0 );
297 String filePath = StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
298 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
300 // for MRM-872 handle checksums of the merged metadata files
301 if( repositoryRequest.isSupportFile( requestedResource ) )
303 File metadataChecksum = new File( filePath + "."
304 + StringUtils.substringAfterLast( requestedResource, "." ) );
305 if( metadataChecksum.exists() )
307 LogicalResource logicalResource =
308 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
310 String activePrincipal = getActivePrincipal( request );
312 ArchivaDavResource metadataChecksumResource =
313 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
314 null, request.getRemoteAddr(), activePrincipal,
315 request.getDavSession(), archivaLocator, this, mimeTypes,
316 auditListeners, consumers );
317 availableResources.add( 0, metadataChecksumResource );
321 { // merge the metadata of all repos under group
322 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
323 for ( String resourceAbsPath : resourcesInAbsolutePath )
327 File metadataFile = new File( resourceAbsPath );
328 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
329 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
331 catch ( RepositoryMetadataException r )
333 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
334 "Error occurred while reading metadata file." );
340 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
342 LogicalResource logicalResource =
343 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
345 String activePrincipal = getActivePrincipal( request );
347 ArchivaDavResource metadataResource =
348 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
349 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
350 archivaLocator, this, mimeTypes, auditListeners, consumers );
351 availableResources.add( 0, metadataResource );
353 catch ( RepositoryMetadataException r )
355 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
356 "Error occurred while writing metadata file." );
358 catch ( IOException ie )
360 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
361 "Error occurred while generating checksum files." );
363 catch ( DigesterException de )
365 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
366 "Error occurred while generating checksum files." );
372 DavResource resource = availableResources.get( 0 );
373 setHeaders(response, locator, resource );
375 // compatibility with MRM-440 to ensure browsing the repository works ok
376 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
378 throw new BrowserRedirectException( resource.getHref() );
380 resource.addLockManager(lockManager);
384 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
387 checkLocatorIsInstanceOfRepositoryLocator( locator );
388 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
390 DavResource resource = null;
391 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
393 ManagedRepositoryContent managedRepository = getManagedRepository( archivaLocator.getRepositoryId() );
394 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
395 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
397 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
398 managedRepository.getRepository(), davSession, archivaLocator, this, mimeTypes,
399 auditListeners, consumers );
401 resource.addLockManager(lockManager);
405 private DavResource doGet( ManagedRepositoryContent managedRepository, DavServletRequest request,
406 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
409 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
411 //MRM-893, dont send back a file when user intentionally wants a directory
412 if ( locator.getHref( false ).endsWith( "/" ) )
414 if ( ! resourceFile.isDirectory() )
416 //force a resource not found
421 String activePrincipal = getActivePrincipal( request );
423 ArchivaDavResource resource =
424 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
425 managedRepository.getRepository(), request.getRemoteAddr(), activePrincipal,
426 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
428 if ( !resource.isCollection() )
430 boolean previouslyExisted = resourceFile.exists();
432 // At this point the incoming request can either be in default or
433 // legacy layout format.
434 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
438 // Perform an adjustment of the resource to the managed
439 // repository expected path.
440 String localResourcePath =
441 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
442 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
444 catch ( LayoutException e )
446 if ( previouslyExisted )
450 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
453 // Attempt to fetch the resource from any defined proxy.
456 String repositoryId = locator.getRepositoryId();
457 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) + PROXIED_SUFFIX;
458 triggerAuditEvent( request.getRemoteAddr(), repositoryId, logicalResource.getPath(), event,
462 if ( !resourceFile.exists() )
469 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
470 managedRepository.getRepository(), request.getRemoteAddr(),
471 activePrincipal, request.getDavSession(), locator, this, mimeTypes,
472 auditListeners, consumers );
478 private DavResource doPut( ManagedRepositoryContent managedRepository, DavServletRequest request,
479 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
483 * Create parent directories that don't exist when writing a file This actually makes this implementation not
484 * compliant to the WebDAV RFC - but we have enough knowledge about how the collection is being used to do this
485 * reasonably and some versions of Maven's WebDAV don't correctly create the collections themselves.
488 File rootDirectory = new File( managedRepository.getRepoRoot() );
489 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
491 String activePrincipal = getActivePrincipal( request );
493 if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
496 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
497 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR,
501 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
503 return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
504 managedRepository.getRepository(), request.getRemoteAddr(), activePrincipal,
505 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
508 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
509 LogicalResource resource )
512 if ( repositoryRequest.isSupportFile( resource.getPath() ) )
514 File proxiedFile = connectors.fetchFromProxies( managedRepository, resource.getPath() );
516 return ( proxiedFile != null );
519 // Is it a Metadata resource?
520 if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
522 return connectors.fetchMetatadaFromProxies(managedRepository, resource.getPath()) != null;
525 // Not any of the above? Then it's gotta be an artifact reference.
528 // Get the artifact reference in a layout neutral way.
529 ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
531 if ( artifact != null )
533 applyServerSideRelocation( managedRepository, artifact );
535 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
537 resource.setPath( managedRepository.toPath( artifact ) );
539 return ( proxiedFile != null );
542 catch ( LayoutException e )
546 catch ( ProxyDownloadException e )
548 log.error( e.getMessage(), e );
549 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
555 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
556 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
559 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
560 * metadatas and serving the expected artifact.
562 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
563 throws ProxyDownloadException
565 if ( "pom".equals( artifact.getType() ) )
570 // Build the artifact POM reference
571 ArtifactReference pomReference = new ArtifactReference();
572 pomReference.setGroupId( artifact.getGroupId() );
573 pomReference.setArtifactId( artifact.getArtifactId() );
574 pomReference.setVersion( artifact.getVersion() );
575 pomReference.setType( "pom" );
577 // Get the artifact POM from proxied repositories if needed
578 connectors.fetchFromProxies( managedRepository, pomReference );
580 // Open and read the POM from the managed repo
581 File pom = managedRepository.toFile( pomReference );
590 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
591 FileReader reader = new FileReader( pom );
595 model = new MavenXpp3Reader().read( reader );
605 DistributionManagement dist = model.getDistributionManagement();
608 Relocation relocation = dist.getRelocation();
609 if ( relocation != null )
611 // artifact is relocated : update the repositoryPath
612 if ( relocation.getGroupId() != null )
614 artifact.setGroupId( relocation.getGroupId() );
616 if ( relocation.getArtifactId() != null )
618 artifact.setArtifactId( relocation.getArtifactId() );
620 if ( relocation.getVersion() != null )
622 artifact.setVersion( relocation.getVersion() );
627 catch ( FileNotFoundException e )
629 // Artifact has no POM in repo : ignore
631 catch ( IOException e )
633 // Unable to read POM : ignore.
635 catch ( XmlPullParserException e )
637 // Invalid POM : ignore
642 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
645 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
646 event.setRemoteIP( remoteIP );
648 for ( AuditListener listener : auditListeners )
650 listener.auditEvent( event );
654 public void addAuditListener( AuditListener listener )
656 this.auditListeners.add( listener );
659 public void clearAuditListeners()
661 this.auditListeners.clear();
664 public void removeAuditListener( AuditListener listener )
666 this.auditListeners.remove( listener );
669 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
671 // [MRM-503] - Metadata file need Pragma:no-cache response
673 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
675 response.addHeader( "Pragma", "no-cache" );
676 response.addHeader( "Cache-Control", "no-cache" );
679 //We need to specify this so connecting wagons can work correctly
680 response.addDateHeader("last-modified", resource.getModificationTime());
682 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
685 private ManagedRepositoryContent getManagedRepository( String respositoryId )
688 if ( respositoryId != null )
692 return repositoryFactory.getManagedRepositoryContent( respositoryId );
694 catch ( RepositoryNotFoundException e )
696 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
698 catch ( RepositoryException e )
700 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
706 private void checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
709 if ( !( locator instanceof RepositoryLocator ) )
711 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
712 "Locator does not implement RepositoryLocator" );
716 class LogicalResource
720 public LogicalResource( String path )
725 public String getPath()
730 public void setPath( String path )
736 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
741 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
742 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
744 return servletAuth.isAuthenticated( request, result ) &&
745 servletAuth.isAuthorized( request, securitySession, repositoryId,
746 WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
748 catch ( AuthenticationException e )
750 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
752 // safety check for MRM-911
753 String guest = UserManager.GUEST_USERNAME;
756 if( servletAuth.isAuthorized( guest,
757 ( ( ArchivaDavResourceLocator ) request.getRequestLocator() ).getRepositoryId(), isPut ) )
762 catch ( UnauthorizedException ae )
764 throw new UnauthorizedDavException( repositoryId,
765 "You are not authenticated and authorized to access any repository." );
768 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
770 catch ( MustChangePasswordException e )
772 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
774 catch ( AccountLockedException e )
776 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
778 catch ( AuthorizationException e )
780 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
781 "Fatal Authorization Subsystem Error." );
783 catch ( UnauthorizedException e )
785 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
789 private DavResource getResource( DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator )
792 List<File> mergedRepositoryContents = new ArrayList<File>();
793 LogicalResource logicalResource =
794 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
797 // if the current user logged in has permission to any of the repositories, allow user to
798 // browse the repo group but displaying only the repositories which the user has permission to access.
799 // otherwise, prompt for authentication.
801 String activePrincipal = getActivePrincipal( request );
803 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
807 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
809 for( String repository : repositories )
811 // for prompted authentication
812 if( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
816 if( isAuthorized( request, repository ) )
818 getResource( locator, mergedRepositoryContents, logicalResource, repository );
821 catch ( DavException e )
828 // for the current user logged in
831 if( servletAuth.isAuthorized( activePrincipal, repository, isPut ) )
833 getResource( locator, mergedRepositoryContents, logicalResource, repository );
836 catch ( UnauthorizedException e )
845 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
848 ArchivaVirtualDavResource resource =
849 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this );
851 // compatibility with MRM-440 to ensure browsing the repository group works ok
852 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
854 throw new BrowserRedirectException( resource.getHref() );
860 private String getActivePrincipal( DavServletRequest request )
862 User sessionUser = httpAuth.getSessionUser( request.getSession() );
863 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
866 private void getResource( ArchivaDavResourceLocator locator, List<File> mergedRepositoryContents,
867 LogicalResource logicalResource, String repository )
870 ManagedRepositoryContent managedRepository = null;
874 managedRepository = getManagedRepository( repository );
876 catch ( DavException de )
878 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
882 if ( !locator.getResourcePath().startsWith( ArchivaVirtualDavResource.HIDDEN_PATH_PREFIX ) )
884 if( managedRepository != null )
886 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
887 if( resourceFile.exists() )
889 mergedRepositoryContents.add( resourceFile );
896 * Check if the current user is authorized to access any of the repos
899 * @param repositories
900 * @param activePrincipal
903 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
905 boolean allow = false;
908 // if securitySession != null, it means that the user was prompted for authentication
909 if( httpAuth.getSecuritySession( request.getSession() ) != null )
911 for( String repository : repositories )
915 if( isAuthorized( request, repository ) )
921 catch( DavException e )
929 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
930 for( String repository : repositories )
934 if( servletAuth.isAuthorized( activePrincipal, repository, isPut ) )
940 catch ( UnauthorizedException e )
950 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
951 throws RepositoryMetadataException, DigesterException, IOException
953 File outputFile = new File( outputFilename );
954 if( outputFile.exists() )
956 FileUtils.deleteQuietly( outputFile );
959 outputFile.getParentFile().mkdirs();
960 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
962 createChecksumFile( outputFilename, digestSha1 );
963 createChecksumFile( outputFilename, digestMd5 );
968 private void createChecksumFile( String path, Digester digester )
969 throws DigesterException, IOException
971 File checksumFile = new File( path + digester.getFilenameExtension() );
972 if ( !checksumFile.exists() )
974 FileUtils.deleteQuietly( checksumFile );
975 checksum.createChecksum( new File( path ), digester );
977 else if ( !checksumFile.isFile() )
979 log.error( "Checksum file is not a file." );
983 private boolean isProjectReference( String requestedResource )
987 metadataTools.toVersionedReference( requestedResource );
990 catch ( RepositoryMetadataException re )
996 public void setServletAuth( ServletAuthenticator servletAuth )
998 this.servletAuth = servletAuth;
1001 public void setHttpAuth( HttpAuthenticator httpAuth )
1003 this.httpAuth = httpAuth;