1 package org.apache.archiva.rest.v2.svc.maven;
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
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
20 import org.apache.archiva.admin.model.AuditInformation;
21 import org.apache.archiva.admin.model.RepositoryAdminException;
22 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
23 import org.apache.archiva.components.rest.model.PagedResult;
24 import org.apache.archiva.components.rest.util.QueryHelper;
25 import org.apache.archiva.configuration.model.ManagedRepositoryConfiguration;
26 import org.apache.archiva.redback.authentication.AuthenticationResult;
27 import org.apache.archiva.redback.authorization.AuthorizationException;
28 import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal;
29 import org.apache.archiva.redback.rest.services.RedbackRequestInformation;
30 import org.apache.archiva.redback.system.DefaultSecuritySession;
31 import org.apache.archiva.redback.system.SecuritySession;
32 import org.apache.archiva.redback.system.SecuritySystem;
33 import org.apache.archiva.redback.users.User;
34 import org.apache.archiva.redback.users.UserManagerException;
35 import org.apache.archiva.redback.users.UserNotFoundException;
36 import org.apache.archiva.repository.ManagedRepository;
37 import org.apache.archiva.repository.ReleaseScheme;
38 import org.apache.archiva.repository.Repository;
39 import org.apache.archiva.repository.RepositoryRegistry;
40 import org.apache.archiva.repository.RepositoryType;
41 import org.apache.archiva.repository.content.ContentItem;
42 import org.apache.archiva.repository.content.LayoutException;
43 import org.apache.archiva.repository.storage.fs.FsStorageUtil;
44 import org.apache.archiva.rest.api.v2.model.FileInfo;
45 import org.apache.archiva.rest.api.v2.model.MavenManagedRepository;
46 import org.apache.archiva.rest.api.v2.model.MavenManagedRepositoryUpdate;
47 import org.apache.archiva.rest.api.v2.svc.ArchivaRestServiceException;
48 import org.apache.archiva.rest.api.v2.svc.ErrorKeys;
49 import org.apache.archiva.rest.api.v2.svc.ErrorMessage;
50 import org.apache.archiva.rest.api.v2.svc.maven.MavenManagedRepositoryService;
51 import org.apache.archiva.security.common.ArchivaRoleConstants;
52 import org.apache.commons.lang3.StringUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.stereotype.Service;
57 import javax.servlet.http.HttpServletResponse;
58 import javax.ws.rs.core.Context;
59 import javax.ws.rs.core.Response;
60 import javax.ws.rs.core.UriInfo;
61 import java.io.IOException;
62 import java.util.Collection;
63 import java.util.Comparator;
64 import java.util.List;
65 import java.util.function.Predicate;
66 import java.util.stream.Collectors;
68 import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_READ_REPOSITORY;
69 import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_ADD_ARTIFACT;
72 * @author Martin Stockhammer <martin_s@apache.org>
74 @Service("v2.managedMavenRepositoryService#rest")
75 public class DefaultMavenManagedRepositoryService implements MavenManagedRepositoryService
78 HttpServletResponse httpServletResponse;
83 private static final Logger log = LoggerFactory.getLogger( DefaultMavenManagedRepositoryService.class );
84 private static final QueryHelper<ManagedRepository> QUERY_HELPER = new QueryHelper<>( new String[]{"id", "name"} );
87 QUERY_HELPER.addStringFilter( "id", ManagedRepository::getId );
88 QUERY_HELPER.addStringFilter( "name", ManagedRepository::getName );
89 QUERY_HELPER.addStringFilter( "location", (r) -> r.getLocation().toString() );
90 QUERY_HELPER.addBooleanFilter( "snapshot", (r) -> r.getActiveReleaseSchemes( ).contains( ReleaseScheme.SNAPSHOT ) );
91 QUERY_HELPER.addBooleanFilter( "release", (r) -> r.getActiveReleaseSchemes().contains( ReleaseScheme.RELEASE ));
92 QUERY_HELPER.addNullsafeFieldComparator( "id", ManagedRepository::getId );
93 QUERY_HELPER.addNullsafeFieldComparator( "name", ManagedRepository::getName );
96 private final ManagedRepositoryAdmin managedRepositoryAdmin;
97 private final RepositoryRegistry repositoryRegistry;
98 private final SecuritySystem securitySystem;
100 public DefaultMavenManagedRepositoryService( SecuritySystem securitySystem,
101 RepositoryRegistry repositoryRegistry,
102 ManagedRepositoryAdmin managedRepositoryAdmin )
104 this.securitySystem = securitySystem;
105 this.repositoryRegistry = repositoryRegistry;
106 this.managedRepositoryAdmin = managedRepositoryAdmin;
109 protected AuditInformation getAuditInformation( )
111 RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get( );
114 if (redbackRequestInformation==null) {
119 user = redbackRequestInformation.getUser( );
120 remoteAddr = redbackRequestInformation.getRemoteAddr( );
122 return new AuditInformation( user, remoteAddr );
125 public static ManagedRepositoryConfiguration toConfig(MavenManagedRepository repo) {
126 ManagedRepositoryConfiguration cfg = new ManagedRepositoryConfiguration( );
132 public PagedResult<MavenManagedRepository> getManagedRepositories( final String searchTerm, final Integer offset,
133 final Integer limit, final List<String> orderBy,
134 final String order ) throws ArchivaRestServiceException
138 Collection<ManagedRepository> repos = repositoryRegistry.getManagedRepositories( );
139 final Predicate<ManagedRepository> queryFilter = QUERY_HELPER.getQueryFilter( searchTerm ).and( r -> r.getType() == RepositoryType.MAVEN );
140 final Comparator<ManagedRepository> comparator = QUERY_HELPER.getComparator( orderBy, order );
141 int totalCount = Math.toIntExact( repos.stream( ).filter( queryFilter ).count( ) );
142 return PagedResult.of( totalCount, offset, limit, repos.stream( ).filter( queryFilter ).sorted( comparator )
143 .map( MavenManagedRepository::of ).skip( offset ).limit( limit ).collect( Collectors.toList( ) ) );
145 catch (ArithmeticException e) {
146 log.error( "Invalid number of repositories detected." );
147 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.INVALID_RESULT_SET_ERROR ) );
152 public MavenManagedRepository getManagedRepository( String repositoryId ) throws ArchivaRestServiceException
154 ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
156 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
158 if (repo.getType()!=RepositoryType.MAVEN) {
159 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_WRONG_TYPE, repositoryId, repo.getType().name() ), 404 );
161 return MavenManagedRepository.of( repo );
165 public Response deleteManagedRepository( String repositoryId, Boolean deleteContent ) throws ArchivaRestServiceException
167 MavenManagedRepository repo = getManagedRepository( repositoryId );
172 managedRepositoryAdmin.deleteManagedRepository( repositoryId, getAuditInformation( ), deleteContent );
173 return Response.ok( ).build( );
175 catch ( RepositoryAdminException e )
177 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_DELETE_FAILED, e.getMessage( ) ) );
180 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
184 private org.apache.archiva.admin.model.beans.ManagedRepository convert(MavenManagedRepository repository) {
185 org.apache.archiva.admin.model.beans.ManagedRepository repoBean = new org.apache.archiva.admin.model.beans.ManagedRepository( );
186 repoBean.setId( repository.getId( ) );
187 repoBean.setName( repository.getName() );
188 repoBean.setDescription( repository.getDescription() );
189 repoBean.setBlockRedeployments( repository.isBlocksRedeployments() );
190 repoBean.setCronExpression( repository.getSchedulingDefinition() );
191 repoBean.setLocation( repository.getLocation() );
192 repoBean.setReleases( repository.getReleaseSchemes().contains( ReleaseScheme.RELEASE.name() ) );
193 repoBean.setSnapshots( repository.getReleaseSchemes().contains( ReleaseScheme.SNAPSHOT.name() ) );
194 repoBean.setScanned( repository.isScanned() );
195 repoBean.setDeleteReleasedSnapshots( repository.isDeleteSnapshotsOfRelease() );
196 repoBean.setSkipPackedIndexCreation( repository.isSkipPackedIndexCreation() );
197 repoBean.setRetentionCount( repository.getRetentionCount() );
198 if (repository.getRetentionPeriod()!=null)
200 repoBean.setRetentionPeriod( repository.getRetentionPeriod( ).getDays( ) );
202 repoBean.setIndexDirectory( repository.getIndexPath() );
203 repoBean.setPackedIndexDirectory( repository.getPackedIndexPath() );
204 repoBean.setLayout( repository.getLayout() );
205 repoBean.setType( RepositoryType.MAVEN.name( ) );
210 public MavenManagedRepository addManagedRepository( MavenManagedRepository managedRepository ) throws ArchivaRestServiceException
212 final String repoId = managedRepository.getId( );
213 if ( StringUtils.isEmpty( repoId ) ) {
214 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_INVALID_ID, repoId ), 422 );
216 Repository repo = repositoryRegistry.getRepository( repoId );
218 httpServletResponse.setHeader( "Location", uriInfo.getAbsolutePathBuilder( ).path( repoId ).build( ).toString( ) );
219 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ID_EXISTS, repoId ), 303 );
223 managedRepositoryAdmin.addManagedRepository( convert( managedRepository ), managedRepository.isHasStagingRepository(), getAuditInformation() );
224 httpServletResponse.setStatus( 201 );
225 return MavenManagedRepository.of( repositoryRegistry.getManagedRepository( repoId ) );
227 catch ( RepositoryAdminException e )
229 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) );
234 public MavenManagedRepository updateManagedRepository( final String repositoryId, final MavenManagedRepositoryUpdate managedRepository ) throws ArchivaRestServiceException
236 org.apache.archiva.admin.model.beans.ManagedRepository repo = convert( managedRepository );
239 managedRepositoryAdmin.updateManagedRepository( repo, managedRepository.isHasStagingRepository( ), getAuditInformation( ), managedRepository.isResetStats( ) );
240 ManagedRepository newRepo = repositoryRegistry.getManagedRepository( managedRepository.getId( ) );
242 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_UPDATE_FAILED, repositoryId ) );
244 return MavenManagedRepository.of( newRepo );
246 catch ( RepositoryAdminException e )
248 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) );
253 public FileInfo getFileStatus( String repositoryId, String fileLocation ) throws ArchivaRestServiceException
255 ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
257 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
261 ContentItem contentItem = repo.getContent( ).toItem( fileLocation );
262 if (contentItem.getAsset( ).exists( )) {
263 return FileInfo.of( contentItem.getAsset( ) );
265 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, repositoryId, fileLocation ), 404 );
268 catch ( LayoutException e )
270 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage( ) ) );
275 public Response copyArtifact( String srcRepositoryId, String dstRepositoryId,
276 String path ) throws ArchivaRestServiceException
278 final AuditInformation auditInformation = getAuditInformation( );
279 final String userName = auditInformation.getUser( ).getUsername( );
280 if ( StringUtils.isEmpty( userName ) )
282 httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" );
283 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.NOT_AUTHENTICATED ), 401 );
285 ManagedRepository srcRepo = repositoryRegistry.getManagedRepository( srcRepositoryId );
287 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, srcRepositoryId ), 404 );
289 ManagedRepository dstRepo = repositoryRegistry.getManagedRepository( dstRepositoryId );
291 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, dstRepositoryId ), 404 );
293 checkAuthority( auditInformation.getUser().getUsername(), srcRepositoryId, dstRepositoryId );
296 ContentItem srcItem = srcRepo.getContent( ).toItem( path );
297 ContentItem dstItem = dstRepo.getContent( ).toItem( path );
298 if (!srcItem.getAsset().exists()){
299 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, srcRepositoryId, path ), 404 );
301 if (dstItem.getAsset().exists()) {
302 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_EXISTS_AT_DEST, srcRepositoryId, path ), 400 );
304 FsStorageUtil.copyAsset( srcItem.getAsset( ), dstItem.getAsset( ), true );
306 catch ( LayoutException e )
308 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage() ) );
310 catch ( IOException e )
312 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_COPY_ERROR, e.getMessage() ) );
314 return Response.ok( ).build();
317 private void checkAuthority(final String userName, final String srcRepositoryId, final String dstRepositoryId ) throws ArchivaRestServiceException {
321 user = securitySystem.getUserManager().findUser( userName );
323 catch ( UserNotFoundException e )
325 httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" );
326 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_NOT_FOUND, userName ), 401 );
328 catch ( UserManagerException e )
330 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_MANAGER_ERROR, e.getMessage( ) ) );
333 // check karma on source : read
334 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
335 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
339 securitySystem.isAuthorized( securitySession, OPERATION_READ_REPOSITORY,
343 throw new ArchivaRestServiceException(ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, srcRepositoryId, OPERATION_READ_REPOSITORY ), 403);
346 catch ( AuthorizationException e )
348 log.error( "Error reading permission: {}", e.getMessage(), e );
349 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403);
352 // check karma on target: write
356 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_ADD_ARTIFACT,
360 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, dstRepositoryId, OPERATION_ADD_ARTIFACT ) );
363 catch ( AuthorizationException e )
365 log.error( "Error reading permission: {}", e.getMessage(), e );
366 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403);
373 public Response deleteArtifact( String repositoryId, String path ) throws ArchivaRestServiceException
381 public Response removeProjectVersion( String repositoryId, String namespace, String projectId, String version ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException
387 public Response deleteProject( String repositoryId, String namespace, String projectId ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException
393 public Response deleteNamespace( String repositoryId, String namespace ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException