1 package org.apache.maven.archiva.web.action;
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
23 import java.io.FileInputStream;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.text.DateFormat;
27 import java.text.SimpleDateFormat;
28 import java.util.ArrayList;
29 import java.util.Calendar;
30 import java.util.Date;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.TimeZone;
35 import org.apache.archiva.checksum.ChecksumAlgorithm;
36 import org.apache.archiva.checksum.ChecksummedFile;
37 import org.apache.maven.archiva.common.utils.VersionComparator;
38 import org.apache.maven.archiva.common.utils.VersionUtil;
39 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
40 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
41 import org.apache.maven.archiva.model.ArchivaProjectModel;
42 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
43 import org.apache.maven.archiva.model.ArtifactReference;
44 import org.apache.maven.archiva.model.SnapshotVersion;
45 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
46 import org.apache.maven.archiva.repository.RepositoryContentFactory;
47 import org.apache.maven.archiva.repository.RepositoryException;
48 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
49 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
50 import org.apache.maven.archiva.repository.audit.AuditEvent;
51 import org.apache.maven.archiva.repository.audit.Auditable;
52 import org.apache.maven.archiva.repository.metadata.MetadataTools;
53 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
54 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
55 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
56 import org.apache.maven.archiva.repository.project.ProjectModelException;
57 import org.apache.maven.archiva.repository.project.ProjectModelWriter;
58 import org.apache.maven.archiva.repository.project.writers.ProjectModel400Writer;
59 import org.apache.maven.archiva.security.AccessDeniedException;
60 import org.apache.maven.archiva.security.ArchivaSecurityException;
61 import org.apache.maven.archiva.security.PrincipalNotFoundException;
62 import org.apache.maven.archiva.security.UserRepositories;
64 import com.opensymphony.xwork2.Preparable;
65 import com.opensymphony.xwork2.Validateable;
66 import org.apache.commons.io.FilenameUtils;
67 import org.apache.commons.lang.StringUtils;
70 * Upload an artifact using Jakarta file upload in webwork. If set by the user a pom will also be generated. Metadata
71 * will also be updated if one exists, otherwise it would be created.
73 * @plexus.component role="com.opensymphony.xwork2.Action" role-hint="uploadAction" instantiation-strategy="per-lookup"
75 public class UploadAction
76 extends PlexusActionSupport
77 implements Validateable, Preparable, Auditable
82 private RepositoryContentConsumers consumers;
85 * The groupId of the artifact to be deployed.
87 private String groupId;
90 * The artifactId of the artifact to be deployed.
92 private String artifactId;
95 * The version of the artifact to be deployed.
97 private String version;
100 * The packaging of the artifact to be deployed.
102 private String packaging;
105 * The classifier of the artifact to be deployed.
107 private String classifier;
110 * The temporary file representing the artifact to be deployed.
112 private File artifactFile;
115 * The temporary file representing the pom to be deployed alongside the artifact.
117 private File pomFile;
120 * The repository where the artifact is to be deployed.
122 private String repositoryId;
125 * Flag whether to generate a pom for the artifact or not.
127 private boolean generatePom;
130 * List of managed repositories to deploy to.
132 private List<String> managedRepoIdList;
135 * @plexus.requirement
137 private UserRepositories userRepositories;
140 * @plexus.requirement role-hint="default"
142 private ArchivaConfiguration configuration;
145 * @plexus.requirement
147 private RepositoryContentFactory repositoryFactory;
149 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[] { ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
151 private ProjectModelWriter pomWriter = new ProjectModel400Writer();
153 public void setArtifact( File file )
155 this.artifactFile = file;
158 public void setArtifactContentType( String contentType )
160 StringUtils.trim( contentType );
163 public void setArtifactFileName( String filename )
165 StringUtils.trim( filename );
168 public void setPom( File file )
173 public void setPomContentType( String contentType )
175 StringUtils.trim( contentType );
178 public void setPomFileName( String filename )
180 StringUtils.trim( filename );
183 public String getGroupId()
188 public void setGroupId( String groupId )
190 this.groupId = StringUtils.trim( groupId );
193 public String getArtifactId()
198 public void setArtifactId( String artifactId )
200 this.artifactId = StringUtils.trim( artifactId );
203 public String getVersion()
208 public void setVersion( String version )
210 this.version = StringUtils.trim( version );
213 public String getPackaging()
218 public void setPackaging( String packaging )
220 this.packaging = StringUtils.trim( packaging );
223 public String getClassifier()
228 public void setClassifier( String classifier )
230 this.classifier = StringUtils.trim( classifier );
233 public String getRepositoryId()
238 public void setRepositoryId( String repositoryId )
240 this.repositoryId = repositoryId;
243 public boolean isGeneratePom()
248 public void setGeneratePom( boolean generatePom )
250 this.generatePom = generatePom;
253 public List<String> getManagedRepoIdList()
255 return managedRepoIdList;
258 public void setManagedRepoIdList( List<String> managedRepoIdList )
260 this.managedRepoIdList = managedRepoIdList;
263 public void prepare()
265 managedRepoIdList = getManagableRepos();
268 public String input()
275 // reset the fields so the form is clear when
276 // the action returns to the jsp page
288 public String doUpload()
292 ManagedRepositoryConfiguration repoConfig =
293 configuration.getConfiguration().findManagedRepositoryById( repositoryId );
295 ArtifactReference artifactReference = new ArtifactReference();
296 artifactReference.setArtifactId( artifactId );
297 artifactReference.setGroupId( groupId );
298 artifactReference.setVersion( version );
299 artifactReference.setClassifier( classifier );
300 artifactReference.setType( packaging );
302 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
304 String artifactPath = repository.toPath( artifactReference );
306 int lastIndex = artifactPath.lastIndexOf( '/' );
308 File targetPath = new File( repoConfig.getLocation(), artifactPath.substring( 0, lastIndex ) );
310 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
311 int newBuildNumber = -1;
312 String timestamp = null;
314 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
315 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
317 if (VersionUtil.isSnapshot(version))
319 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
320 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
321 fmt.setTimeZone( timezone );
322 timestamp = fmt.format( lastUpdatedTimestamp );
323 if ( metadata.getSnapshotVersion() != null )
325 newBuildNumber = metadata.getSnapshotVersion().getBuildNumber() + 1;
329 metadata.setSnapshotVersion( new SnapshotVersion() );
334 if ( !targetPath.exists() )
339 String filename = artifactPath.substring( lastIndex + 1 );
340 if ( VersionUtil.isSnapshot( version ) )
342 filename = filename.replaceAll( "SNAPSHOT", timestamp + "-" + newBuildNumber );
347 copyFile( artifactFile, targetPath, filename );
348 consumers.executeConsumers( repoConfig, repository.toFile( artifactReference ) );
350 catch ( IOException ie )
352 addActionError( "Error encountered while uploading file: " + ie.getMessage() );
356 String pomFilename = filename;
357 if( classifier != null && !"".equals( classifier ) )
359 pomFilename = StringUtils.remove( pomFilename, "-" + classifier );
361 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
367 File generatedPomFile = createPom( targetPath, pomFilename );
368 consumers.executeConsumers( repoConfig, generatedPomFile );
370 catch ( IOException ie )
372 addActionError( "Error encountered while writing pom file: " + ie.getMessage() );
375 catch ( ProjectModelException pe )
377 addActionError( "Error encountered while generating pom file: " + pe.getMessage() );
382 if ( pomFile != null && pomFile.length() > 0 )
386 copyFile( pomFile, targetPath, pomFilename );
387 consumers.executeConsumers( repoConfig, new File( targetPath, pomFilename ) );
389 catch ( IOException ie )
391 addActionError( "Error encountered while uploading pom file: " + ie.getMessage() );
397 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, timestamp, newBuildNumber );
399 String msg = "Artifact \'" + groupId + ":" + artifactId + ":" + version +
400 "\' was successfully deployed to repository \'" + repositoryId + "\'";
402 triggerAuditEvent( repositoryId, groupId + ":" + artifactId + ":" + version, AuditEvent.UPLOAD_FILE );
404 addActionMessage( msg );
409 catch ( RepositoryNotFoundException re )
411 addActionError( "Target repository cannot be found: " + re.getMessage() );
414 catch ( RepositoryException rep )
416 addActionError( "Repository exception: " + rep.getMessage() );
421 private void copyFile( File sourceFile, File targetPath, String targetFilename )
424 FileOutputStream out = new FileOutputStream( new File( targetPath, targetFilename ) );
428 FileInputStream input = new FileInputStream( sourceFile );
430 while ( ( i = input.read() ) != -1 )
442 private File createPom( File targetPath, String filename )
443 throws IOException, ProjectModelException
445 ArchivaProjectModel projectModel = new ArchivaProjectModel();
446 projectModel.setGroupId( groupId );
447 projectModel.setArtifactId( artifactId );
448 projectModel.setVersion( version );
449 projectModel.setPackaging( packaging );
451 File pomFile = new File( targetPath, filename);
452 pomWriter.write( projectModel, pomFile );
457 private File getMetadata( String targetPath )
459 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
461 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
464 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
465 throws RepositoryMetadataException
467 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
468 if ( metadataFile.exists() )
470 metadata = RepositoryMetadataReader.read( metadataFile );
476 * Update artifact level metadata. If it does not exist, create the metadata.
480 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
481 String timestamp, int buildNumber )
482 throws RepositoryMetadataException
484 List<String> availableVersions = new ArrayList<String>();
485 String latestVersion = version;
487 if ( metadataFile.exists() )
489 availableVersions = metadata.getAvailableVersions();
491 Collections.sort( availableVersions, VersionComparator.getInstance() );
493 if ( !availableVersions.contains( version ) )
495 availableVersions.add( version );
498 latestVersion = availableVersions.get( availableVersions.size() - 1 );
502 availableVersions.add( version );
504 metadata.setGroupId( groupId );
505 metadata.setArtifactId( artifactId );
508 if ( metadata.getGroupId() == null )
510 metadata.setGroupId( groupId );
512 if ( metadata.getArtifactId() == null )
514 metadata.setArtifactId( artifactId );
517 metadata.setLatestVersion( latestVersion );
518 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
519 metadata.setAvailableVersions( availableVersions );
521 if ( !VersionUtil.isSnapshot( version ) )
523 metadata.setReleasedVersion( latestVersion );
527 metadata.getSnapshotVersion().setBuildNumber( buildNumber );
529 metadata.getSnapshotVersion().setTimestamp( timestamp );
532 RepositoryMetadataWriter.write( metadata, metadataFile );
533 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
534 checksum.fixChecksums( algorithms );
537 public void validate()
541 // is this enough check for the repository permission?
542 if ( !userRepositories.isAuthorizedToUploadArtifacts( getPrincipal(), repositoryId ) )
544 addActionError( "User is not authorized to upload in repository " + repositoryId );
547 if ( artifactFile == null || artifactFile.length() == 0 )
549 addActionError( "Please add a file to upload." );
552 if ( !VersionUtil.isVersion( version ) )
554 addActionError( "Invalid version." );
557 catch ( PrincipalNotFoundException pe )
559 addActionError( pe.getMessage() );
561 catch ( ArchivaSecurityException ae )
563 addActionError( ae.getMessage() );
567 private List<String> getManagableRepos()
571 return userRepositories.getManagableRepositoryIds( getPrincipal() );
573 catch ( PrincipalNotFoundException e )
575 log.warn( e.getMessage(), e );
577 catch ( AccessDeniedException e )
579 log.warn( e.getMessage(), e );
580 // TODO: pass this onto the screen.
582 catch ( ArchivaSecurityException e )
584 log.warn( e.getMessage(), e );
586 return Collections.emptyList();