You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RepositoryModelResolver.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. package org.apache.archiva.metadata.repository.storage.maven2;
  2. /*
  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
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  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
  18. * under the License.
  19. */
  20. import java.io.File;
  21. import java.io.IOException;
  22. import java.util.List;
  23. import java.util.Map;
  24. import org.apache.archiva.metadata.repository.storage.RepositoryPathTranslator;
  25. import org.apache.archiva.proxy.common.WagonFactory;
  26. import org.apache.archiva.proxy.common.WagonFactoryException;
  27. import org.apache.commons.io.FileUtils;
  28. import org.apache.commons.lang.StringUtils;
  29. import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
  30. import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
  31. import org.apache.maven.model.Repository;
  32. import org.apache.maven.model.building.FileModelSource;
  33. import org.apache.maven.model.building.ModelSource;
  34. import org.apache.maven.model.resolution.InvalidRepositoryException;
  35. import org.apache.maven.model.resolution.ModelResolver;
  36. import org.apache.maven.model.resolution.UnresolvableModelException;
  37. import org.apache.maven.wagon.ConnectionException;
  38. import org.apache.maven.wagon.ResourceDoesNotExistException;
  39. import org.apache.maven.wagon.TransferFailedException;
  40. import org.apache.maven.wagon.Wagon;
  41. import org.apache.maven.wagon.authentication.AuthenticationException;
  42. import org.apache.maven.wagon.authentication.AuthenticationInfo;
  43. import org.apache.maven.wagon.authorization.AuthorizationException;
  44. import org.apache.maven.wagon.proxy.ProxyInfo;
  45. import org.slf4j.Logger;
  46. import org.slf4j.LoggerFactory;
  47. public class RepositoryModelResolver
  48. implements ModelResolver
  49. {
  50. private File basedir;
  51. private RepositoryPathTranslator pathTranslator;
  52. private WagonFactory wagonFactory;
  53. private List<RemoteRepositoryConfiguration> remoteRepositories;
  54. private ManagedRepositoryConfiguration targetRepository;
  55. private static final Logger log = LoggerFactory.getLogger( RepositoryModelResolver.class );
  56. // key/value: remote repo ID/network proxy
  57. Map<String, ProxyInfo> networkProxyMap;
  58. public RepositoryModelResolver( File basedir, RepositoryPathTranslator pathTranslator )
  59. {
  60. this.basedir = basedir;
  61. this.pathTranslator = pathTranslator;
  62. }
  63. public RepositoryModelResolver( File basedir, RepositoryPathTranslator pathTranslator,
  64. WagonFactory wagonFactory, List<RemoteRepositoryConfiguration> remoteRepositories,
  65. Map<String, ProxyInfo> networkProxiesMap, ManagedRepositoryConfiguration targetRepository )
  66. {
  67. this( basedir, pathTranslator );
  68. this.wagonFactory = wagonFactory;
  69. this.remoteRepositories = remoteRepositories;
  70. this.networkProxyMap = networkProxiesMap;
  71. this.targetRepository = targetRepository;
  72. }
  73. public ModelSource resolveModel( String groupId, String artifactId, String version )
  74. throws UnresolvableModelException
  75. {
  76. String filename = artifactId + "-" + version + ".pom";
  77. // TODO: we need to convert 1.0-20091120.112233-1 type paths to baseVersion for the below call - add a test
  78. File model = pathTranslator.toFile( basedir, groupId, artifactId, version, filename );
  79. if( !model.exists() )
  80. {
  81. for( RemoteRepositoryConfiguration remoteRepository : remoteRepositories )
  82. {
  83. try
  84. {
  85. boolean success = getModelFromProxy( remoteRepository, groupId, artifactId, version, filename );
  86. if( success && model.exists() )
  87. {
  88. log.info( "Model '" + model.getAbsolutePath() + "' successfully retrieved from remote repository '"
  89. + remoteRepository.getId() + "'" );
  90. break;
  91. }
  92. }
  93. catch( Exception e )
  94. {
  95. log.warn( "An exception was caught while attempting to retrieve model '" + model.getAbsolutePath()
  96. + "' from remote repository '" + remoteRepository.getId() + "'.", e );
  97. continue;
  98. }
  99. }
  100. }
  101. return new FileModelSource( model );
  102. }
  103. public void addRepository( Repository repository )
  104. throws InvalidRepositoryException
  105. {
  106. // we just ignore repositories outside of the current one for now
  107. // TODO: it'd be nice to look them up from Archiva's set, but we want to do that by URL / mapping, not just the
  108. // ID since they will rarely match
  109. }
  110. public ModelResolver newCopy()
  111. {
  112. return new RepositoryModelResolver( basedir, pathTranslator );
  113. }
  114. // TODO: we need to do some refactoring, we cannot re-use the proxy components of archiva-proxy in maven2-repository
  115. // because it's causing a cyclic dependency
  116. private boolean getModelFromProxy( RemoteRepositoryConfiguration remoteRepository, String groupId,
  117. String artifactId, String version, String filename )
  118. throws AuthorizationException, TransferFailedException, ResourceDoesNotExistException, WagonFactoryException
  119. {
  120. boolean success = false;
  121. File tmpMd5 = null;
  122. File tmpSha1 = null;
  123. File tmpResource = null;
  124. String artifactPath = pathTranslator.toPath( groupId, artifactId, version, filename );
  125. File resource = new File( targetRepository.getLocation(), artifactPath );
  126. File workingDirectory = createWorkingDirectory( targetRepository.getLocation() );
  127. try
  128. {
  129. Wagon wagon = null;
  130. try
  131. {
  132. String protocol = getProtocol( remoteRepository.getUrl() );
  133. wagon = wagonFactory.getWagon( "wagon#" + protocol );
  134. if ( wagon == null )
  135. {
  136. throw new RuntimeException( "Unsupported remote repository protocol: " + protocol );
  137. }
  138. boolean connected = connectToRepository( wagon, remoteRepository );
  139. if ( connected )
  140. {
  141. tmpResource = new File( workingDirectory, filename );
  142. log.info( "Retrieving " + artifactPath + " from " + remoteRepository.getName() );
  143. wagon.get( artifactPath, tmpResource );
  144. log.debug( "Downloaded successfully." );
  145. tmpSha1 =
  146. transferChecksum( wagon, remoteRepository, artifactPath, tmpResource, workingDirectory, ".sha1" );
  147. tmpMd5 =
  148. transferChecksum( wagon, remoteRepository, artifactPath, tmpResource, workingDirectory, ".md5" );
  149. }
  150. }
  151. finally
  152. {
  153. if ( wagon != null )
  154. {
  155. try
  156. {
  157. wagon.disconnect();
  158. }
  159. catch ( ConnectionException e )
  160. {
  161. log.warn( "Unable to disconnect wagon.", e );
  162. }
  163. }
  164. }
  165. if ( resource != null )
  166. {
  167. synchronized ( resource.getAbsolutePath().intern() )
  168. {
  169. File directory = resource.getParentFile();
  170. moveFileIfExists( tmpMd5, directory );
  171. moveFileIfExists( tmpSha1, directory );
  172. moveFileIfExists( tmpResource, directory );
  173. success = true;
  174. }
  175. }
  176. }
  177. finally
  178. {
  179. FileUtils.deleteQuietly( workingDirectory );
  180. }
  181. // do we still need to execute the consumers?
  182. return success;
  183. }
  184. /**
  185. * Using wagon, connect to the remote repository.
  186. *
  187. * @param wagon the wagon instance to establish the connection on.
  188. * @return true if the connection was successful. false if not connected.
  189. */
  190. private boolean connectToRepository( Wagon wagon, RemoteRepositoryConfiguration remoteRepository )
  191. {
  192. boolean connected;
  193. final ProxyInfo networkProxy;
  194. networkProxy = this.networkProxyMap.get( remoteRepository.getId() );
  195. if ( networkProxy != null )
  196. {
  197. String msg =
  198. "Using network proxy " + networkProxy.getHost() + ":" + networkProxy.getPort()
  199. + " to connect to remote repository " + remoteRepository.getUrl();
  200. if ( networkProxy.getNonProxyHosts() != null )
  201. {
  202. msg += "; excluding hosts: " + networkProxy.getNonProxyHosts();
  203. }
  204. if ( StringUtils.isNotBlank( networkProxy.getUserName() ) )
  205. {
  206. msg += "; as user: " + networkProxy.getUserName();
  207. }
  208. log.debug( msg );
  209. }
  210. AuthenticationInfo authInfo = null;
  211. String username = remoteRepository.getUsername();
  212. String password = remoteRepository.getPassword();
  213. if ( StringUtils.isNotBlank( username ) && StringUtils.isNotBlank( password ) )
  214. {
  215. log.debug( "Using username " + username + " to connect to remote repository " + remoteRepository.getUrl() );
  216. authInfo = new AuthenticationInfo();
  217. authInfo.setUserName( username );
  218. authInfo.setPassword( password );
  219. }
  220. // Convert seconds to milliseconds
  221. int timeoutInMilliseconds = remoteRepository.getTimeout() * 1000;
  222. // Set timeout
  223. wagon.setTimeout( timeoutInMilliseconds );
  224. try
  225. {
  226. org.apache.maven.wagon.repository.Repository wagonRepository =
  227. new org.apache.maven.wagon.repository.Repository( remoteRepository.getId(), remoteRepository.getUrl() );
  228. wagon.connect( wagonRepository, authInfo, networkProxy );
  229. connected = true;
  230. }
  231. catch ( ConnectionException e )
  232. {
  233. log.error( "Could not connect to " + remoteRepository.getName() + ": " + e.getMessage() );
  234. connected = false;
  235. }
  236. catch ( AuthenticationException e )
  237. {
  238. log.error( "Could not connect to " + remoteRepository.getName() + ": " + e.getMessage() );
  239. connected = false;
  240. }
  241. return connected;
  242. }
  243. private File transferChecksum( Wagon wagon, RemoteRepositoryConfiguration remoteRepository, String remotePath,
  244. File resource, File tmpDirectory, String ext )
  245. throws AuthorizationException, TransferFailedException, ResourceDoesNotExistException
  246. {
  247. File destFile = new File( tmpDirectory, resource.getName() + ext );
  248. log.info( "Retrieving " + remotePath + " from " + remoteRepository.getName() );
  249. wagon.get( remotePath, destFile );
  250. log.debug( "Downloaded successfully." );
  251. return destFile;
  252. }
  253. private String getProtocol( String url )
  254. {
  255. String protocol = StringUtils.substringBefore( url, ":" );
  256. return protocol;
  257. }
  258. private File createWorkingDirectory( String targetRepository )
  259. {
  260. try
  261. {
  262. File tmpDir = File.createTempFile( ".workingdirectory", null, new File( targetRepository ) );
  263. tmpDir.delete();
  264. tmpDir.mkdirs();
  265. return tmpDir;
  266. }
  267. catch ( IOException e )
  268. {
  269. throw new RuntimeException( "Could not create working directory for this request", e );
  270. }
  271. }
  272. private void moveFileIfExists( File fileToMove, File directory )
  273. {
  274. if ( fileToMove != null && fileToMove.exists() )
  275. {
  276. File newLocation = new File( directory, fileToMove.getName() );
  277. if ( newLocation.exists() && !newLocation.delete() )
  278. {
  279. throw new RuntimeException( "Unable to overwrite existing target file: " + newLocation.getAbsolutePath() );
  280. }
  281. newLocation.getParentFile().mkdirs();
  282. if ( !fileToMove.renameTo( newLocation ) )
  283. {
  284. log.warn( "Unable to rename tmp file to its final name... resorting to copy command." );
  285. try
  286. {
  287. FileUtils.copyFile( fileToMove, newLocation );
  288. }
  289. catch ( IOException e )
  290. {
  291. if ( newLocation.exists() )
  292. {
  293. log.error( "Tried to copy file " + fileToMove.getName() + " to " + newLocation.getAbsolutePath()
  294. + " but file with this name already exists." );
  295. }
  296. else
  297. {
  298. throw new RuntimeException( "Cannot copy tmp file " + fileToMove.getAbsolutePath()
  299. + " to its final location", e );
  300. }
  301. }
  302. finally
  303. {
  304. FileUtils.deleteQuietly( fileToMove );
  305. }
  306. }
  307. }
  308. }
  309. }