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.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.substringAfterLast( entry.getKey(), "#" );
177 beans.put( key, entry.getValue() );
182 protected void triggerAuditEvent( String repositoryId, String filePath, String action )
184 AuditEvent auditEvent = new AuditEvent( repositoryId, getPrincipal(), filePath, action );
185 AuditInformation auditInformation = getAuditInformation();
186 auditEvent.setUserId( auditInformation.getUser() == null ? "" : auditInformation.getUser().getUsername() );
187 auditEvent.setRemoteIP( auditInformation.getRemoteAddr() );
188 for ( AuditListener auditListener : getAuditListeners() )
190 auditListener.auditEvent( auditEvent );
198 protected String getArtifactUrl( Artifact artifact )
199 throws ArchivaRestServiceException
204 if ( httpServletRequest == null )
209 StringBuilder sb = new StringBuilder( getBaseUrl() );
211 sb.append( "/repository" );
213 // FIXME when artifact come from a remote repository when have here the remote repo id
214 // we must replace it with a valid managed one available for the user.
216 sb.append( '/' ).append( artifact.getContext() );
218 sb.append( '/' ).append( StringUtils.replaceChars( artifact.getGroupId(), '.', '/' ) );
219 sb.append( '/' ).append( artifact.getArtifactId() );
220 if ( VersionUtil.isSnapshot( artifact.getVersion() ) )
222 sb.append( '/' ).append( VersionUtil.getBaseVersion( artifact.getVersion() ) );
226 sb.append( '/' ).append( artifact.getVersion() );
228 sb.append( '/' ).append( artifact.getArtifactId() );
229 sb.append( '-' ).append( artifact.getVersion() );
230 if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
232 sb.append( '-' ).append( artifact.getClassifier() );
234 // maven-plugin packaging is a jar
235 if ( StringUtils.equals( "maven-plugin", artifact.getPackaging() ) )
241 sb.append( '.' ).append( artifact.getFileExtension() );
244 return sb.toString();
246 catch ( RepositoryAdminException e )
248 throw new ArchivaRestServiceException( e.getMessage(),
249 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
253 protected List<Artifact> buildArtifacts( List<ArtifactMetadata> artifactMetadatas, String repositoryId )
254 throws ArchivaRestServiceException
258 if ( artifactMetadatas != null && !artifactMetadatas.isEmpty() )
260 List<Artifact> artifacts = new ArrayList<Artifact>( artifactMetadatas.size() );
261 for ( ArtifactMetadata artifact : artifactMetadatas )
264 ArtifactBuilder builder =
265 new ArtifactBuilder().forArtifactMetadata( artifact ).withManagedRepositoryContent(
266 repositoryContentFactory.getManagedRepositoryContent( repositoryId ) );
267 Artifact art = builder.build();
268 art.setUrl( getArtifactUrl( art ) );
269 artifacts.add( art );
273 return Collections.emptyList();
275 catch ( RepositoryException e )
277 log.error( e.getMessage(), e );
278 throw new ArchivaRestServiceException( e.getMessage(),
279 Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
283 protected Boolean doScanRepository( String repositoryId, boolean fullScan )
285 if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
287 log.info( "scanning of repository with id {} already scheduled", repositoryId );
288 return Boolean.FALSE;
290 RepositoryTask task = new RepositoryTask();
291 task.setRepositoryId( repositoryId );
292 task.setScanAll( fullScan );
295 repositoryTaskScheduler.queueTask( task );
297 catch ( TaskQueueException e )
299 log.error( "failed to schedule scanning of repo with id {}", repositoryId, e );