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.model.VersionedReference;
48 import org.apache.maven.archiva.policies.ProxyDownloadException;
49 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
50 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
51 import org.apache.maven.archiva.repository.RepositoryContentFactory;
52 import org.apache.maven.archiva.repository.RepositoryException;
53 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
54 import org.apache.maven.archiva.repository.audit.AuditEvent;
55 import org.apache.maven.archiva.repository.audit.AuditListener;
56 import org.apache.maven.archiva.repository.audit.Auditable;
57 import org.apache.maven.archiva.repository.content.RepositoryRequest;
58 import org.apache.maven.archiva.repository.layout.LayoutException;
59 import org.apache.maven.archiva.repository.metadata.MetadataTools;
60 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
61 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
62 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
63 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
64 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
65 import org.apache.maven.archiva.security.ServletAuthenticator;
66 import org.apache.maven.archiva.webdav.util.MimeTypes;
67 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
68 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
69 import org.apache.maven.model.DistributionManagement;
70 import org.apache.maven.model.Model;
71 import org.apache.maven.model.Relocation;
72 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
73 import org.codehaus.plexus.digest.ChecksumFile;
74 import org.codehaus.plexus.digest.Digester;
75 import org.codehaus.plexus.digest.DigesterException;
76 import org.codehaus.plexus.redback.authentication.AuthenticationException;
77 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
78 import org.codehaus.plexus.redback.authorization.AuthorizationException;
79 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
80 import org.codehaus.plexus.redback.policy.AccountLockedException;
81 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
82 import org.codehaus.plexus.redback.system.SecuritySession;
83 import org.codehaus.plexus.redback.system.SecuritySystemConstants;
84 import org.codehaus.plexus.redback.users.User;
85 import org.codehaus.plexus.redback.users.UserManager;
86 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
87 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
94 public class ArchivaDavResourceFactory
95 implements DavResourceFactory, Auditable
97 private static final String PROXIED_SUFFIX = " (proxied)";
99 private static final String HTTP_PUT_METHOD = "PUT";
101 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
104 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
106 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
109 * @plexus.requirement
111 private RepositoryContentFactory repositoryFactory;
114 * @plexus.requirement
116 private RepositoryRequest repositoryRequest;
119 * @plexus.requirement role-hint="default"
121 private RepositoryProxyConnectors connectors;
124 * @plexus.requirement
126 private MetadataTools metadataTools;
129 * @plexus.requirement
131 private MimeTypes mimeTypes;
134 * @plexus.requirement
136 private ArchivaConfiguration archivaConfiguration;
139 * @plexus.requirement
141 private ServletAuthenticator servletAuth;
144 * @plexus.requirement role-hint="basic"
146 private HttpAuthenticator httpAuth;
149 * Lock Manager - use simple implementation from JackRabbit
151 private final LockManager lockManager = new SimpleLockManager();
154 * @plexus.requirement
156 private RepositoryContentConsumers consumers;
159 * @plexus.requirement
161 private ChecksumFile checksum;
164 * @plexus.requirement role-hint="sha1"
166 private Digester digestSha1;
169 * @plexus.requirement role-hint="md5";
171 private Digester digestMd5;
173 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
174 final DavServletResponse response )
177 checkLocatorIsInstanceOfRepositoryLocator( locator );
178 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
180 RepositoryGroupConfiguration repoGroupConfig =
181 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
182 List<String> repositories = new ArrayList<String>();
184 boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
185 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
187 if ( repoGroupConfig != null )
189 if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
191 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
192 "Write method not allowed for repository groups." );
194 repositories.addAll( repoGroupConfig.getRepositories() );
196 // handle browse requests for virtual repos
197 if ( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ).endsWith( "/" ) )
199 return getResource( request, repositories, archivaLocator );
204 repositories.add( archivaLocator.getRepositoryId() );
207 //MRM-419 - Windows Webdav support. Should not 404 if there is no content.
208 if (StringUtils.isEmpty(archivaLocator.getRepositoryId()))
210 throw new DavException(HttpServletResponse.SC_NO_CONTENT);
213 List<DavResource> availableResources = new ArrayList<DavResource>();
214 List<String> resourcesInAbsolutePath = new ArrayList<String>();
215 DavException e = null;
217 for ( String repositoryId : repositories )
219 ManagedRepositoryContent managedRepository = null;
223 managedRepository = getManagedRepository( repositoryId );
225 catch ( DavException de )
227 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
228 repositoryId + ">" );
231 DavResource resource = null;
233 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
235 if ( managedRepository != null )
239 if( isAuthorized( request, repositoryId ) )
241 LogicalResource logicalResource =
242 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
246 resource = doGet( managedRepository, request, archivaLocator, logicalResource );
251 resource = doPut( managedRepository, request, archivaLocator, logicalResource );
255 catch ( DavException de )
261 if( resource == null )
263 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
267 availableResources.add( resource );
269 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
270 resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
275 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Repository does not exist" );
280 if ( availableResources.isEmpty() )
285 String requestedResource = request.getRequestURI();
287 // MRM-872 : merge all available metadata
288 // merge metadata only when requested via the repo group
289 if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) ) &&
290 repoGroupConfig != null )
292 // this should only be at the project level not version level!
293 if( isProjectReference( requestedResource ) )
295 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
296 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
298 ArchivaDavResource res = ( ArchivaDavResource ) availableResources.get( 0 );
299 String filePath = StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
300 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
302 // for MRM-872 handle checksums of the merged metadata files
303 if( repositoryRequest.isSupportFile( requestedResource ) )
305 File metadataChecksum = new File( filePath + "."
306 + StringUtils.substringAfterLast( requestedResource, "." ) );
307 if( metadataChecksum.exists() )
309 LogicalResource logicalResource =
310 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
312 String activePrincipal = getActivePrincipal( request );
314 ArchivaDavResource metadataChecksumResource =
315 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
316 null, request.getRemoteAddr(), activePrincipal,
317 request.getDavSession(), archivaLocator, this, mimeTypes,
318 auditListeners, consumers );
319 availableResources.add( 0, metadataChecksumResource );
323 { // merge the metadata of all repos under group
324 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
325 for ( String resourceAbsPath : resourcesInAbsolutePath )
329 File metadataFile = new File( resourceAbsPath );
330 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
331 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
333 catch ( RepositoryMetadataException r )
335 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
336 "Error occurred while reading metadata file." );
342 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
344 LogicalResource logicalResource =
345 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
347 String activePrincipal = getActivePrincipal( request );
349 ArchivaDavResource metadataResource =
350 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
351 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
352 archivaLocator, this, mimeTypes, auditListeners, consumers );
353 availableResources.add( 0, metadataResource );
355 catch ( RepositoryMetadataException r )
357 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
358 "Error occurred while writing metadata file." );
360 catch ( IOException ie )
362 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
363 "Error occurred while generating checksum files." );
365 catch ( DigesterException de )
367 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
368 "Error occurred while generating checksum files." );
374 DavResource resource = availableResources.get( 0 );
375 setHeaders(response, locator, resource );
377 // compatibility with MRM-440 to ensure browsing the repository works ok
378 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
380 throw new BrowserRedirectException( resource.getHref() );
382 resource.addLockManager(lockManager);
386 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
389 checkLocatorIsInstanceOfRepositoryLocator( locator );
390 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
392 DavResource resource = null;
393 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
395 ManagedRepositoryContent managedRepository = getManagedRepository( archivaLocator.getRepositoryId() );
396 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
397 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
399 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
400 managedRepository.getRepository(), davSession, archivaLocator, this, mimeTypes,
401 auditListeners, consumers );
403 resource.addLockManager(lockManager);
407 private DavResource doGet( ManagedRepositoryContent managedRepository, DavServletRequest request,
408 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
411 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
413 //MRM-893, dont send back a file when user intentionally wants a directory
414 if ( locator.getHref( false ).endsWith( "/" ) )
416 if ( ! resourceFile.isDirectory() )
418 //force a resource not found
423 String activePrincipal = getActivePrincipal( request );
425 ArchivaDavResource resource =
426 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
427 managedRepository.getRepository(), request.getRemoteAddr(), activePrincipal,
428 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
430 if ( !resource.isCollection() )
432 boolean previouslyExisted = resourceFile.exists();
434 // At this point the incoming request can either be in default or
435 // legacy layout format.
436 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
440 // Perform an adjustment of the resource to the managed
441 // repository expected path.
442 String localResourcePath =
443 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
444 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
446 catch ( LayoutException e )
448 if ( previouslyExisted )
452 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
455 // Attempt to fetch the resource from any defined proxy.
458 String repositoryId = locator.getRepositoryId();
459 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) + PROXIED_SUFFIX;
460 triggerAuditEvent( request.getRemoteAddr(), repositoryId, logicalResource.getPath(), event,
464 if ( !resourceFile.exists() )
471 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
472 managedRepository.getRepository(), request.getRemoteAddr(),
473 activePrincipal, request.getDavSession(), locator, this, mimeTypes,
474 auditListeners, consumers );
480 private DavResource doPut( ManagedRepositoryContent managedRepository, DavServletRequest request,
481 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
485 * Create parent directories that don't exist when writing a file This actually makes this implementation not
486 * compliant to the WebDAV RFC - but we have enough knowledge about how the collection is being used to do this
487 * reasonably and some versions of Maven's WebDAV don't correctly create the collections themselves.
490 File rootDirectory = new File( managedRepository.getRepoRoot() );
491 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
493 String activePrincipal = getActivePrincipal( request );
495 if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
498 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
499 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR,
503 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
505 return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
506 managedRepository.getRepository(), request.getRemoteAddr(), activePrincipal,
507 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
510 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
511 LogicalResource resource )
514 if ( repositoryRequest.isSupportFile( resource.getPath() ) )
516 File proxiedFile = connectors.fetchFromProxies( managedRepository, resource.getPath() );
518 return ( proxiedFile != null );
521 // Is it a Metadata resource?
522 if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
524 return connectors.fetchMetatadaFromProxies(managedRepository, resource.getPath()) != null;
527 // Not any of the above? Then it's gotta be an artifact reference.
530 // Get the artifact reference in a layout neutral way.
531 ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
533 if ( artifact != null )
535 applyServerSideRelocation( managedRepository, artifact );
537 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
539 resource.setPath( managedRepository.toPath( artifact ) );
541 return ( proxiedFile != null );
544 catch ( LayoutException e )
548 catch ( ProxyDownloadException e )
550 log.error( e.getMessage(), e );
551 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
557 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
558 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
561 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
562 * metadatas and serving the expected artifact.
564 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
565 throws ProxyDownloadException
567 if ( "pom".equals( artifact.getType() ) )
572 // Build the artifact POM reference
573 ArtifactReference pomReference = new ArtifactReference();
574 pomReference.setGroupId( artifact.getGroupId() );
575 pomReference.setArtifactId( artifact.getArtifactId() );
576 pomReference.setVersion( artifact.getVersion() );
577 pomReference.setType( "pom" );
579 // Get the artifact POM from proxied repositories if needed
580 connectors.fetchFromProxies( managedRepository, pomReference );
582 // Open and read the POM from the managed repo
583 File pom = managedRepository.toFile( pomReference );
592 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
593 FileReader reader = new FileReader( pom );
597 model = new MavenXpp3Reader().read( reader );
607 DistributionManagement dist = model.getDistributionManagement();
610 Relocation relocation = dist.getRelocation();
611 if ( relocation != null )
613 // artifact is relocated : update the repositoryPath
614 if ( relocation.getGroupId() != null )
616 artifact.setGroupId( relocation.getGroupId() );
618 if ( relocation.getArtifactId() != null )
620 artifact.setArtifactId( relocation.getArtifactId() );
622 if ( relocation.getVersion() != null )
624 artifact.setVersion( relocation.getVersion() );
629 catch ( FileNotFoundException e )
631 // Artifact has no POM in repo : ignore
633 catch ( IOException e )
635 // Unable to read POM : ignore.
637 catch ( XmlPullParserException e )
639 // Invalid POM : ignore
644 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
647 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
648 event.setRemoteIP( remoteIP );
650 for ( AuditListener listener : auditListeners )
652 listener.auditEvent( event );
656 public void addAuditListener( AuditListener listener )
658 this.auditListeners.add( listener );
661 public void clearAuditListeners()
663 this.auditListeners.clear();
666 public void removeAuditListener( AuditListener listener )
668 this.auditListeners.remove( listener );
671 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
673 // [MRM-503] - Metadata file need Pragma:no-cache response
675 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
677 response.addHeader( "Pragma", "no-cache" );
678 response.addHeader( "Cache-Control", "no-cache" );
681 //We need to specify this so connecting wagons can work correctly
682 response.addDateHeader("last-modified", resource.getModificationTime());
684 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
687 private ManagedRepositoryContent getManagedRepository( String respositoryId )
690 if ( respositoryId != null )
694 return repositoryFactory.getManagedRepositoryContent( respositoryId );
696 catch ( RepositoryNotFoundException e )
698 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
700 catch ( RepositoryException e )
702 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
708 private void checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
711 if ( !( locator instanceof RepositoryLocator ) )
713 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
714 "Locator does not implement RepositoryLocator" );
718 class LogicalResource
722 public LogicalResource( String path )
727 public String getPath()
732 public void setPath( String path )
738 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
743 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
744 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
746 return servletAuth.isAuthenticated( request, result ) &&
747 servletAuth.isAuthorized( request, securitySession, repositoryId,
748 WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
750 catch ( AuthenticationException e )
752 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
754 // safety check for MRM-911
755 String guest = UserManager.GUEST_USERNAME;
758 if( servletAuth.isAuthorized( guest,
759 ( ( ArchivaDavResourceLocator ) request.getRequestLocator() ).getRepositoryId(), isPut ) )
764 catch ( UnauthorizedException ae )
766 throw new UnauthorizedDavException( repositoryId,
767 "You are not authenticated and authorized to access any repository." );
770 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
772 catch ( MustChangePasswordException e )
774 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
776 catch ( AccountLockedException e )
778 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
780 catch ( AuthorizationException e )
782 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
783 "Fatal Authorization Subsystem Error." );
785 catch ( UnauthorizedException e )
787 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
791 private DavResource getResource( DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator )
794 List<File> mergedRepositoryContents = new ArrayList<File>();
795 LogicalResource logicalResource =
796 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
799 // if the current user logged in has permission to any of the repositories, allow user to
800 // browse the repo group but displaying only the repositories which the user has permission to access.
801 // otherwise, prompt for authentication.
803 String activePrincipal = getActivePrincipal( request );
805 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
809 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
811 for( String repository : repositories )
813 // for prompted authentication
814 if( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
818 if( isAuthorized( request, repository ) )
820 getResource( locator, mergedRepositoryContents, logicalResource, repository );
823 catch ( DavException e )
830 // for the current user logged in
833 if( servletAuth.isAuthorized( activePrincipal, repository, isPut ) )
835 getResource( locator, mergedRepositoryContents, logicalResource, repository );
838 catch ( UnauthorizedException e )
847 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
850 ArchivaVirtualDavResource resource =
851 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this );
853 // compatibility with MRM-440 to ensure browsing the repository group works ok
854 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
856 throw new BrowserRedirectException( resource.getHref() );
862 private String getActivePrincipal( DavServletRequest request )
864 User sessionUser = httpAuth.getSessionUser( request.getSession() );
865 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
868 private void getResource( ArchivaDavResourceLocator locator, List<File> mergedRepositoryContents,
869 LogicalResource logicalResource, String repository )
872 ManagedRepositoryContent managedRepository = null;
876 managedRepository = getManagedRepository( repository );
878 catch ( DavException de )
880 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
884 if ( !locator.getResourcePath().startsWith( ArchivaVirtualDavResource.HIDDEN_PATH_PREFIX ) )
886 if( managedRepository != null )
888 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
889 if( resourceFile.exists() )
891 mergedRepositoryContents.add( resourceFile );
898 * Check if the current user is authorized to access any of the repos
901 * @param repositories
902 * @param activePrincipal
905 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
907 boolean allow = false;
910 // if securitySession != null, it means that the user was prompted for authentication
911 if( httpAuth.getSecuritySession( request.getSession() ) != null )
913 for( String repository : repositories )
917 if( isAuthorized( request, repository ) )
923 catch( DavException e )
931 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
932 for( String repository : repositories )
936 if( servletAuth.isAuthorized( activePrincipal, repository, isPut ) )
942 catch ( UnauthorizedException e )
952 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
953 throws RepositoryMetadataException, DigesterException, IOException
955 File outputFile = new File( outputFilename );
956 if( outputFile.exists() )
958 FileUtils.deleteQuietly( outputFile );
961 outputFile.getParentFile().mkdirs();
962 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
964 createChecksumFile( outputFilename, digestSha1 );
965 createChecksumFile( outputFilename, digestMd5 );
970 private void createChecksumFile( String path, Digester digester )
971 throws DigesterException, IOException
973 File checksumFile = new File( path + digester.getFilenameExtension() );
974 if ( !checksumFile.exists() )
976 FileUtils.deleteQuietly( checksumFile );
977 checksum.createChecksum( new File( path ), digester );
979 else if ( !checksumFile.isFile() )
981 log.error( "Checksum file is not a file." );
985 private boolean isProjectReference( String requestedResource )
989 VersionedReference versionRef = metadataTools.toVersionedReference( requestedResource );
992 catch ( RepositoryMetadataException re )
998 public void setServletAuth( ServletAuthenticator servletAuth )
1000 this.servletAuth = servletAuth;
1003 public void setHttpAuth( HttpAuthenticator httpAuth )
1005 this.httpAuth = httpAuth;