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.HashMap;
28 import java.util.List;
31 import javax.servlet.http.HttpServletResponse;
33 import org.apache.commons.io.FileUtils;
34 import org.apache.commons.lang.StringUtils;
35 import org.apache.jackrabbit.webdav.DavException;
36 import org.apache.jackrabbit.webdav.DavResource;
37 import org.apache.jackrabbit.webdav.DavResourceFactory;
38 import org.apache.jackrabbit.webdav.DavResourceLocator;
39 import org.apache.jackrabbit.webdav.DavServletRequest;
40 import org.apache.jackrabbit.webdav.DavServletResponse;
41 import org.apache.jackrabbit.webdav.DavSession;
42 import org.apache.jackrabbit.webdav.lock.LockManager;
43 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
44 import org.apache.maven.archiva.common.utils.PathUtil;
45 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
46 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
47 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
48 import org.apache.maven.archiva.model.ArtifactReference;
49 import org.apache.maven.archiva.model.ProjectReference;
50 import org.apache.maven.archiva.model.VersionedReference;
51 import org.apache.maven.archiva.policies.ProxyDownloadException;
52 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
53 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
54 import org.apache.maven.archiva.repository.RepositoryContentFactory;
55 import org.apache.maven.archiva.repository.RepositoryException;
56 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
57 import org.apache.maven.archiva.repository.audit.AuditEvent;
58 import org.apache.maven.archiva.repository.audit.AuditListener;
59 import org.apache.maven.archiva.repository.audit.Auditable;
60 import org.apache.maven.archiva.repository.content.RepositoryRequest;
61 import org.apache.maven.archiva.repository.layout.LayoutException;
62 import org.apache.maven.archiva.repository.metadata.MetadataTools;
63 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
64 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
65 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
66 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
67 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
68 import org.apache.maven.archiva.security.ArchivaXworkUser;
69 import org.apache.maven.archiva.security.ServletAuthenticator;
70 import org.apache.maven.archiva.webdav.util.MimeTypes;
71 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
72 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
73 import org.apache.maven.model.DistributionManagement;
74 import org.apache.maven.model.Model;
75 import org.apache.maven.model.Relocation;
76 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
77 import org.codehaus.plexus.digest.ChecksumFile;
78 import org.codehaus.plexus.digest.Digester;
79 import org.codehaus.plexus.digest.DigesterException;
80 import org.codehaus.plexus.redback.authentication.AuthenticationException;
81 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
82 import org.codehaus.plexus.redback.authorization.AuthorizationException;
83 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
84 import org.codehaus.plexus.redback.policy.AccountLockedException;
85 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
86 import org.codehaus.plexus.redback.system.SecuritySession;
87 import org.codehaus.plexus.redback.system.SecuritySystemConstants;
88 import org.codehaus.plexus.redback.xwork.filter.authentication.HttpAuthenticator;
89 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
93 import com.opensymphony.xwork.ActionContext;
96 * @author <a href="mailto:james@atlassian.com">James William Dumay</a>
97 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
99 public class ArchivaDavResourceFactory
100 implements DavResourceFactory, Auditable
102 private static final String PROXIED_SUFFIX = " (proxied)";
104 private static final String HTTP_PUT_METHOD = "PUT";
106 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
109 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
111 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
114 * @plexus.requirement
116 private RepositoryContentFactory repositoryFactory;
119 * @plexus.requirement
121 private RepositoryRequest repositoryRequest;
124 * @plexus.requirement role-hint="default"
126 private RepositoryProxyConnectors connectors;
129 * @plexus.requirement
131 private MetadataTools metadataTools;
134 * @plexus.requirement
136 private MimeTypes mimeTypes;
139 * @plexus.requirement
141 private ArchivaConfiguration archivaConfiguration;
144 * @plexus.requirement
146 private ServletAuthenticator servletAuth;
149 * @plexus.requirement role-hint="basic"
151 private HttpAuthenticator httpAuth;
154 * Lock Manager - use simple implementation from JackRabbit
156 private final LockManager lockManager = new SimpleLockManager();
159 * @plexus.requirement
161 private RepositoryContentConsumers consumers;
164 * @plexus.requirement
166 private ChecksumFile checksum;
169 * @plexus.requirement role-hint="sha1"
171 private Digester digestSha1;
174 * @plexus.requirement role-hint="md5";
176 private Digester digestMd5;
178 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
179 final DavServletResponse response )
182 checkLocatorIsInstanceOfRepositoryLocator( locator );
183 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
185 RepositoryGroupConfiguration repoGroupConfig =
186 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
187 List<String> repositories = new ArrayList<String>();
189 boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
190 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
192 if ( repoGroupConfig != null )
194 if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
196 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
197 "Write method not allowed for repository groups." );
199 repositories.addAll( repoGroupConfig.getRepositories() );
201 // handle browse requests for virtual repos
202 if ( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ).endsWith( "/" ) )
204 return getResource( request, repositories, archivaLocator );
209 repositories.add( archivaLocator.getRepositoryId() );
212 //MRM-419 - Windows Webdav support. Should not 404 if there is no content.
213 if (StringUtils.isEmpty(archivaLocator.getRepositoryId()))
215 throw new DavException(HttpServletResponse.SC_NO_CONTENT);
218 List<DavResource> availableResources = new ArrayList<DavResource>();
219 List<String> resourcesInAbsolutePath = new ArrayList<String>();
220 DavException e = null;
222 for ( String repositoryId : repositories )
224 ManagedRepositoryContent managedRepository = null;
228 managedRepository = getManagedRepository( repositoryId );
230 catch ( DavException de )
232 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
233 repositoryId + ">" );
236 DavResource resource = null;
238 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
240 if ( managedRepository != null )
244 if( isAuthorized( request, repositoryId ) )
246 LogicalResource logicalResource =
247 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
251 resource = doGet( managedRepository, request, archivaLocator, logicalResource );
256 resource = doPut( managedRepository, request, archivaLocator, logicalResource );
260 catch ( DavException de )
266 if( resource == null )
268 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
272 availableResources.add( resource );
274 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
275 resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
280 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Repository does not exist" );
285 if ( availableResources.isEmpty() )
290 String requestedResource = request.getRequestURI();
292 // MRM-872 : merge all available metadata
293 // merge metadata only when requested via the repo group
294 if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) ) &&
295 repoGroupConfig != null )
297 // this should only be at the project level not version level!
298 if( isProjectReference( requestedResource ) )
300 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
301 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
303 ArchivaDavResource res = ( ArchivaDavResource ) availableResources.get( 0 );
304 String filePath = StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
305 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
307 // for MRM-872 handle checksums of the merged metadata files
308 if( repositoryRequest.isSupportFile( requestedResource ) )
310 File metadataChecksum = new File( filePath + "."
311 + StringUtils.substringAfterLast( requestedResource, "." ) );
312 if( metadataChecksum.exists() )
314 LogicalResource logicalResource =
315 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
317 ArchivaDavResource metadataChecksumResource =
318 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
319 request.getRemoteAddr(), request.getDavSession(), archivaLocator, this,
320 mimeTypes, auditListeners, consumers );
321 availableResources.add( 0, metadataChecksumResource );
325 { // merge the metadata of all repos under group
326 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
327 for ( String resourceAbsPath : resourcesInAbsolutePath )
331 File metadataFile = new File( resourceAbsPath );
332 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
333 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
335 catch ( RepositoryMetadataException r )
337 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
338 "Error occurred while reading metadata file." );
344 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
346 LogicalResource logicalResource =
347 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
349 ArchivaDavResource metadataResource =
350 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
351 request.getRemoteAddr(), request.getDavSession(), archivaLocator, this,
352 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 ArchivaDavResource resource =
424 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
425 managedRepository.getRepository(), request.getRemoteAddr(),
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 );
461 if ( !resourceFile.exists() )
468 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
469 managedRepository.getRepository(), request.getRemoteAddr(),
470 request.getDavSession(), locator, this, mimeTypes, auditListeners,
477 private DavResource doPut( ManagedRepositoryContent managedRepository, DavServletRequest request,
478 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
482 * Create parent directories that don't exist when writing a file This actually makes this implementation not
483 * compliant to the WebDAV RFC - but we have enough knowledge about how the collection is being used to do this
484 * reasonably and some versions of Maven's WebDAV don't correctly create the collections themselves.
487 File rootDirectory = new File( managedRepository.getRepoRoot() );
488 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
489 if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
492 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
493 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR );
496 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
498 return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
499 managedRepository.getRepository(), request.getRemoteAddr(),
500 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
503 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
504 LogicalResource resource )
507 if ( repositoryRequest.isSupportFile( resource.getPath() ) )
509 File proxiedFile = connectors.fetchFromProxies( managedRepository, resource.getPath() );
511 return ( proxiedFile != null );
514 // Is it a Metadata resource?
515 if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
517 return fetchMetadataFromProxies( managedRepository, request, resource );
520 // Not any of the above? Then it's gotta be an artifact reference.
523 // Get the artifact reference in a layout neutral way.
524 ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
526 if ( artifact != null )
528 applyServerSideRelocation( managedRepository, artifact );
530 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
532 resource.setPath( managedRepository.toPath( artifact ) );
534 return ( proxiedFile != null );
537 catch ( LayoutException e )
541 catch ( ProxyDownloadException e )
543 log.error( e.getMessage(), e );
544 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
549 private boolean fetchMetadataFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
550 LogicalResource resource )
553 ProjectReference project;
554 VersionedReference versioned;
559 versioned = metadataTools.toVersionedReference( resource.getPath() );
560 if ( versioned != null )
562 connectors.fetchFromProxies( managedRepository, versioned );
566 catch ( RepositoryMetadataException e )
573 project = metadataTools.toProjectReference( resource.getPath() );
574 if ( project != null )
576 connectors.fetchFromProxies( managedRepository, project );
580 catch ( RepositoryMetadataException e )
589 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
590 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
593 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
594 * metadatas and serving the expected artifact.
596 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
597 throws ProxyDownloadException
599 if ( "pom".equals( artifact.getType() ) )
604 // Build the artifact POM reference
605 ArtifactReference pomReference = new ArtifactReference();
606 pomReference.setGroupId( artifact.getGroupId() );
607 pomReference.setArtifactId( artifact.getArtifactId() );
608 pomReference.setVersion( artifact.getVersion() );
609 pomReference.setType( "pom" );
611 // Get the artifact POM from proxied repositories if needed
612 connectors.fetchFromProxies( managedRepository, pomReference );
614 // Open and read the POM from the managed repo
615 File pom = managedRepository.toFile( pomReference );
624 Model model = new MavenXpp3Reader().read( new FileReader( pom ) );
625 DistributionManagement dist = model.getDistributionManagement();
628 Relocation relocation = dist.getRelocation();
629 if ( relocation != null )
631 // artifact is relocated : update the repositoryPath
632 if ( relocation.getGroupId() != null )
634 artifact.setGroupId( relocation.getGroupId() );
636 if ( relocation.getArtifactId() != null )
638 artifact.setArtifactId( relocation.getArtifactId() );
640 if ( relocation.getVersion() != null )
642 artifact.setVersion( relocation.getVersion() );
647 catch ( FileNotFoundException e )
649 // Artifact has no POM in repo : ignore
651 catch ( IOException e )
653 // Unable to read POM : ignore.
655 catch ( XmlPullParserException e )
657 // Invalid POM : ignore
662 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
664 String activePrincipal = ArchivaXworkUser.getActivePrincipal( ActionContext.getContext().getSession() );
665 AuditEvent event = new AuditEvent( repositoryId, activePrincipal, resource, action );
666 event.setRemoteIP( remoteIP );
668 for ( AuditListener listener : auditListeners )
670 listener.auditEvent( event );
674 public void addAuditListener( AuditListener listener )
676 this.auditListeners.add( listener );
679 public void clearAuditListeners()
681 this.auditListeners.clear();
684 public void removeAuditListener( AuditListener listener )
686 this.auditListeners.remove( listener );
689 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
691 // [MRM-503] - Metadata file need Pragma:no-cache response
693 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
695 response.addHeader( "Pragma", "no-cache" );
696 response.addHeader( "Cache-Control", "no-cache" );
699 //We need to specify this so connecting wagons can work correctly
700 response.addDateHeader("last-modified", resource.getModificationTime());
702 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
705 private ManagedRepositoryContent getManagedRepository( String respositoryId )
708 if ( respositoryId != null )
712 return repositoryFactory.getManagedRepositoryContent( respositoryId );
714 catch ( RepositoryNotFoundException e )
716 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
718 catch ( RepositoryException e )
720 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
726 private void checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
729 if ( !( locator instanceof RepositoryLocator ) )
731 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
732 "Locator does not implement RepositoryLocator" );
736 class LogicalResource
740 public LogicalResource( String path )
745 public String getPath()
750 public void setPath( String path )
756 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
761 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
762 SecuritySession securitySession = httpAuth.getSecuritySession();
764 return servletAuth.isAuthenticated( request, result ) &&
765 servletAuth.isAuthorized( request, securitySession, repositoryId,
766 WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
768 catch ( AuthenticationException e )
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 // put the current session in the session map which will be passed to ArchivaXworkUser
804 Map<String, Object> sessionMap = new HashMap<String, Object>();
805 if( request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) != null )
807 sessionMap.put( SecuritySystemConstants.SECURITY_SESSION_KEY,
808 request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) );
811 String activePrincipal = ArchivaXworkUser.getActivePrincipal( sessionMap );
812 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
816 for( String repository : repositories )
818 // for prompted authentication
819 if( httpAuth.getSecuritySession() != null )
823 if( isAuthorized( request, repository ) )
825 getResource( locator, mergedRepositoryContents, logicalResource, repository );
828 catch ( DavException e )
835 // for the current user logged in
838 if( servletAuth.isAuthorizedToAccessVirtualRepository( activePrincipal, repository ) )
840 getResource( locator, mergedRepositoryContents, logicalResource, repository );
843 catch ( UnauthorizedException e )
852 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
855 ArchivaVirtualDavResource resource =
856 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this );
858 // compatibility with MRM-440 to ensure browsing the repository group works ok
859 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
861 throw new BrowserRedirectException( resource.getHref() );
867 private void getResource( ArchivaDavResourceLocator locator, List<File> mergedRepositoryContents,
868 LogicalResource logicalResource, String repository )
871 ManagedRepositoryContent managedRepository = null;
875 managedRepository = getManagedRepository( repository );
877 catch ( DavException de )
879 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
883 if ( !locator.getResourcePath().startsWith( ArchivaVirtualDavResource.HIDDEN_PATH_PREFIX ) )
885 if( managedRepository != null )
887 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
888 if( resourceFile.exists() )
890 mergedRepositoryContents.add( resourceFile );
897 * Check if the current user is authorized to access any of the repos
900 * @param repositories
901 * @param activePrincipal
904 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
906 boolean allow = false;
909 // if securitySession != null, it means that the user was prompted for authentication
910 if( httpAuth.getSecuritySession() != null )
912 for( String repository : repositories )
916 if( isAuthorized( request, repository ) )
922 catch( DavException e )
930 for( String repository : repositories )
934 if( servletAuth.isAuthorizedToAccessVirtualRepository( activePrincipal, repository ) )
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 VersionedReference versionRef = metadataTools.toVersionedReference( requestedResource );
990 catch ( RepositoryMetadataException re )