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<String>();
166 RepositorySession repositorySession = repositorySessionFactory.createSession();
167 Set<String> namespaces;
170 MetadataResolver metadataResolver = repositorySession.getResolver();
172 Set<String> namespacesToCollapse = new LinkedHashSet<String>();
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<String>();
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 );
479 return dependencyTreeBuilder.buildDependencyTree( selectedRepos, groupId, artifactId, version );
482 catch ( Exception e )
484 log.error( e.getMessage(), e );
487 return Collections.emptyList();
491 public List<ManagedRepository> getUserRepositories()
492 throws ArchivaRestServiceException
496 return userRepositories.getAccessibleRepositories( getPrincipal() );
498 catch ( ArchivaSecurityException e )
500 throw new ArchivaRestServiceException( "repositories.read.observable.error",
501 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
506 public List<Artifact> getDependees( String groupId, String artifactId, String version, String repositoryId )
507 throws ArchivaRestServiceException
509 List<ProjectVersionReference> references = new ArrayList<>();
510 // TODO: what if we get duplicates across repositories?
511 RepositorySession repositorySession = repositorySessionFactory.createSession();
514 MetadataResolver metadataResolver = repositorySession.getResolver();
515 for ( String repoId : getObservableRepos() )
517 // TODO: what about if we want to see this irrespective of version?
519 metadataResolver.resolveProjectReferences( repositorySession, repoId, groupId, artifactId,
523 catch ( MetadataResolutionException e )
525 throw new ArchivaRestServiceException( e.getMessage(),
526 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
530 repositorySession.close();
533 List<Artifact> artifacts = new ArrayList<>( references.size() );
535 for ( ProjectVersionReference projectVersionReference : references )
537 artifacts.add( new Artifact( projectVersionReference.getNamespace(), projectVersionReference.getProjectId(),
538 projectVersionReference.getProjectVersion() ) );
544 public List<Entry> getMetadatas( String groupId, String artifactId, String version, String repositoryId )
545 throws ArchivaRestServiceException
547 ProjectVersionMetadata projectVersionMetadata =
548 getProjectMetadata( groupId, artifactId, version, repositoryId );
549 if ( projectVersionMetadata == null )
551 return Collections.emptyList();
553 MetadataFacet metadataFacet = projectVersionMetadata.getFacet( GenericMetadataFacet.FACET_ID );
555 if ( metadataFacet == null )
557 return Collections.emptyList();
559 Map<String, String> map = metadataFacet.toProperties();
560 List<Entry> entries = new ArrayList<>( map.size() );
562 for ( Map.Entry<String, String> entry : map.entrySet() )
564 entries.add( new Entry( entry.getKey(), entry.getValue() ) );
571 public Boolean addMetadata( String groupId, String artifactId, String version, String key, String value,
572 String repositoryId )
573 throws ArchivaRestServiceException
575 ProjectVersionMetadata projectVersionMetadata =
576 getProjectMetadata( groupId, artifactId, version, repositoryId );
578 if ( projectVersionMetadata == null )
580 return Boolean.FALSE;
583 Map<String, String> properties = new HashMap<>();
585 MetadataFacet metadataFacet = projectVersionMetadata.getFacet( GenericMetadataFacet.FACET_ID );
587 if ( metadataFacet != null && metadataFacet.toProperties() != null )
589 properties.putAll( metadataFacet.toProperties() );
593 metadataFacet = new GenericMetadataFacet();
596 properties.put( key, value );
598 metadataFacet.fromProperties( properties );
600 projectVersionMetadata.addFacet( metadataFacet );
602 RepositorySession repositorySession = repositorySessionFactory.createSession();
606 MetadataRepository metadataRepository = repositorySession.getRepository();
608 metadataRepository.updateProjectVersion( repositoryId, groupId, artifactId, projectVersionMetadata );
610 repositorySession.save();
612 catch ( MetadataRepositoryException e )
614 log.error( e.getMessage(), e );
615 throw new ArchivaRestServiceException( e.getMessage(),
616 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
620 repositorySession.close();
626 public Boolean deleteMetadata( String groupId, String artifactId, String version, String key, String repositoryId )
627 throws ArchivaRestServiceException
629 ProjectVersionMetadata projectVersionMetadata =
630 getProjectMetadata( groupId, artifactId, version, repositoryId );
632 if ( projectVersionMetadata == null )
634 return Boolean.FALSE;
637 GenericMetadataFacet metadataFacet =
638 (GenericMetadataFacet) projectVersionMetadata.getFacet( GenericMetadataFacet.FACET_ID );
640 if ( metadataFacet != null && metadataFacet.toProperties() != null )
642 Map<String, String> properties = metadataFacet.toProperties();
643 properties.remove( key );
644 metadataFacet.setAdditionalProperties( properties );
651 RepositorySession repositorySession = repositorySessionFactory.createSession();
655 MetadataRepository metadataRepository = repositorySession.getRepository();
657 metadataRepository.updateProjectVersion( repositoryId, groupId, artifactId, projectVersionMetadata );
659 repositorySession.save();
661 catch ( MetadataRepositoryException e )
663 log.error( e.getMessage(), e );
664 throw new ArchivaRestServiceException( e.getMessage(),
665 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
669 repositorySession.close();
675 public List<ArtifactContentEntry> getArtifactContentEntries( String groupId, String artifactId, String version,
676 String classifier, String type, String path,
677 String repositoryId )
678 throws ArchivaRestServiceException
680 List<String> selectedRepos = getSelectedRepos( repositoryId );
683 for ( String repoId : selectedRepos )
686 ManagedRepositoryContent managedRepositoryContent =
687 repositoryContentFactory.getManagedRepositoryContent( repoId );
688 ArchivaArtifact archivaArtifact = new ArchivaArtifact( groupId, artifactId, version, classifier,
689 StringUtils.isEmpty( type ) ? "jar" : type,
691 File file = managedRepositoryContent.toFile( archivaArtifact );
694 return readFileEntries( file, path, repoId );
698 catch ( IOException e )
700 log.error( e.getMessage(), e );
701 throw new ArchivaRestServiceException( e.getMessage(),
702 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
704 catch ( RepositoryNotFoundException e )
706 log.error( e.getMessage(), e );
707 throw new ArchivaRestServiceException( e.getMessage(),
708 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
710 catch ( RepositoryException e )
712 log.error( e.getMessage(), e );
713 throw new ArchivaRestServiceException( e.getMessage(),
714 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
716 return Collections.emptyList();
720 public List<Artifact> getArtifactDownloadInfos( String groupId, String artifactId, String version,
721 String repositoryId )
722 throws ArchivaRestServiceException
724 List<String> selectedRepos = getSelectedRepos( repositoryId );
726 List<Artifact> artifactDownloadInfos = new ArrayList<>();
728 RepositorySession session = repositorySessionFactory.createSession();
730 MetadataResolver metadataResolver = session.getResolver();
734 for ( String repoId : selectedRepos )
736 List<ArtifactMetadata> artifacts = new ArrayList<>(
737 metadataResolver.resolveArtifacts( session, repoId, groupId, artifactId, version ) );
738 Collections.sort( artifacts, ArtifactMetadataVersionComparator.INSTANCE );
739 if ( artifacts != null && !artifacts.isEmpty() )
741 return buildArtifacts( artifacts, repoId );
745 catch ( MetadataResolutionException e )
747 log.error( e.getMessage(), e );
748 throw new ArchivaRestServiceException( e.getMessage(),
749 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
753 if ( session != null )
755 session.closeQuietly();
759 return artifactDownloadInfos;
763 public ArtifactContent getArtifactContentText( String groupId, String artifactId, String version, String classifier,
764 String type, String path, String repositoryId )
765 throws ArchivaRestServiceException
767 List<String> selectedRepos = getSelectedRepos( repositoryId );
770 for ( String repoId : selectedRepos )
773 ManagedRepositoryContent managedRepositoryContent =
774 repositoryContentFactory.getManagedRepositoryContent( repoId );
775 ArchivaArtifact archivaArtifact = new ArchivaArtifact( groupId, artifactId, version, classifier,
776 StringUtils.isEmpty( type ) ? "jar" : type,
778 File file = managedRepositoryContent.toFile( archivaArtifact );
779 if ( !file.exists() )
781 log.debug( "file: {} not exists for repository: {} try next repository", file, repoId );
784 if ( StringUtils.isNotBlank( path ) )
786 // zip entry of the path -> path must a real file entry of the archive
787 JarFile jarFile = new JarFile( file );
788 ZipEntry zipEntry = jarFile.getEntry( path );
789 InputStream inputStream = jarFile.getInputStream( zipEntry );
792 return new ArtifactContent( IOUtils.toString( inputStream ), repoId );
796 closeQuietly( jarFile );
797 IOUtils.closeQuietly( inputStream );
800 return new ArtifactContent( FileUtils.readFileToString( file ), repoId );
803 catch ( IOException e )
805 log.error( e.getMessage(), e );
806 throw new ArchivaRestServiceException( e.getMessage(),
807 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
809 catch ( RepositoryNotFoundException e )
811 log.error( e.getMessage(), e );
812 throw new ArchivaRestServiceException( e.getMessage(),
813 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
815 catch ( RepositoryException e )
817 log.error( e.getMessage(), e );
818 throw new ArchivaRestServiceException( e.getMessage(),
819 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
821 log.debug( "artifact: {}:{}:{}:{}:{} not found", groupId, artifactId, version, classifier, type );
823 return new ArtifactContent();
827 public Boolean artifactAvailable( String groupId, String artifactId, String version, String classifier,
828 String repositoryId )
829 throws ArchivaRestServiceException
831 List<String> selectedRepos = getSelectedRepos( repositoryId );
833 boolean snapshot = VersionUtil.isSnapshot( version );
837 for ( String repoId : selectedRepos )
840 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repoId );
842 if ( ( snapshot && !managedRepository.isSnapshots() ) || ( !snapshot
843 && managedRepository.isSnapshots() ) )
847 ManagedRepositoryContent managedRepositoryContent =
848 repositoryContentFactory.getManagedRepositoryContent( repoId );
849 // FIXME default to jar which can be wrong for war zip etc....
850 ArchivaArtifact archivaArtifact = new ArchivaArtifact( groupId, artifactId, version,
851 StringUtils.isEmpty( classifier )
853 : classifier, "jar", repoId
855 File file = managedRepositoryContent.toFile( archivaArtifact );
857 if ( file != null && file.exists() )
862 // in case of SNAPSHOT we can have timestamped version locally !
863 if ( StringUtils.endsWith( version, VersionUtil.SNAPSHOT ) )
865 File metadataFile = new File( file.getParent(), MetadataTools.MAVEN_METADATA );
866 if ( metadataFile.exists() )
870 ArchivaRepositoryMetadata archivaRepositoryMetadata =
871 MavenMetadataReader.read( metadataFile );
872 int buildNumber = archivaRepositoryMetadata.getSnapshotVersion().getBuildNumber();
873 String timeStamp = archivaRepositoryMetadata.getSnapshotVersion().getTimestamp();
874 // rebuild file name with timestamped version and build number
875 String timeStampFileName = new StringBuilder( artifactId ).append( '-' ) //
876 .append( StringUtils.remove( version, "-" + VersionUtil.SNAPSHOT ) ) //
877 .append( '-' ).append( timeStamp ) //
878 .append( '-' ).append( Integer.toString( buildNumber ) ) //
879 .append( ( StringUtils.isEmpty( classifier ) ? "" : "-" + classifier ) ) //
880 .append( ".jar" ).toString();
882 File timeStampFile = new File( file.getParent(), timeStampFileName );
883 log.debug( "try to find timestamped snapshot version file: {}", timeStampFile.getPath() );
884 if ( timeStampFile.exists() )
889 catch ( XMLException e )
891 log.warn( "skip fail to find timestamped snapshot file: {}", e.getMessage() );
896 String path = managedRepositoryContent.toPath( archivaArtifact );
898 file = connectors.fetchFromProxies( managedRepositoryContent, path );
900 if ( file != null && file.exists() )
903 String pomPath = StringUtils.substringBeforeLast( path, ".jar" ) + ".pom";
904 connectors.fetchFromProxies( managedRepositoryContent, pomPath );
909 catch ( RepositoryAdminException e )
911 log.error( e.getMessage(), e );
912 throw new ArchivaRestServiceException( e.getMessage(),
913 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
915 catch ( RepositoryException e )
917 log.error( e.getMessage(), e );
918 throw new ArchivaRestServiceException( e.getMessage(),
919 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
926 public Boolean artifactAvailable( String groupId, String artifactId, String version, String repositoryId )
927 throws ArchivaRestServiceException
929 return artifactAvailable( groupId, artifactId, version, null, repositoryId );
933 public List<Artifact> getArtifacts( String repositoryId )
934 throws ArchivaRestServiceException
936 RepositorySession repositorySession = repositorySessionFactory.createSession();
939 List<ArtifactMetadata> artifactMetadatas = repositorySession.getRepository().getArtifacts( repositoryId );
940 return buildArtifacts( artifactMetadatas, repositoryId );
942 catch ( MetadataRepositoryException e )
944 throw new ArchivaRestServiceException( e.getMessage(), e );
948 repositorySession.close();
953 public Boolean importMetadata( MetadataAddRequest metadataAddRequest, String repositoryId )
954 throws ArchivaRestServiceException
956 boolean result = true;
957 for ( Map.Entry<String, String> metadata : metadataAddRequest.getMetadatas().entrySet() )
959 result = addMetadata( metadataAddRequest.getGroupId(), metadataAddRequest.getArtifactId(),
960 metadataAddRequest.getVersion(), metadata.getKey(), metadata.getValue(),
970 //---------------------------
972 //---------------------------
974 private void closeQuietly( JarFile jarFile )
976 if ( jarFile != null )
982 catch ( IOException e )
984 log.warn( "ignore error closing jarFile {}", jarFile.getName() );
989 protected List<ArtifactContentEntry> readFileEntries( File file, String filterPath, String repoId )
992 Map<String, ArtifactContentEntry> artifactContentEntryMap = new HashMap<>();
993 int filterDepth = StringUtils.countMatches( filterPath, "/" );
994 /*if ( filterDepth == 0 )
998 JarFile jarFile = new JarFile( file );
1001 Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
1002 while ( jarEntryEnumeration.hasMoreElements() )
1004 JarEntry currentEntry = jarEntryEnumeration.nextElement();
1005 String cleanedEntryName = StringUtils.endsWith( currentEntry.getName(), "/" ) ? //
1006 StringUtils.substringBeforeLast( currentEntry.getName(), "/" ) : currentEntry.getName();
1007 String entryRootPath = getRootPath( cleanedEntryName );
1008 int depth = StringUtils.countMatches( cleanedEntryName, "/" );
1009 if ( StringUtils.isEmpty( filterPath ) //
1010 && !artifactContentEntryMap.containsKey( entryRootPath ) //
1011 && depth == filterDepth )
1014 artifactContentEntryMap.put( entryRootPath,
1015 new ArtifactContentEntry( entryRootPath, !currentEntry.isDirectory(),
1021 if ( StringUtils.startsWith( cleanedEntryName, filterPath ) //
1022 && ( depth == filterDepth || ( !currentEntry.isDirectory() && depth == filterDepth ) ) )
1024 artifactContentEntryMap.put( cleanedEntryName, new ArtifactContentEntry( cleanedEntryName,
1025 !currentEntry.isDirectory(),
1031 if ( StringUtils.isNotEmpty( filterPath ) )
1033 Map<String, ArtifactContentEntry> filteredArtifactContentEntryMap = new HashMap<>();
1035 for ( Map.Entry<String, ArtifactContentEntry> entry : artifactContentEntryMap.entrySet() )
1037 filteredArtifactContentEntryMap.put( entry.getKey(), entry.getValue() );
1040 List<ArtifactContentEntry> sorted = getSmallerDepthEntries( filteredArtifactContentEntryMap );
1041 if ( sorted == null )
1043 return Collections.emptyList();
1045 Collections.sort( sorted, ArtifactContentEntryComparator.INSTANCE );
1051 if ( jarFile != null )
1056 List<ArtifactContentEntry> sorted = new ArrayList<>( artifactContentEntryMap.values() );
1057 Collections.sort( sorted, ArtifactContentEntryComparator.INSTANCE );
1061 private List<ArtifactContentEntry> getSmallerDepthEntries( Map<String, ArtifactContentEntry> entries )
1063 int smallestDepth = Integer.MAX_VALUE;
1064 Map<Integer, List<ArtifactContentEntry>> perDepthList = new HashMap<>();
1065 for ( Map.Entry<String, ArtifactContentEntry> entry : entries.entrySet() )
1068 ArtifactContentEntry current = entry.getValue();
1070 if ( current.getDepth() < smallestDepth )
1072 smallestDepth = current.getDepth();
1075 List<ArtifactContentEntry> currentList = perDepthList.get( current.getDepth() );
1077 if ( currentList == null )
1079 currentList = new ArrayList<>();
1080 currentList.add( current );
1081 perDepthList.put( current.getDepth(), currentList );
1085 currentList.add( current );
1090 return perDepthList.get( smallestDepth );
1095 * @return org/apache -> org , org -> org
1097 private String getRootPath( String path )
1099 if ( StringUtils.contains( path, '/' ) )
1101 return StringUtils.substringBefore( path, "/" );
1106 private List<String> getSelectedRepos( String repositoryId )
1107 throws ArchivaRestServiceException
1110 List<String> selectedRepos = getObservableRepos();
1112 if ( CollectionUtils.isEmpty( selectedRepos ) )
1114 return Collections.emptyList();
1117 if ( StringUtils.isNotEmpty( repositoryId ) )
1119 // check user has karma on the repository
1120 if ( !selectedRepos.contains( repositoryId ) )
1122 throw new ArchivaRestServiceException( "browse.root.groups.repositoy.denied",
1123 Response.Status.FORBIDDEN.getStatusCode(), null );
1125 selectedRepos = Collections.singletonList( repositoryId );
1127 return selectedRepos;
1131 private String collapseNamespaces( RepositorySession repositorySession, MetadataResolver metadataResolver,
1132 Collection<String> repoIds, String n )
1133 throws MetadataResolutionException
1135 Set<String> subNamespaces = new LinkedHashSet<String>();
1136 for ( String repoId : repoIds )
1138 subNamespaces.addAll( metadataResolver.resolveNamespaces( repositorySession, repoId, n ) );
1140 if ( subNamespaces.size() != 1 )
1142 log.debug( "{} is not collapsible as it has sub-namespaces: {}", n, subNamespaces );
1147 for ( String repoId : repoIds )
1149 Collection<String> projects = metadataResolver.resolveProjects( repositorySession, repoId, n );
1150 if ( projects != null && !projects.isEmpty() )
1152 log.debug( "{} is not collapsible as it has projects", n );
1156 return collapseNamespaces( repositorySession, metadataResolver, repoIds,
1157 n + "." + subNamespaces.iterator().next() );
1161 public Cache getVersionMetadataCache()
1163 return versionMetadataCache;
1166 public void setVersionMetadataCache( Cache versionMetadataCache )
1168 this.versionMetadataCache = versionMetadataCache;