1 package org.apache.archiva.rest.services;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.AuditInformation;
23 import org.apache.archiva.admin.model.RepositoryAdminException;
24 import org.apache.archiva.admin.model.admin.ArchivaAdministration;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.audit.AuditEvent;
27 import org.apache.archiva.audit.AuditListener;
28 import org.apache.archiva.common.utils.VersionUtil;
29 import org.apache.archiva.maven2.model.Artifact;
30 import org.apache.archiva.metadata.model.ArtifactMetadata;
31 import org.apache.archiva.metadata.repository.RepositorySessionFactory;
32 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
33 import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal;
34 import org.apache.archiva.redback.rest.services.RedbackRequestInformation;
35 import org.apache.archiva.redback.users.User;
36 import org.apache.archiva.redback.users.UserManager;
37 import org.apache.archiva.repository.RepositoryContentFactory;
38 import org.apache.archiva.repository.RepositoryException;
39 import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
40 import org.apache.archiva.rest.services.utils.ArtifactBuilder;
41 import org.apache.archiva.scheduler.repository.DefaultRepositoryArchivaTaskScheduler;
42 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
43 import org.apache.archiva.security.AccessDeniedException;
44 import org.apache.archiva.security.ArchivaSecurityException;
45 import org.apache.archiva.security.PrincipalNotFoundException;
46 import org.apache.archiva.security.UserRepositories;
47 import org.apache.commons.lang.StringUtils;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.context.ApplicationContext;
52 import javax.inject.Inject;
53 import javax.inject.Named;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.ws.rs.core.Context;
56 import javax.ws.rs.core.Response;
57 import java.util.ArrayList;
58 import java.util.Collections;
59 import java.util.HashMap;
60 import java.util.List;
64 * abstract class with common utilities methods
66 * @author Olivier Lamy
69 public abstract class AbstractRestService
72 protected Logger log = LoggerFactory.getLogger( getClass() );
75 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
78 protected UserRepositories userRepositories;
82 @Named(value = "repositorySessionFactory")
83 protected RepositorySessionFactory repositorySessionFactory;
86 protected ArchivaAdministration archivaAdministration;
89 protected ManagedRepositoryAdmin managedRepositoryAdmin;
92 protected RepositoryContentFactory repositoryContentFactory;
95 @Named(value = "archivaTaskScheduler#repository")
96 protected DefaultRepositoryArchivaTaskScheduler repositoryTaskScheduler;
99 protected HttpServletRequest httpServletRequest;
101 protected AuditInformation getAuditInformation()
103 RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
104 User user = redbackRequestInformation == null ? null : redbackRequestInformation.getUser();
105 String remoteAddr = redbackRequestInformation == null ? null : redbackRequestInformation.getRemoteAddr();
106 return new AuditInformation( user, remoteAddr );
109 public List<AuditListener> getAuditListeners()
111 return auditListeners;
114 public void setAuditListeners( List<AuditListener> auditListeners )
116 this.auditListeners = auditListeners;
119 protected List<String> getObservableRepos()
123 List<String> ids = userRepositories.getObservableRepositoryIds( getPrincipal() );
124 return ids == null ? Collections.<String>emptyList() : ids;
126 catch ( PrincipalNotFoundException e )
128 log.warn( e.getMessage(), e );
130 catch ( AccessDeniedException e )
132 log.warn( e.getMessage(), e );
134 catch ( ArchivaSecurityException e )
136 log.warn( e.getMessage(), e );
138 return Collections.emptyList();
141 protected String getPrincipal()
143 RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
145 return redbackRequestInformation == null
146 ? UserManager.GUEST_USERNAME
147 : ( redbackRequestInformation.getUser() == null
148 ? UserManager.GUEST_USERNAME
149 : redbackRequestInformation.getUser().getUsername() );
152 protected String getBaseUrl()
153 throws RepositoryAdminException
155 String applicationUrl = archivaAdministration.getUiConfiguration().getApplicationUrl();
156 if ( StringUtils.isNotBlank( applicationUrl ) )
158 return applicationUrl;
160 return httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + (
161 httpServletRequest.getServerPort() == 80 ? "" : ":" + httpServletRequest.getServerPort() )
162 + httpServletRequest.getContextPath();
165 protected <T> Map<String, T> getBeansOfType( ApplicationContext applicationContext, Class<T> clazz )
167 //TODO do some caching here !!!
168 // olamy : with plexus we get only roleHint
169 // as per convention we named spring bean role#hint remove role# if exists
170 Map<String, T> springBeans = applicationContext.getBeansOfType( clazz );
172 Map<String, T> beans = new HashMap<String, T>( springBeans.size() );
174 for ( Map.Entry<String, T> entry : springBeans.entrySet() )
176 String key = StringUtils.contains( entry.getKey(), '#' )
177 ? StringUtils.substringAfterLast( entry.getKey(), "#" )
179 beans.put( key, entry.getValue() );
184 protected void triggerAuditEvent( String repositoryId, String filePath, String action )
186 AuditEvent auditEvent = new AuditEvent( repositoryId, getPrincipal(), filePath, action );
187 AuditInformation auditInformation = getAuditInformation();
188 auditEvent.setUserId( auditInformation.getUser() == null ? "" : auditInformation.getUser().getUsername() );
189 auditEvent.setRemoteIP( auditInformation.getRemoteAddr() );
190 for ( AuditListener auditListener : getAuditListeners() )
192 auditListener.auditEvent( auditEvent );
200 protected String getArtifactUrl( Artifact artifact )
201 throws ArchivaRestServiceException
206 if ( httpServletRequest == null )
211 StringBuilder sb = new StringBuilder( getBaseUrl() );
213 sb.append( "/repository" );
215 // FIXME when artifact come from a remote repository when have here the remote repo id
216 // we must replace it with a valid managed one available for the user.
218 sb.append( '/' ).append( artifact.getContext() );
220 sb.append( '/' ).append( StringUtils.replaceChars( artifact.getGroupId(), '.', '/' ) );
221 sb.append( '/' ).append( artifact.getArtifactId() );
222 if ( VersionUtil.isSnapshot( artifact.getVersion() ) )
224 sb.append( '/' ).append( VersionUtil.getBaseVersion( artifact.getVersion() ) );
228 sb.append( '/' ).append( artifact.getVersion() );
230 sb.append( '/' ).append( artifact.getArtifactId() );
231 sb.append( '-' ).append( artifact.getVersion() );
232 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
234 sb.append( '-' ).append( artifact.getClassifier() );
236 // maven-plugin packaging is a jar
237 if ( StringUtils.equals( "maven-plugin", artifact.getPackaging() ) )
243 sb.append( '.' ).append( artifact.getFileExtension() );
246 return sb.toString();
248 catch ( RepositoryAdminException e )
250 throw new ArchivaRestServiceException( e.getMessage(),
251 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
255 protected List<Artifact> buildArtifacts( List<ArtifactMetadata> artifactMetadatas, String repositoryId )
256 throws ArchivaRestServiceException
260 if ( artifactMetadatas != null && !artifactMetadatas.isEmpty() )
262 List<Artifact> artifacts = new ArrayList<Artifact>( artifactMetadatas.size() );
263 for ( ArtifactMetadata artifact : artifactMetadatas )
266 ArtifactBuilder builder =
267 new ArtifactBuilder().forArtifactMetadata( artifact ).withManagedRepositoryContent(
268 repositoryContentFactory.getManagedRepositoryContent( repositoryId ) );
269 Artifact art = builder.build();
270 art.setUrl( getArtifactUrl( art ) );
271 artifacts.add( art );
275 return Collections.emptyList();
277 catch ( RepositoryException e )
279 log.error( e.getMessage(), e );
280 throw new ArchivaRestServiceException( e.getMessage(),
281 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
285 protected Boolean doScanRepository( String repositoryId, boolean fullScan )
287 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
289 log.info( "scanning of repository with id {} already scheduled", repositoryId );
290 return Boolean.FALSE;
292 RepositoryTask task = new RepositoryTask();
293 task.setRepositoryId( repositoryId );
294 task.setScanAll( fullScan );
297 repositoryTaskScheduler.queueTask( task );
299 catch ( TaskQueueException e )
301 log.error( "failed to schedule scanning of repo with id {}", repositoryId, e );