1 package org.apache.archiva.rest.services;
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
21 import org.apache.archiva.admin.model.RepositoryAdminException;
22 import org.apache.archiva.admin.model.beans.ManagedRepository;
23 import org.apache.archiva.common.utils.VersionComparator;
24 import org.apache.archiva.common.utils.VersionUtil;
25 import org.apache.archiva.dependency.tree.maven2.DependencyTreeBuilder;
26 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
27 import org.apache.archiva.maven2.model.Artifact;
28 import org.apache.archiva.maven2.model.TreeEntry;
29 import org.apache.archiva.metadata.generic.GenericMetadataFacet;
30 import org.apache.archiva.metadata.model.ArtifactMetadata;
31 import org.apache.archiva.metadata.model.MetadataFacet;
32 import org.apache.archiva.metadata.model.ProjectVersionMetadata;
33 import org.apache.archiva.metadata.model.ProjectVersionReference;
34 import org.apache.archiva.metadata.repository.MetadataRepository;
35 import org.apache.archiva.metadata.repository.MetadataRepositoryException;
36 import org.apache.archiva.metadata.repository.MetadataResolutionException;
37 import org.apache.archiva.metadata.repository.MetadataResolver;
38 import org.apache.archiva.metadata.repository.RepositorySession;
39 import org.apache.archiva.metadata.repository.storage.maven2.ArtifactMetadataVersionComparator;
40 import org.apache.archiva.metadata.repository.storage.maven2.MavenProjectFacet;
41 import org.apache.archiva.model.ArchivaArtifact;
42 import org.apache.archiva.model.ArchivaRepositoryMetadata;
43 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
44 import org.apache.archiva.redback.components.cache.Cache;
45 import org.apache.archiva.repository.ManagedRepositoryContent;
46 import org.apache.archiva.repository.RepositoryContentFactory;
47 import org.apache.archiva.repository.RepositoryException;
48 import org.apache.archiva.repository.RepositoryNotFoundException;
49 import org.apache.archiva.repository.metadata.MetadataTools;
50 import org.apache.archiva.rest.api.model.ArtifactContent;
51 import org.apache.archiva.rest.api.model.ArtifactContentEntry;
52 import org.apache.archiva.rest.api.model.BrowseResult;
53 import org.apache.archiva.rest.api.model.BrowseResultEntry;
54 import org.apache.archiva.rest.api.model.Entry;
55 import org.apache.archiva.rest.api.model.MetadataAddRequest;
56 import org.apache.archiva.rest.api.model.VersionsList;
57 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
58 import org.apache.archiva.rest.api.services.BrowseService;
59 import org.apache.archiva.rest.services.utils.ArtifactContentEntryComparator;
60 import org.apache.archiva.security.ArchivaSecurityException;
61 import org.apache.archiva.xml.XMLException;
62 import org.apache.commons.collections.CollectionUtils;
63 import org.apache.commons.io.FileUtils;
64 import org.apache.commons.io.IOUtils;
65 import org.apache.commons.lang.StringUtils;
66 import org.springframework.stereotype.Service;
68 import javax.inject.Inject;
69 import javax.inject.Named;
70 import javax.ws.rs.core.Response;
72 import java.io.IOException;
73 import java.io.InputStream;
74 import java.util.ArrayList;
75 import java.util.Collection;
76 import java.util.Collections;
77 import java.util.Enumeration;
78 import java.util.HashMap;
79 import java.util.LinkedHashSet;
80 import java.util.List;
83 import java.util.jar.JarEntry;
84 import java.util.jar.JarFile;
85 import java.util.zip.ZipEntry;
88 * @author Olivier Lamy
91 @Service( "browseService#rest" )
92 public class DefaultBrowseService
93 extends AbstractRestService
94 implements BrowseService
98 private DependencyTreeBuilder dependencyTreeBuilder;
101 private RepositoryContentFactory repositoryContentFactory;
104 @Named( value = "repositoryProxyConnectors#default" )
105 private RepositoryProxyConnectors connectors;
108 @Named( value = "browse#versionMetadata" )
109 private Cache<String, ProjectVersionMetadata> versionMetadataCache;
112 public BrowseResult getRootGroups( String repositoryId )
113 throws ArchivaRestServiceException
115 List<String> selectedRepos = getSelectedRepos( repositoryId );
117 Set<String> namespaces = new LinkedHashSet<String>();
119 // TODO: this logic should be optional, particularly remembering we want to keep this code simple
120 // it is located here to avoid the content repository implementation needing to do too much for what
121 // is essentially presentation code
122 Set<String> namespacesToCollapse = new LinkedHashSet<String>();
123 RepositorySession repositorySession = repositorySessionFactory.createSession();
126 MetadataResolver metadataResolver = repositorySession.getResolver();
128 for ( String repoId : selectedRepos )
130 namespacesToCollapse.addAll( metadataResolver.resolveRootNamespaces( repositorySession, repoId ) );
132 for ( String n : namespacesToCollapse )
134 // TODO: check performance of this
135 namespaces.add( collapseNamespaces( repositorySession, metadataResolver, selectedRepos, n ) );
138 catch ( MetadataResolutionException e )
140 throw new ArchivaRestServiceException( e.getMessage(),
141 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
145 repositorySession.close();
148 List<BrowseResultEntry> browseGroupResultEntries = new ArrayList<>( namespaces.size() );
149 for ( String namespace : namespaces )
151 browseGroupResultEntries.add( new BrowseResultEntry( namespace, false ) );
154 Collections.sort( browseGroupResultEntries );
155 return new BrowseResult( browseGroupResultEntries );
159 public BrowseResult browseGroupId( String groupId, String repositoryId )
160 throws ArchivaRestServiceException
162 List<String> selectedRepos = getSelectedRepos( repositoryId );
164 Set<String> projects = new LinkedHashSet<>();
166 RepositorySession repositorySession = repositorySessionFactory.createSession();
167 Set<String> namespaces;
170 MetadataResolver metadataResolver = repositorySession.getResolver();
172 Set<String> namespacesToCollapse = new LinkedHashSet<>();
173 for ( String repoId : selectedRepos )
175 namespacesToCollapse.addAll( metadataResolver.resolveNamespaces( repositorySession, repoId, groupId ) );
177 projects.addAll( metadataResolver.resolveProjects( repositorySession, repoId, groupId ) );
180 // TODO: this logic should be optional, particularly remembering we want to keep this code simple
181 // it is located here to avoid the content repository implementation needing to do too much for what
182 // is essentially presentation code
183 namespaces = new LinkedHashSet<>();
184 for ( String n : namespacesToCollapse )
186 // TODO: check performance of this
188 collapseNamespaces( repositorySession, metadataResolver, selectedRepos, groupId + "." + n ) );
191 catch ( MetadataResolutionException e )
193 throw new ArchivaRestServiceException( e.getMessage(),
194 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
198 repositorySession.close();
200 List<BrowseResultEntry> browseGroupResultEntries = new ArrayList<>( namespaces.size() + projects.size() );
201 for ( String namespace : namespaces )
203 browseGroupResultEntries.add( new BrowseResultEntry( namespace, false ).groupId( namespace ) );
205 for ( String project : projects )
207 browseGroupResultEntries.add(
208 new BrowseResultEntry( groupId + '.' + project, true ).groupId( groupId ).artifactId( project ) );
210 Collections.sort( browseGroupResultEntries );
211 return new BrowseResult( browseGroupResultEntries );
216 public VersionsList getVersionsList( String groupId, String artifactId, String repositoryId )
217 throws ArchivaRestServiceException
219 List<String> selectedRepos = getSelectedRepos( repositoryId );
223 Collection<String> versions = getVersions( selectedRepos, groupId, artifactId );
224 return new VersionsList( new ArrayList<>( versions ) );
226 catch ( MetadataResolutionException e )
228 throw new ArchivaRestServiceException( e.getMessage(),
229 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
234 private Collection<String> getVersions( List<String> selectedRepos, String groupId, String artifactId )
235 throws MetadataResolutionException
238 RepositorySession repositorySession = repositorySessionFactory.createSession();
241 MetadataResolver metadataResolver = repositorySession.getResolver();
243 Set<String> versions = new LinkedHashSet<String>();
245 for ( String repoId : selectedRepos )
247 Collection<String> projectVersions =
248 metadataResolver.resolveProjectVersions( repositorySession, repoId, groupId, artifactId );
249 versions.addAll( projectVersions );
252 List<String> sortedVersions = new ArrayList<>( versions );
254 Collections.sort( sortedVersions, VersionComparator.getInstance() );
256 return sortedVersions;
260 repositorySession.close();
265 public ProjectVersionMetadata getProjectMetadata( String groupId, String artifactId, String version,
266 String repositoryId )
267 throws ArchivaRestServiceException
269 List<String> selectedRepos = getSelectedRepos( repositoryId );
271 RepositorySession repositorySession = null;
274 repositorySession = repositorySessionFactory.createSession();
276 MetadataResolver metadataResolver = repositorySession.getResolver();
278 ProjectVersionMetadata versionMetadata = null;
279 for ( String repoId : selectedRepos )
281 if ( versionMetadata == null || versionMetadata.isIncomplete() )
286 metadataResolver.resolveProjectVersion( repositorySession, repoId, groupId, artifactId,
289 catch ( MetadataResolutionException e )
291 log.warn( "Skipping invalid metadata while compiling shared model for {}:{} in repo {}: {}",
292 groupId, artifactId, repoId, e.getMessage() );
297 return versionMetadata;
301 if ( repositorySession != null )
303 repositorySession.close();
310 public ProjectVersionMetadata getProjectVersionMetadata( String groupId, String artifactId, String repositoryId )
311 throws ArchivaRestServiceException
314 List<String> selectedRepos = getSelectedRepos( repositoryId );
316 RepositorySession repositorySession = null;
320 Collection<String> projectVersions = getVersions( selectedRepos, groupId, artifactId );
322 repositorySession = repositorySessionFactory.createSession();
324 MetadataResolver metadataResolver = repositorySession.getResolver();
326 ProjectVersionMetadata sharedModel = new ProjectVersionMetadata();
328 MavenProjectFacet mavenFacet = new MavenProjectFacet();
329 mavenFacet.setGroupId( groupId );
330 mavenFacet.setArtifactId( artifactId );
331 sharedModel.addFacet( mavenFacet );
333 boolean isFirstVersion = true;
335 for ( String version : projectVersions )
337 ProjectVersionMetadata versionMetadata = null;
338 for ( String repoId : selectedRepos )
340 if ( versionMetadata == null || versionMetadata.isIncomplete() )
344 ProjectVersionMetadata projectVersionMetadataResolved = null;
345 boolean useCache = !StringUtils.endsWith( version, VersionUtil.SNAPSHOT );
346 String cacheKey = null;
347 boolean cacheToUpdate = false;
348 // FIXME a bit maven centric!!!
349 // not a snapshot so get it from cache
352 cacheKey = repoId + groupId + artifactId + version;
353 projectVersionMetadataResolved = versionMetadataCache.get( cacheKey );
355 if ( useCache && projectVersionMetadataResolved != null )
357 versionMetadata = projectVersionMetadataResolved;
361 projectVersionMetadataResolved =
362 metadataResolver.resolveProjectVersion( repositorySession, repoId, groupId,
363 artifactId, version );
364 versionMetadata = projectVersionMetadataResolved;
365 cacheToUpdate = true;
368 if ( useCache && cacheToUpdate )
370 versionMetadataCache.put( cacheKey, projectVersionMetadataResolved );
374 catch ( MetadataResolutionException e )
376 log.error( "Skipping invalid metadata while compiling shared model for " + groupId + ":"
377 + artifactId + " in repo " + repoId + ": " + e.getMessage() );
382 if ( versionMetadata == null )
387 if ( isFirstVersion )
389 sharedModel = versionMetadata;
390 sharedModel.setId( null );
394 MavenProjectFacet versionMetadataMavenFacet =
395 (MavenProjectFacet) versionMetadata.getFacet( MavenProjectFacet.FACET_ID );
396 if ( versionMetadataMavenFacet != null )
398 if ( mavenFacet.getPackaging() != null //
399 && !StringUtils.equalsIgnoreCase( mavenFacet.getPackaging(),
400 versionMetadataMavenFacet.getPackaging() ) )
402 mavenFacet.setPackaging( null );
406 if ( StringUtils.isEmpty( sharedModel.getName() ) //
407 && !StringUtils.isEmpty( versionMetadata.getName() ) )
409 sharedModel.setName( versionMetadata.getName() );
412 if ( sharedModel.getDescription() != null //
413 && !StringUtils.equalsIgnoreCase( sharedModel.getDescription(),
414 versionMetadata.getDescription() ) )
416 sharedModel.setDescription( StringUtils.isNotEmpty( versionMetadata.getDescription() )
417 ? versionMetadata.getDescription()
421 if ( sharedModel.getIssueManagement() != null //
422 && versionMetadata.getIssueManagement() != null //
423 && !StringUtils.equalsIgnoreCase( sharedModel.getIssueManagement().getUrl(),
424 versionMetadata.getIssueManagement().getUrl() ) )
426 sharedModel.setIssueManagement( versionMetadata.getIssueManagement() );
429 if ( sharedModel.getCiManagement() != null //
430 && versionMetadata.getCiManagement() != null //
431 && !StringUtils.equalsIgnoreCase( sharedModel.getCiManagement().getUrl(),
432 versionMetadata.getCiManagement().getUrl() ) )
434 sharedModel.setCiManagement( versionMetadata.getCiManagement() );
437 if ( sharedModel.getOrganization() != null //
438 && versionMetadata.getOrganization() != null //
439 && !StringUtils.equalsIgnoreCase( sharedModel.getOrganization().getName(),
440 versionMetadata.getOrganization().getName() ) )
442 sharedModel.setOrganization( versionMetadata.getOrganization() );
445 if ( sharedModel.getUrl() != null //
446 && !StringUtils.equalsIgnoreCase( sharedModel.getUrl(), versionMetadata.getUrl() ) )
448 sharedModel.setUrl( versionMetadata.getUrl() );
452 isFirstVersion = false;
456 catch ( MetadataResolutionException e )
458 throw new ArchivaRestServiceException( e.getMessage(),
459 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
463 if ( repositorySession != null )
465 repositorySession.close();
471 public List<TreeEntry> getTreeEntries( String groupId, String artifactId, String version, String repositoryId )
472 throws ArchivaRestServiceException
474 List<String> selectedRepos = getSelectedRepos( repositoryId );
478 return dependencyTreeBuilder.buildDependencyTree( selectedRepos, groupId, artifactId, version );
480 catch ( Exception e )
482 log.error( e.getMessage(), e );
485 return Collections.emptyList();
489 public List<ManagedRepository> getUserRepositories()
490 throws ArchivaRestServiceException
494 return userRepositories.getAccessibleRepositories( getPrincipal() );
496 catch ( ArchivaSecurityException e )
498 throw new ArchivaRestServiceException( "repositories.read.observable.error",
499 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
504 public List<Artifact> getDependees( String groupId, String artifactId, String version, String repositoryId )
505 throws ArchivaRestServiceException
507 List<ProjectVersionReference> references = new ArrayList<>();
508 // TODO: what if we get duplicates across repositories?
509 RepositorySession repositorySession = repositorySessionFactory.createSession();
512 MetadataResolver metadataResolver = repositorySession.getResolver();
513 for ( String repoId : getObservableRepos() )
515 // TODO: what about if we want to see this irrespective of version?
517 metadataResolver.resolveProjectReferences( repositorySession, repoId, groupId, artifactId,
521 catch ( MetadataResolutionException e )
523 throw new ArchivaRestServiceException( e.getMessage(),
524 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
528 repositorySession.close();
531 List<Artifact> artifacts = new ArrayList<>( references.size() );
533 for ( ProjectVersionReference projectVersionReference : references )
535 artifacts.add( new Artifact( projectVersionReference.getNamespace(), projectVersionReference.getProjectId(),
536 projectVersionReference.getProjectVersion() ) );
542 public List<Entry> getMetadatas( String groupId, String artifactId, String version, String repositoryId )
543 throws ArchivaRestServiceException
545 ProjectVersionMetadata projectVersionMetadata =
546 getProjectMetadata( groupId, artifactId, version, repositoryId );
547 if ( projectVersionMetadata == null )
549 return Collections.emptyList();
551 MetadataFacet metadataFacet = projectVersionMetadata.getFacet( GenericMetadataFacet.FACET_ID );
553 if ( metadataFacet == null )
555 return Collections.emptyList();
557 Map<String, String> map = metadataFacet.toProperties();
558 List<Entry> entries = new ArrayList<>( map.size() );
560 for ( Map.Entry<String, String> entry : map.entrySet() )
562 entries.add( new Entry( entry.getKey(), entry.getValue() ) );
569 public Boolean addMetadata( String groupId, String artifactId, String version, String key, String value,
570 String repositoryId )
571 throws ArchivaRestServiceException
573 ProjectVersionMetadata projectVersionMetadata =
574 getProjectMetadata( groupId, artifactId, version, repositoryId );
576 if ( projectVersionMetadata == null )
578 return Boolean.FALSE;
581 Map<String, String> properties = new HashMap<>();
583 MetadataFacet metadataFacet = projectVersionMetadata.getFacet( GenericMetadataFacet.FACET_ID );
585 if ( metadataFacet != null && metadataFacet.toProperties() != null )
587 properties.putAll( metadataFacet.toProperties() );
591 metadataFacet = new GenericMetadataFacet();
594 properties.put( key, value );
596 metadataFacet.fromProperties( properties );
598 projectVersionMetadata.addFacet( metadataFacet );
600 RepositorySession repositorySession = repositorySessionFactory.createSession();
604 MetadataRepository metadataRepository = repositorySession.getRepository();
606 metadataRepository.updateProjectVersion( repositoryId, groupId, artifactId, projectVersionMetadata );
608 repositorySession.save();
610 catch ( MetadataRepositoryException e )
612 log.error( e.getMessage(), e );
613 throw new ArchivaRestServiceException( e.getMessage(),
614 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
618 repositorySession.close();
624 public Boolean deleteMetadata( String groupId, String artifactId, String version, String key, String repositoryId )
625 throws ArchivaRestServiceException
627 ProjectVersionMetadata projectVersionMetadata =
628 getProjectMetadata( groupId, artifactId, version, repositoryId );
630 if ( projectVersionMetadata == null )
632 return Boolean.FALSE;
635 GenericMetadataFacet metadataFacet =
636 (GenericMetadataFacet) projectVersionMetadata.getFacet( GenericMetadataFacet.FACET_ID );
638 if ( metadataFacet != null && metadataFacet.toProperties() != null )
640 Map<String, String> properties = metadataFacet.toProperties();
641 properties.remove( key );
642 metadataFacet.setAdditionalProperties( properties );
649 RepositorySession repositorySession = repositorySessionFactory.createSession();
653 MetadataRepository metadataRepository = repositorySession.getRepository();
655 metadataRepository.updateProjectVersion( repositoryId, groupId, artifactId, projectVersionMetadata );
657 repositorySession.save();
659 catch ( MetadataRepositoryException e )
661 log.error( e.getMessage(), e );
662 throw new ArchivaRestServiceException( e.getMessage(),
663 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
667 repositorySession.close();
673 public List<ArtifactContentEntry> getArtifactContentEntries( String groupId, String artifactId, String version,
674 String classifier, String type, String path,
675 String repositoryId )
676 throws ArchivaRestServiceException
678 List<String> selectedRepos = getSelectedRepos( repositoryId );
681 for ( String repoId : selectedRepos )
684 ManagedRepositoryContent managedRepositoryContent =
685 repositoryContentFactory.getManagedRepositoryContent( repoId );
686 ArchivaArtifact archivaArtifact = new ArchivaArtifact( groupId, artifactId, version, classifier,
687 StringUtils.isEmpty( type ) ? "jar" : type,
689 File file = managedRepositoryContent.toFile( archivaArtifact );
692 return readFileEntries( file, path, repoId );
696 catch ( IOException e )
698 log.error( e.getMessage(), e );
699 throw new ArchivaRestServiceException( e.getMessage(),
700 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
702 catch ( RepositoryNotFoundException e )
704 log.error( e.getMessage(), e );
705 throw new ArchivaRestServiceException( e.getMessage(),
706 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
708 catch ( RepositoryException e )
710 log.error( e.getMessage(), e );
711 throw new ArchivaRestServiceException( e.getMessage(),
712 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
714 return Collections.emptyList();
718 public List<Artifact> getArtifactDownloadInfos( String groupId, String artifactId, String version,
719 String repositoryId )
720 throws ArchivaRestServiceException
722 List<String> selectedRepos = getSelectedRepos( repositoryId );
724 List<Artifact> artifactDownloadInfos = new ArrayList<>();
726 try (RepositorySession session = repositorySessionFactory.createSession())
728 MetadataResolver metadataResolver = session.getResolver();
729 for ( String repoId : selectedRepos )
731 List<ArtifactMetadata> artifacts = new ArrayList<>(
732 metadataResolver.resolveArtifacts( session, repoId, groupId, artifactId, version ) );
733 Collections.sort( artifacts, ArtifactMetadataVersionComparator.INSTANCE );
734 if ( artifacts != null && !artifacts.isEmpty() )
736 return buildArtifacts( artifacts, repoId );
740 catch ( MetadataResolutionException e )
742 log.error( e.getMessage(), e );
743 throw new ArchivaRestServiceException( e.getMessage(),
744 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
747 return artifactDownloadInfos;
751 public ArtifactContent getArtifactContentText( String groupId, String artifactId, String version, String classifier,
752 String type, String path, String repositoryId )
753 throws ArchivaRestServiceException
755 List<String> selectedRepos = getSelectedRepos( repositoryId );
758 for ( String repoId : selectedRepos )
761 ManagedRepositoryContent managedRepositoryContent =
762 repositoryContentFactory.getManagedRepositoryContent( repoId );
763 ArchivaArtifact archivaArtifact = new ArchivaArtifact( groupId, artifactId, version, classifier,
764 StringUtils.isEmpty( type ) ? "jar" : type,
766 File file = managedRepositoryContent.toFile( archivaArtifact );
767 if ( !file.exists() )
769 log.debug( "file: {} not exists for repository: {} try next repository", file, repoId );
772 if ( StringUtils.isNotBlank( path ) )
774 // zip entry of the path -> path must a real file entry of the archive
775 JarFile jarFile = new JarFile( file );
776 ZipEntry zipEntry = jarFile.getEntry( path );
777 try (InputStream inputStream = jarFile.getInputStream( zipEntry ))
779 return new ArtifactContent( IOUtils.toString( inputStream ), repoId );
783 closeQuietly( jarFile );
786 return new ArtifactContent( FileUtils.readFileToString( file ), repoId );
789 catch ( IOException e )
791 log.error( e.getMessage(), e );
792 throw new ArchivaRestServiceException( e.getMessage(),
793 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
795 catch ( RepositoryNotFoundException e )
797 log.error( e.getMessage(), e );
798 throw new ArchivaRestServiceException( e.getMessage(),
799 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
801 catch ( RepositoryException e )
803 log.error( e.getMessage(), e );
804 throw new ArchivaRestServiceException( e.getMessage(),
805 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
807 log.debug( "artifact: {}:{}:{}:{}:{} not found", groupId, artifactId, version, classifier, type );
809 return new ArtifactContent();
813 public Boolean artifactAvailable( String groupId, String artifactId, String version, String classifier,
814 String repositoryId )
815 throws ArchivaRestServiceException
817 List<String> selectedRepos = getSelectedRepos( repositoryId );
819 boolean snapshot = VersionUtil.isSnapshot( version );
823 for ( String repoId : selectedRepos )
826 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repoId );
828 if ( ( snapshot && !managedRepository.isSnapshots() ) || ( !snapshot
829 && managedRepository.isSnapshots() ) )
833 ManagedRepositoryContent managedRepositoryContent =
834 repositoryContentFactory.getManagedRepositoryContent( repoId );
835 // FIXME default to jar which can be wrong for war zip etc....
836 ArchivaArtifact archivaArtifact = new ArchivaArtifact( groupId, artifactId, version,
837 StringUtils.isEmpty( classifier )
839 : classifier, "jar", repoId
841 File file = managedRepositoryContent.toFile( archivaArtifact );
843 if ( file != null && file.exists() )
848 // in case of SNAPSHOT we can have timestamped version locally !
849 if ( StringUtils.endsWith( version, VersionUtil.SNAPSHOT ) )
851 File metadataFile = new File( file.getParent(), MetadataTools.MAVEN_METADATA );
852 if ( metadataFile.exists() )
856 ArchivaRepositoryMetadata archivaRepositoryMetadata =
857 MavenMetadataReader.read( metadataFile );
858 int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber();
859 String timeStamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp();
860 // rebuild file name with timestamped version and build number
861 String timeStampFileName = new StringBuilder( artifactId ).append( '-' ) //
862 .append( StringUtils.remove( version, "-" + VersionUtil.SNAPSHOT ) ) //
863 .append( '-' ).append( timeStamp ) //
864 .append( '-' ).append( Integer.toString( buildNumber ) ) //
865 .append( ( StringUtils.isEmpty( classifier ) ? "" : "-" + classifier ) ) //
866 .append( ".jar" ).toString();
868 File timeStampFile = new File( file.getParent(), timeStampFileName );
869 log.debug( "try to find timestamped snapshot version file: {}", timeStampFile.getPath() );
870 if ( timeStampFile.exists() )
875 catch ( XMLException e )
877 log.warn( "skip fail to find timestamped snapshot file: {}", e.getMessage() );
882 String path = managedRepositoryContent.toPath( archivaArtifact );
884 file = connectors.fetchFromProxies( managedRepositoryContent, path );
886 if ( file != null && file.exists() )
889 String pomPath = StringUtils.substringBeforeLast( path, ".jar" ) + ".pom";
890 connectors.fetchFromProxies( managedRepositoryContent, pomPath );
895 catch ( RepositoryAdminException e )
897 log.error( e.getMessage(), e );
898 throw new ArchivaRestServiceException( e.getMessage(),
899 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
901 catch ( RepositoryException e )
903 log.error( e.getMessage(), e );
904 throw new ArchivaRestServiceException( e.getMessage(),
905 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
912 public Boolean artifactAvailable( String groupId, String artifactId, String version, String repositoryId )
913 throws ArchivaRestServiceException
915 return artifactAvailable( groupId, artifactId, version, null, repositoryId );
919 public List<Artifact> getArtifacts( String repositoryId )
920 throws ArchivaRestServiceException
922 RepositorySession repositorySession = repositorySessionFactory.createSession();
925 List<ArtifactMetadata> artifactMetadatas = repositorySession.getRepository().getArtifacts( repositoryId );
926 return buildArtifacts( artifactMetadatas, repositoryId );
928 catch ( MetadataRepositoryException e )
930 throw new ArchivaRestServiceException( e.getMessage(), e );
934 repositorySession.close();
939 public Boolean importMetadata( MetadataAddRequest metadataAddRequest, String repositoryId )
940 throws ArchivaRestServiceException
942 boolean result = true;
943 for ( Map.Entry<String, String> metadata : metadataAddRequest.getMetadatas().entrySet() )
945 result = addMetadata( metadataAddRequest.getGroupId(), metadataAddRequest.getArtifactId(),
946 metadataAddRequest.getVersion(), metadata.getKey(), metadata.getValue(),
956 //---------------------------
958 //---------------------------
960 private void closeQuietly( JarFile jarFile )
962 if ( jarFile != null )
968 catch ( IOException e )
970 log.warn( "ignore error closing jarFile {}", jarFile.getName() );
975 protected List<ArtifactContentEntry> readFileEntries( File file, String filterPath, String repoId )
978 Map<String, ArtifactContentEntry> artifactContentEntryMap = new HashMap<>();
979 int filterDepth = StringUtils.countMatches( filterPath, "/" );
980 /*if ( filterDepth == 0 )
984 JarFile jarFile = new JarFile( file );
987 Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
988 while ( jarEntryEnumeration.hasMoreElements() )
990 JarEntry currentEntry = jarEntryEnumeration.nextElement();
991 String cleanedEntryName = StringUtils.endsWith( currentEntry.getName(), "/" ) ? //
992 StringUtils.substringBeforeLast( currentEntry.getName(), "/" ) : currentEntry.getName();
993 String entryRootPath = getRootPath( cleanedEntryName );
994 int depth = StringUtils.countMatches( cleanedEntryName, "/" );
995 if ( StringUtils.isEmpty( filterPath ) //
996 && !artifactContentEntryMap.containsKey( entryRootPath ) //
997 && depth == filterDepth )
1000 artifactContentEntryMap.put( entryRootPath,
1001 new ArtifactContentEntry( entryRootPath, !currentEntry.isDirectory(),
1007 if ( StringUtils.startsWith( cleanedEntryName, filterPath ) //
1008 && ( depth == filterDepth || ( !currentEntry.isDirectory() && depth == filterDepth ) ) )
1010 artifactContentEntryMap.put( cleanedEntryName, new ArtifactContentEntry( cleanedEntryName,
1011 !currentEntry.isDirectory(),
1017 if ( StringUtils.isNotEmpty( filterPath ) )
1019 Map<String, ArtifactContentEntry> filteredArtifactContentEntryMap = new HashMap<>();
1021 for ( Map.Entry<String, ArtifactContentEntry> entry : artifactContentEntryMap.entrySet() )
1023 filteredArtifactContentEntryMap.put( entry.getKey(), entry.getValue() );
1026 List<ArtifactContentEntry> sorted = getSmallerDepthEntries( filteredArtifactContentEntryMap );
1027 if ( sorted == null )
1029 return Collections.emptyList();
1031 Collections.sort( sorted, ArtifactContentEntryComparator.INSTANCE );
1037 if ( jarFile != null )
1042 List<ArtifactContentEntry> sorted = new ArrayList<>( artifactContentEntryMap.values() );
1043 Collections.sort( sorted, ArtifactContentEntryComparator.INSTANCE );
1047 private List<ArtifactContentEntry> getSmallerDepthEntries( Map<String, ArtifactContentEntry> entries )
1049 int smallestDepth = Integer.MAX_VALUE;
1050 Map<Integer, List<ArtifactContentEntry>> perDepthList = new HashMap<>();
1051 for ( Map.Entry<String, ArtifactContentEntry> entry : entries.entrySet() )
1054 ArtifactContentEntry current = entry.getValue();
1056 if ( current.getDepth() < smallestDepth )
1058 smallestDepth = current.getDepth();
1061 List<ArtifactContentEntry> currentList = perDepthList.get( current.getDepth() );
1063 if ( currentList == null )
1065 currentList = new ArrayList<>();
1066 currentList.add( current );
1067 perDepthList.put( current.getDepth(), currentList );
1071 currentList.add( current );
1076 return perDepthList.get( smallestDepth );
1081 * @return org/apache -> org , org -> org
1083 private String getRootPath( String path )
1085 if ( StringUtils.contains( path, '/' ) )
1087 return StringUtils.substringBefore( path, "/" );
1092 private List<String> getSelectedRepos( String repositoryId )
1093 throws ArchivaRestServiceException
1096 List<String> selectedRepos = getObservableRepos();
1098 if ( CollectionUtils.isEmpty( selectedRepos ) )
1100 return Collections.emptyList();
1103 if ( StringUtils.isNotEmpty( repositoryId ) )
1105 // check user has karma on the repository
1106 if ( !selectedRepos.contains( repositoryId ) )
1108 throw new ArchivaRestServiceException( "browse.root.groups.repositoy.denied",
1109 Response.Status.FORBIDDEN.getStatusCode(), null );
1111 selectedRepos = Collections.singletonList( repositoryId );
1113 return selectedRepos;
1117 private String collapseNamespaces( RepositorySession repositorySession, MetadataResolver metadataResolver,
1118 Collection<String> repoIds, String n )
1119 throws MetadataResolutionException
1121 Set<String> subNamespaces = new LinkedHashSet<String>();
1122 for ( String repoId : repoIds )
1124 subNamespaces.addAll( metadataResolver.resolveNamespaces( repositorySession, repoId, n ) );
1126 if ( subNamespaces.size() != 1 )
1128 log.debug( "{} is not collapsible as it has sub-namespaces: {}", n, subNamespaces );
1133 for ( String repoId : repoIds )
1135 Collection<String> projects = metadataResolver.resolveProjects( repositorySession, repoId, n );
1136 if ( projects != null && !projects.isEmpty() )
1138 log.debug( "{} is not collapsible as it has projects", n );
1142 return collapseNamespaces( repositorySession, metadataResolver, repoIds,
1143 n + "." + subNamespaces.iterator().next() );
1147 public Cache getVersionMetadataCache()
1149 return versionMetadataCache;
1152 public void setVersionMetadataCache( Cache versionMetadataCache )
1154 this.versionMetadataCache = versionMetadataCache;