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.

UploadAction.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. package org.apache.archiva.web.action;
  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 com.opensymphony.xwork2.Preparable;
  21. import com.opensymphony.xwork2.Validateable;
  22. import org.apache.archiva.admin.model.RepositoryAdminException;
  23. import org.apache.archiva.admin.model.admin.ArchivaAdministration;
  24. import org.apache.archiva.admin.model.beans.ManagedRepository;
  25. import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
  26. import org.apache.archiva.audit.AuditEvent;
  27. import org.apache.archiva.audit.Auditable;
  28. import org.apache.archiva.checksum.ChecksumAlgorithm;
  29. import org.apache.archiva.checksum.ChecksummedFile;
  30. import org.apache.archiva.scheduler.ArchivaTaskScheduler;
  31. import org.apache.archiva.scheduler.repository.RepositoryTask;
  32. import org.apache.archiva.security.AccessDeniedException;
  33. import org.apache.archiva.security.ArchivaSecurityException;
  34. import org.apache.archiva.security.PrincipalNotFoundException;
  35. import org.apache.archiva.security.UserRepositories;
  36. import org.apache.commons.io.FilenameUtils;
  37. import org.apache.commons.io.IOUtils;
  38. import org.apache.commons.lang.StringUtils;
  39. import org.apache.archiva.common.utils.VersionComparator;
  40. import org.apache.archiva.common.utils.VersionUtil;
  41. import org.apache.archiva.model.ArchivaRepositoryMetadata;
  42. import org.apache.archiva.model.ArtifactReference;
  43. import org.apache.archiva.model.SnapshotVersion;
  44. import org.apache.archiva.repository.ManagedRepositoryContent;
  45. import org.apache.archiva.repository.RepositoryContentFactory;
  46. import org.apache.archiva.repository.RepositoryException;
  47. import org.apache.archiva.repository.RepositoryNotFoundException;
  48. import org.apache.archiva.repository.metadata.MetadataTools;
  49. import org.apache.archiva.repository.metadata.RepositoryMetadataException;
  50. import org.apache.archiva.repository.metadata.RepositoryMetadataReader;
  51. import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
  52. import org.apache.maven.model.Model;
  53. import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
  54. import org.codehaus.plexus.taskqueue.TaskQueueException;
  55. import org.codehaus.plexus.util.IOUtil;
  56. import org.springframework.context.annotation.Scope;
  57. import org.springframework.stereotype.Controller;
  58. import javax.inject.Inject;
  59. import javax.inject.Named;
  60. import java.io.File;
  61. import java.io.FileInputStream;
  62. import java.io.FileOutputStream;
  63. import java.io.FileWriter;
  64. import java.io.IOException;
  65. import java.text.DateFormat;
  66. import java.text.SimpleDateFormat;
  67. import java.util.ArrayList;
  68. import java.util.Calendar;
  69. import java.util.Collections;
  70. import java.util.Date;
  71. import java.util.List;
  72. import java.util.TimeZone;
  73. /**
  74. * Upload an artifact using Jakarta file upload in webwork. If set by the user a pom will also be generated. Metadata
  75. * will also be updated if one exists, otherwise it would be created.
  76. */
  77. @SuppressWarnings( "serial" )
  78. @Controller( "uploadAction" )
  79. @Scope( "prototype" )
  80. public class UploadAction
  81. extends AbstractActionSupport
  82. implements Validateable, Preparable, Auditable
  83. {
  84. /**
  85. * The groupId of the artifact to be deployed.
  86. */
  87. private String groupId;
  88. /**
  89. * The artifactId of the artifact to be deployed.
  90. */
  91. private String artifactId;
  92. /**
  93. * The version of the artifact to be deployed.
  94. */
  95. private String version;
  96. /**
  97. * The packaging of the artifact to be deployed.
  98. */
  99. private String packaging;
  100. /**
  101. * The classifier of the artifact to be deployed.
  102. */
  103. private String classifier;
  104. /**
  105. * The temporary file representing the artifact to be deployed.
  106. */
  107. private File artifactFile;
  108. /**
  109. * The temporary file representing the pom to be deployed alongside the artifact.
  110. */
  111. private File pomFile;
  112. /**
  113. * The repository where the artifact is to be deployed.
  114. */
  115. private String repositoryId;
  116. /**
  117. * Flag whether to generate a pom for the artifact or not.
  118. */
  119. private boolean generatePom;
  120. /**
  121. * List of managed repositories to deploy to.
  122. */
  123. private List<String> managedRepoIdList;
  124. @Inject
  125. private ManagedRepositoryAdmin managedRepositoryAdmin;
  126. @Inject
  127. private UserRepositories userRepositories;
  128. @Inject
  129. private ArchivaAdministration archivaAdministration;
  130. @Inject
  131. private RepositoryContentFactory repositoryFactory;
  132. @Inject
  133. @Named( value = "archivaTaskScheduler#repository" )
  134. private ArchivaTaskScheduler scheduler;
  135. private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[]{ ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
  136. public void setArtifact( File file )
  137. {
  138. this.artifactFile = file;
  139. }
  140. public void setArtifactContentType( String contentType )
  141. {
  142. StringUtils.trim( contentType );
  143. }
  144. public void setArtifactFileName( String filename )
  145. {
  146. StringUtils.trim( filename );
  147. }
  148. public void setPom( File file )
  149. {
  150. this.pomFile = file;
  151. }
  152. public void setPomContentType( String contentType )
  153. {
  154. StringUtils.trim( contentType );
  155. }
  156. public void setPomFileName( String filename )
  157. {
  158. StringUtils.trim( filename );
  159. }
  160. public String getGroupId()
  161. {
  162. return groupId;
  163. }
  164. public void setGroupId( String groupId )
  165. {
  166. this.groupId = StringUtils.trim( groupId );
  167. }
  168. public String getArtifactId()
  169. {
  170. return artifactId;
  171. }
  172. public void setArtifactId( String artifactId )
  173. {
  174. this.artifactId = StringUtils.trim( artifactId );
  175. }
  176. public String getVersion()
  177. {
  178. return version;
  179. }
  180. public void setVersion( String version )
  181. {
  182. this.version = StringUtils.trim( version );
  183. }
  184. public String getPackaging()
  185. {
  186. return packaging;
  187. }
  188. public void setPackaging( String packaging )
  189. {
  190. this.packaging = StringUtils.trim( packaging );
  191. }
  192. public String getClassifier()
  193. {
  194. return classifier;
  195. }
  196. public void setClassifier( String classifier )
  197. {
  198. this.classifier = StringUtils.trim( classifier );
  199. }
  200. public String getRepositoryId()
  201. {
  202. return repositoryId;
  203. }
  204. public void setRepositoryId( String repositoryId )
  205. {
  206. this.repositoryId = repositoryId;
  207. }
  208. public boolean isGeneratePom()
  209. {
  210. return generatePom;
  211. }
  212. public void setGeneratePom( boolean generatePom )
  213. {
  214. this.generatePom = generatePom;
  215. }
  216. public List<String> getManagedRepoIdList()
  217. {
  218. return managedRepoIdList;
  219. }
  220. public void setManagedRepoIdList( List<String> managedRepoIdList )
  221. {
  222. this.managedRepoIdList = managedRepoIdList;
  223. }
  224. public void prepare()
  225. {
  226. managedRepoIdList = getManagableRepos();
  227. }
  228. public String input()
  229. {
  230. return INPUT;
  231. }
  232. private void reset()
  233. {
  234. // reset the fields so the form is clear when
  235. // the action returns to the jsp page
  236. groupId = "";
  237. artifactId = "";
  238. version = "";
  239. packaging = "";
  240. classifier = "";
  241. artifactFile = null;
  242. pomFile = null;
  243. repositoryId = "";
  244. generatePom = false;
  245. }
  246. public String doUpload()
  247. {
  248. try
  249. {
  250. ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository( repositoryId );
  251. ArtifactReference artifactReference = new ArtifactReference();
  252. artifactReference.setArtifactId( artifactId );
  253. artifactReference.setGroupId( groupId );
  254. artifactReference.setVersion( version );
  255. artifactReference.setClassifier( classifier );
  256. artifactReference.setType( packaging );
  257. ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
  258. String artifactPath = repository.toPath( artifactReference );
  259. int lastIndex = artifactPath.lastIndexOf( File.separatorChar );
  260. String path = artifactPath.substring( 0, lastIndex );
  261. File targetPath = new File( repoConfig.getLocation(), path );
  262. Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
  263. int newBuildNumber = -1;
  264. String timestamp = null;
  265. File versionMetadataFile = new File( targetPath, MetadataTools.MAVEN_METADATA );
  266. ArchivaRepositoryMetadata versionMetadata = getMetadata( versionMetadataFile );
  267. if ( VersionUtil.isSnapshot( version ) )
  268. {
  269. TimeZone timezone = TimeZone.getTimeZone( "UTC" );
  270. DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
  271. fmt.setTimeZone( timezone );
  272. timestamp = fmt.format( lastUpdatedTimestamp );
  273. if ( versionMetadata.getSnapshotVersion() != null )
  274. {
  275. newBuildNumber = versionMetadata.getSnapshotVersion().getBuildNumber() + 1;
  276. }
  277. else
  278. {
  279. newBuildNumber = 1;
  280. }
  281. }
  282. if ( !targetPath.exists() )
  283. {
  284. targetPath.mkdirs();
  285. }
  286. String filename = artifactPath.substring( lastIndex + 1 );
  287. if ( VersionUtil.isSnapshot( version ) )
  288. {
  289. filename = filename.replaceAll( "SNAPSHOT", timestamp + "-" + newBuildNumber );
  290. }
  291. boolean fixChecksums =
  292. !( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
  293. try
  294. {
  295. File targetFile = new File( targetPath, filename );
  296. if ( targetFile.exists() && !VersionUtil.isSnapshot( version ) && repoConfig.isBlockRedeployments() )
  297. {
  298. addActionError(
  299. "Overwriting released artifacts in repository '" + repoConfig.getId() + "' is not allowed." );
  300. return ERROR;
  301. }
  302. else
  303. {
  304. copyFile( artifactFile, targetPath, filename, fixChecksums );
  305. triggerAuditEvent( repository.getId(), path + "/" + filename, AuditEvent.UPLOAD_FILE );
  306. queueRepositoryTask( repository.getId(), targetFile );
  307. }
  308. }
  309. catch ( IOException ie )
  310. {
  311. addActionError( "Error encountered while uploading file: " + ie.getMessage() );
  312. return ERROR;
  313. }
  314. String pomFilename = filename;
  315. if ( classifier != null && !"".equals( classifier ) )
  316. {
  317. pomFilename = StringUtils.remove( pomFilename, "-" + classifier );
  318. }
  319. pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
  320. if ( generatePom )
  321. {
  322. try
  323. {
  324. File generatedPomFile = createPom( targetPath, pomFilename );
  325. triggerAuditEvent( repoConfig.getId(), path + "/" + pomFilename, AuditEvent.UPLOAD_FILE );
  326. if ( fixChecksums )
  327. {
  328. fixChecksums( generatedPomFile );
  329. }
  330. queueRepositoryTask( repoConfig.getId(), generatedPomFile );
  331. }
  332. catch ( IOException ie )
  333. {
  334. addActionError( "Error encountered while writing pom file: " + ie.getMessage() );
  335. return ERROR;
  336. }
  337. }
  338. if ( pomFile != null && pomFile.length() > 0 )
  339. {
  340. try
  341. {
  342. copyFile( pomFile, targetPath, pomFilename, fixChecksums );
  343. triggerAuditEvent( repoConfig.getId(), path + "/" + pomFilename, AuditEvent.UPLOAD_FILE );
  344. queueRepositoryTask( repoConfig.getId(), new File( targetPath, pomFilename ) );
  345. }
  346. catch ( IOException ie )
  347. {
  348. addActionError( "Error encountered while uploading pom file: " + ie.getMessage() );
  349. return ERROR;
  350. }
  351. }
  352. // explicitly update only if metadata-updater consumer is not enabled!
  353. if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
  354. {
  355. updateProjectMetadata( targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
  356. fixChecksums );
  357. if ( VersionUtil.isSnapshot( version ) )
  358. {
  359. updateVersionMetadata( versionMetadata, versionMetadataFile, lastUpdatedTimestamp, timestamp,
  360. newBuildNumber, fixChecksums );
  361. }
  362. }
  363. String msg = "Artifact \'" + groupId + ":" + artifactId + ":" + version
  364. + "\' was successfully deployed to repository \'" + repositoryId + "\'";
  365. addActionMessage( msg );
  366. reset();
  367. return SUCCESS;
  368. }
  369. catch ( RepositoryNotFoundException re )
  370. {
  371. addActionError( "Target repository cannot be found: " + re.getMessage() );
  372. return ERROR;
  373. }
  374. catch ( RepositoryException rep )
  375. {
  376. addActionError( "Repository exception: " + rep.getMessage() );
  377. return ERROR;
  378. }
  379. catch ( RepositoryAdminException e )
  380. {
  381. addActionError( "RepositoryAdmin exception: " + e.getMessage() );
  382. return ERROR;
  383. }
  384. }
  385. private void fixChecksums( File file )
  386. {
  387. ChecksummedFile checksum = new ChecksummedFile( file );
  388. checksum.fixChecksums( algorithms );
  389. }
  390. private void copyFile( File sourceFile, File targetPath, String targetFilename, boolean fixChecksums )
  391. throws IOException
  392. {
  393. FileOutputStream out = new FileOutputStream( new File( targetPath, targetFilename ) );
  394. FileInputStream input = new FileInputStream( sourceFile );
  395. try
  396. {
  397. IOUtils.copy( input, out );
  398. }
  399. finally
  400. {
  401. out.close();
  402. input.close();
  403. }
  404. if ( fixChecksums )
  405. {
  406. fixChecksums( new File( targetPath, targetFilename ) );
  407. }
  408. }
  409. private File createPom( File targetPath, String filename )
  410. throws IOException
  411. {
  412. Model projectModel = new Model();
  413. projectModel.setModelVersion( "4.0.0" );
  414. projectModel.setGroupId( groupId );
  415. projectModel.setArtifactId( artifactId );
  416. projectModel.setVersion( version );
  417. projectModel.setPackaging( packaging );
  418. File pomFile = new File( targetPath, filename );
  419. MavenXpp3Writer writer = new MavenXpp3Writer();
  420. FileWriter w = new FileWriter( pomFile );
  421. try
  422. {
  423. writer.write( w, projectModel );
  424. }
  425. finally
  426. {
  427. IOUtil.close( w );
  428. }
  429. return pomFile;
  430. }
  431. private ArchivaRepositoryMetadata getMetadata( File metadataFile )
  432. throws RepositoryMetadataException
  433. {
  434. ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
  435. if ( metadataFile.exists() )
  436. {
  437. metadata = RepositoryMetadataReader.read( metadataFile );
  438. }
  439. return metadata;
  440. }
  441. /**
  442. * Update version level metadata for snapshot artifacts. If it does not exist, create the metadata and fix checksums
  443. * if necessary.
  444. */
  445. private void updateVersionMetadata( ArchivaRepositoryMetadata metadata, File metadataFile,
  446. Date lastUpdatedTimestamp, String timestamp, int buildNumber,
  447. boolean fixChecksums )
  448. throws RepositoryMetadataException
  449. {
  450. if ( !metadataFile.exists() )
  451. {
  452. metadata.setGroupId( groupId );
  453. metadata.setArtifactId( artifactId );
  454. metadata.setVersion( version );
  455. }
  456. if ( metadata.getSnapshotVersion() == null )
  457. {
  458. metadata.setSnapshotVersion( new SnapshotVersion() );
  459. }
  460. metadata.getSnapshotVersion().setBuildNumber( buildNumber );
  461. metadata.getSnapshotVersion().setTimestamp( timestamp );
  462. metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
  463. RepositoryMetadataWriter.write( metadata, metadataFile );
  464. if ( fixChecksums )
  465. {
  466. fixChecksums( metadataFile );
  467. }
  468. }
  469. /**
  470. * Update artifact level metadata. If it does not exist, create the metadata and fix checksums if necessary.
  471. */
  472. private void updateProjectMetadata( String targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
  473. boolean fixChecksums )
  474. throws RepositoryMetadataException
  475. {
  476. List<String> availableVersions = new ArrayList<String>();
  477. String latestVersion = version;
  478. File projectDir = new File( targetPath ).getParentFile();
  479. File projectMetadataFile = new File( projectDir, MetadataTools.MAVEN_METADATA );
  480. ArchivaRepositoryMetadata projectMetadata = getMetadata( projectMetadataFile );
  481. if ( projectMetadataFile.exists() )
  482. {
  483. availableVersions = projectMetadata.getAvailableVersions();
  484. Collections.sort( availableVersions, VersionComparator.getInstance() );
  485. if ( !availableVersions.contains( version ) )
  486. {
  487. availableVersions.add( version );
  488. }
  489. latestVersion = availableVersions.get( availableVersions.size() - 1 );
  490. }
  491. else
  492. {
  493. availableVersions.add( version );
  494. projectMetadata.setGroupId( groupId );
  495. projectMetadata.setArtifactId( artifactId );
  496. }
  497. if ( projectMetadata.getGroupId() == null )
  498. {
  499. projectMetadata.setGroupId( groupId );
  500. }
  501. if ( projectMetadata.getArtifactId() == null )
  502. {
  503. projectMetadata.setArtifactId( artifactId );
  504. }
  505. projectMetadata.setLatestVersion( latestVersion );
  506. projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
  507. projectMetadata.setAvailableVersions( availableVersions );
  508. if ( !VersionUtil.isSnapshot( version ) )
  509. {
  510. projectMetadata.setReleasedVersion( latestVersion );
  511. }
  512. RepositoryMetadataWriter.write( projectMetadata, projectMetadataFile );
  513. if ( fixChecksums )
  514. {
  515. fixChecksums( projectMetadataFile );
  516. }
  517. }
  518. public void validate()
  519. {
  520. try
  521. {
  522. // is this enough check for the repository permission?
  523. if ( !userRepositories.isAuthorizedToUploadArtifacts( getPrincipal(), repositoryId ) )
  524. {
  525. addActionError( "User is not authorized to upload in repository " + repositoryId );
  526. }
  527. if ( artifactFile == null || artifactFile.length() == 0 )
  528. {
  529. addActionError( "Please add a file to upload." );
  530. }
  531. if ( version == null || !VersionUtil.isVersion( version ) )
  532. {
  533. addActionError( "Invalid version." );
  534. }
  535. }
  536. catch ( PrincipalNotFoundException pe )
  537. {
  538. addActionError( pe.getMessage() );
  539. }
  540. catch ( ArchivaSecurityException ae )
  541. {
  542. addActionError( ae.getMessage() );
  543. }
  544. }
  545. private List<String> getManagableRepos()
  546. {
  547. try
  548. {
  549. return userRepositories.getManagableRepositoryIds( getPrincipal() );
  550. }
  551. catch ( PrincipalNotFoundException e )
  552. {
  553. log.warn( e.getMessage(), e );
  554. }
  555. catch ( AccessDeniedException e )
  556. {
  557. log.warn( e.getMessage(), e );
  558. // TODO: pass this onto the screen.
  559. }
  560. catch ( ArchivaSecurityException e )
  561. {
  562. log.warn( e.getMessage(), e );
  563. }
  564. return Collections.emptyList();
  565. }
  566. private void queueRepositoryTask( String repositoryId, File localFile )
  567. {
  568. RepositoryTask task = new RepositoryTask();
  569. task.setRepositoryId( repositoryId );
  570. task.setResourceFile( localFile );
  571. task.setUpdateRelatedArtifacts( true );
  572. task.setScanAll( false );
  573. try
  574. {
  575. scheduler.queueTask( task );
  576. }
  577. catch ( TaskQueueException e )
  578. {
  579. log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()
  580. + "']." );
  581. }
  582. }
  583. public void setScheduler( ArchivaTaskScheduler scheduler )
  584. {
  585. this.scheduler = scheduler;
  586. }
  587. public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
  588. {
  589. this.repositoryFactory = repositoryFactory;
  590. }
  591. public ManagedRepositoryAdmin getManagedRepositoryAdmin()
  592. {
  593. return managedRepositoryAdmin;
  594. }
  595. public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
  596. {
  597. this.managedRepositoryAdmin = managedRepositoryAdmin;
  598. }
  599. public ArchivaAdministration getArchivaAdministration()
  600. {
  601. return archivaAdministration;
  602. }
  603. public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
  604. {
  605. this.archivaAdministration = archivaAdministration;
  606. }
  607. }