1 package org.apache.archiva.rest.v2.svc;
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.redback.authentication.AuthenticationResult;
26 import org.apache.archiva.redback.authorization.AuthorizationException;
27 import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal;
28 import org.apache.archiva.redback.rest.services.RedbackRequestInformation;
29 import org.apache.archiva.redback.system.DefaultSecuritySession;
30 import org.apache.archiva.redback.system.SecuritySession;
31 import org.apache.archiva.redback.system.SecuritySystem;
32 import org.apache.archiva.redback.users.User;
33 import org.apache.archiva.redback.users.UserManagerException;
34 import org.apache.archiva.redback.users.UserNotFoundException;
35 import org.apache.archiva.repository.ManagedRepository;
36 import org.apache.archiva.repository.ReleaseScheme;
37 import org.apache.archiva.repository.Repository;
38 import org.apache.archiva.repository.RepositoryRegistry;
39 import org.apache.archiva.repository.RepositoryType;
40 import org.apache.archiva.repository.content.ContentItem;
41 import org.apache.archiva.repository.content.LayoutException;
42 import org.apache.archiva.repository.storage.fs.FsStorageUtil;
43 import org.apache.archiva.rest.api.v2.model.FileInfo;
44 import org.apache.archiva.rest.api.v2.model.MavenManagedRepository;
45 import org.apache.archiva.rest.api.v2.model.MavenManagedRepositoryUpdate;
46 import org.apache.archiva.rest.api.v2.svc.ArchivaRestServiceException;
47 import org.apache.archiva.rest.api.v2.svc.ErrorKeys;
48 import org.apache.archiva.rest.api.v2.svc.ErrorMessage;
49 import org.apache.archiva.rest.api.v2.svc.maven.MavenManagedRepositoryService;
50 import org.apache.archiva.security.common.ArchivaRoleConstants;
51 import org.apache.commons.lang3.StringUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.stereotype.Service;
56 import javax.servlet.http.HttpServletResponse;
57 import javax.ws.rs.core.Context;
58 import javax.ws.rs.core.Response;
59 import javax.ws.rs.core.UriInfo;
60 import java.io.IOException;
61 import java.util.Collection;
62 import java.util.Comparator;
63 import java.util.List;
64 import java.util.function.Predicate;
65 import java.util.stream.Collectors;
67 import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS;
68 import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD;
71 * @author Martin Stockhammer <martin_s@apache.org>
73 @Service("v2.managedMavenRepositoryService#rest")
74 public class DefaultMavenManagedRepositoryService implements MavenManagedRepositoryService
77 HttpServletResponse httpServletResponse;
82 private static final Logger log = LoggerFactory.getLogger( DefaultMavenManagedRepositoryService.class );
83 private static final QueryHelper<ManagedRepository> QUERY_HELPER = new QueryHelper<>( new String[]{"id", "name"} );
86 QUERY_HELPER.addStringFilter( "id", ManagedRepository::getId );
87 QUERY_HELPER.addStringFilter( "name", ManagedRepository::getName );
88 QUERY_HELPER.addStringFilter( "location", (r) -> r.getLocation().toString() );
89 QUERY_HELPER.addBooleanFilter( "snapshot", (r) -> r.getActiveReleaseSchemes( ).contains( ReleaseScheme.SNAPSHOT ) );
90 QUERY_HELPER.addBooleanFilter( "release", (r) -> r.getActiveReleaseSchemes().contains( ReleaseScheme.RELEASE ));
91 QUERY_HELPER.addNullsafeFieldComparator( "id", ManagedRepository::getId );
92 QUERY_HELPER.addNullsafeFieldComparator( "name", ManagedRepository::getName );
95 private ManagedRepositoryAdmin managedRepositoryAdmin;
96 private RepositoryRegistry repositoryRegistry;
97 private SecuritySystem securitySystem;
99 public DefaultMavenManagedRepositoryService( SecuritySystem securitySystem,
100 RepositoryRegistry repositoryRegistry,
101 ManagedRepositoryAdmin managedRepositoryAdmin )
103 this.securitySystem = securitySystem;
104 this.repositoryRegistry = repositoryRegistry;
105 this.managedRepositoryAdmin = managedRepositoryAdmin;
108 protected AuditInformation getAuditInformation( )
110 RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get( );
113 if (redbackRequestInformation==null) {
118 user = redbackRequestInformation.getUser( );
119 remoteAddr = redbackRequestInformation.getRemoteAddr( );
121 return new AuditInformation( user, remoteAddr );
125 public PagedResult<MavenManagedRepository> getManagedRepositories( final String searchTerm, final Integer offset,
126 final Integer limit, final List<String> orderBy,
127 final String order ) throws ArchivaRestServiceException
131 Collection<ManagedRepository> repos = repositoryRegistry.getManagedRepositories( );
132 final Predicate<ManagedRepository> queryFilter = QUERY_HELPER.getQueryFilter( searchTerm ).and( r -> r.getType() == RepositoryType.MAVEN );
133 final Comparator<ManagedRepository> comparator = QUERY_HELPER.getComparator( orderBy, order );
134 int totalCount = Math.toIntExact( repos.stream( ).filter( queryFilter ).count( ) );
135 return PagedResult.of( totalCount, offset, limit, repos.stream( ).filter( queryFilter ).sorted( comparator )
136 .map(mr -> MavenManagedRepository.of(mr)).skip( offset ).limit( limit ).collect( Collectors.toList( ) ) );
138 catch (ArithmeticException e) {
139 log.error( "Invalid number of repositories detected." );
140 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.INVALID_RESULT_SET_ERROR ) );
145 public MavenManagedRepository getManagedRepository( String repositoryId ) throws ArchivaRestServiceException
147 ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
149 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
151 if (repo.getType()!=RepositoryType.MAVEN) {
152 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_WRONG_TYPE, repositoryId, repo.getType().name() ), 404 );
154 return MavenManagedRepository.of( repo );
158 public Response deleteManagedRepository( String repositoryId, boolean deleteContent ) throws ArchivaRestServiceException
160 ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
162 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
164 if (repo.getType()!=RepositoryType.MAVEN) {
165 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_WRONG_TYPE, repositoryId, repo.getType().name() ), 404 );
169 managedRepositoryAdmin.deleteManagedRepository( repositoryId, getAuditInformation( ), deleteContent );
170 return Response.ok( ).build( );
172 catch ( RepositoryAdminException e )
174 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_DELETE_FAILED, e.getMessage( ) ) );
178 private org.apache.archiva.admin.model.beans.ManagedRepository convert(MavenManagedRepository repository) {
179 org.apache.archiva.admin.model.beans.ManagedRepository repoBean = new org.apache.archiva.admin.model.beans.ManagedRepository( );
180 repoBean.setId( repository.getId( ) );
181 repoBean.setName( repository.getName() );
182 repoBean.setDescription( repository.getDescription() );
183 repoBean.setBlockRedeployments( repository.isBlocksRedeployments() );
184 repoBean.setCronExpression( repository.getSchedulingDefinition() );
185 repoBean.setLocation( repository.getLocation() );
186 repoBean.setReleases( repository.getReleaseSchemes().contains( ReleaseScheme.RELEASE.name() ) );
187 repoBean.setSnapshots( repository.getReleaseSchemes().contains( ReleaseScheme.SNAPSHOT.name() ) );
188 repoBean.setScanned( repository.isScanned() );
189 repoBean.setDeleteReleasedSnapshots( repository.isDeleteSnapshotsOfRelease() );
190 repoBean.setSkipPackedIndexCreation( repository.isSkipPackedIndexCreation() );
191 repoBean.setRetentionCount( repository.getRetentionCount() );
192 repoBean.setRetentionPeriod( repository.getRetentionPeriod().getDays() );
193 repoBean.setIndexDirectory( repository.getIndexPath() );
194 repoBean.setPackedIndexDirectory( repository.getPackedIndexPath() );
195 repoBean.setLayout( repository.getLayout() );
196 repoBean.setType( RepositoryType.MAVEN.name( ) );
201 public MavenManagedRepository addManagedRepository( MavenManagedRepository managedRepository ) throws ArchivaRestServiceException
203 final String repoId = managedRepository.getId( );
204 if ( StringUtils.isEmpty( repoId ) ) {
205 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_INVALID_ID, repoId ), 422 );
207 Repository repo = repositoryRegistry.getRepository( repoId );
209 httpServletResponse.setHeader( "Location", uriInfo.getAbsolutePathBuilder( ).path( repoId ).build( ).toString( ) );
210 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ID_EXISTS, repoId ), 303 );
214 managedRepositoryAdmin.addManagedRepository( convert( managedRepository ), managedRepository.isHasStagingRepository(), getAuditInformation() );
215 httpServletResponse.setStatus( 201 );
216 return MavenManagedRepository.of( repositoryRegistry.getManagedRepository( repoId ) );
218 catch ( RepositoryAdminException e )
220 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) );
225 public MavenManagedRepository updateManagedRepository( final String repositoryId, final MavenManagedRepositoryUpdate managedRepository ) throws ArchivaRestServiceException
227 org.apache.archiva.admin.model.beans.ManagedRepository repo = convert( managedRepository );
230 managedRepositoryAdmin.updateManagedRepository( repo, managedRepository.isHasStagingRepository( ), getAuditInformation( ), managedRepository.isResetStats( ) );
231 ManagedRepository newRepo = repositoryRegistry.getManagedRepository( managedRepository.getId( ) );
233 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_UPDATE_FAILED, repositoryId ) );
235 return MavenManagedRepository.of( newRepo );
237 catch ( RepositoryAdminException e )
239 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) );
244 public FileInfo getFileStatus( String repositoryId, String fileLocation ) throws ArchivaRestServiceException
246 ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
248 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 );
252 ContentItem contentItem = repo.getContent( ).toItem( fileLocation );
253 if (contentItem.getAsset( ).exists( )) {
254 return FileInfo.of( contentItem.getAsset( ) );
256 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, repositoryId, fileLocation ), 404 );
259 catch ( LayoutException e )
261 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage( ) ) );
266 public Response copyArtifact( String srcRepositoryId, String dstRepositoryId,
267 String path ) throws ArchivaRestServiceException
269 final AuditInformation auditInformation = getAuditInformation( );
270 final String userName = auditInformation.getUser( ).getUsername( );
271 if ( StringUtils.isEmpty( userName ) )
273 httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" );
274 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.NOT_AUTHENTICATED ), 401 );
276 ManagedRepository srcRepo = repositoryRegistry.getManagedRepository( srcRepositoryId );
278 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, srcRepositoryId ), 404 );
280 ManagedRepository dstRepo = repositoryRegistry.getManagedRepository( dstRepositoryId );
282 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, dstRepositoryId ), 404 );
284 checkAuthority( auditInformation.getUser().getUsername(), srcRepositoryId, dstRepositoryId );
287 ContentItem srcItem = srcRepo.getContent( ).toItem( path );
288 ContentItem dstItem = dstRepo.getContent( ).toItem( path );
289 if (!srcItem.getAsset().exists()){
290 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, srcRepositoryId, path ), 404 );
292 if (dstItem.getAsset().exists()) {
293 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_EXISTS_AT_DEST, srcRepositoryId, path ), 400 );
295 FsStorageUtil.copyAsset( srcItem.getAsset( ), dstItem.getAsset( ), true );
297 catch ( LayoutException e )
299 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage() ) );
301 catch ( IOException e )
303 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_COPY_ERROR, e.getMessage() ) );
305 return Response.ok( ).build();
308 private void checkAuthority(final String userName, final String srcRepositoryId, final String dstRepositoryId ) throws ArchivaRestServiceException {
312 user = securitySystem.getUserManager().findUser( userName );
314 catch ( UserNotFoundException e )
316 httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" );
317 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_NOT_FOUND, userName ), 401 );
319 catch ( UserManagerException e )
321 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_MANAGER_ERROR, e.getMessage( ) ) );
324 // check karma on source : read
325 AuthenticationResult authn = new AuthenticationResult( true, userName, null );
326 SecuritySession securitySession = new DefaultSecuritySession( authn, user );
330 securitySystem.isAuthorized( securitySession, OPERATION_REPOSITORY_ACCESS,
334 throw new ArchivaRestServiceException(ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, srcRepositoryId, OPERATION_REPOSITORY_ACCESS ), 403);
337 catch ( AuthorizationException e )
339 log.error( "Error reading permission: {}", e.getMessage(), e );
340 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403);
343 // check karma on target: write
347 securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD,
351 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, dstRepositoryId, OPERATION_REPOSITORY_UPLOAD ) );
354 catch ( AuthorizationException e )
356 log.error( "Error reading permission: {}", e.getMessage(), e );
357 throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403);
364 public Response deleteArtifact( String repositoryId, String path ) throws ArchivaRestServiceException
372 public Response removeProjectVersion( String repositoryId, String namespace, String projectId, String version ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException
378 public Response deleteProject( String repositoryId, String namespace, String projectId ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException
384 public Response deleteNamespace( String repositoryId, String namespace ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException