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.AuditListener;
52 import org.apache.maven.archiva.repository.audit.Auditable;
53 import org.apache.maven.archiva.repository.metadata.MetadataTools;
54 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
55 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
56 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
57 import org.apache.maven.archiva.repository.project.ProjectModelException;
58 import org.apache.maven.archiva.repository.project.ProjectModelWriter;
59 import org.apache.maven.archiva.repository.project.writers.ProjectModel400Writer;
60 import org.apache.maven.archiva.security.ArchivaSecurityException;
61 import org.apache.maven.archiva.security.PrincipalNotFoundException;
62 import org.apache.maven.archiva.security.UserRepositories;
63 import org.apache.maven.archiva.security.ArchivaXworkUser;
65 import org.apache.struts2.ServletActionContext;
66 import com.opensymphony.xwork2.ActionContext;
67 import com.opensymphony.xwork2.Preparable;
68 import com.opensymphony.xwork2.Validateable;
69 import org.apache.commons.io.FilenameUtils;
70 import org.apache.commons.lang.StringUtils;
73 * Upload an artifact using Jakarta file upload in webwork. If set by the user a pom will also be generated. Metadata
74 * will also be updated if one exists, otherwise it would be created.
76 * @plexus.component role="com.opensymphony.xwork2.Action" role-hint="uploadAction"
78 public class UploadAction
79 extends PlexusActionSupport
80 implements Validateable, Preparable, Auditable
85 private RepositoryContentConsumers consumers;
90 private ArchivaXworkUser archivaXworkUser;
93 * The groupId of the artifact to be deployed.
95 private String groupId;
98 * The artifactId of the artifact to be deployed.
100 private String artifactId;
103 * The version of the artifact to be deployed.
105 private String version;
108 * The packaging of the artifact to be deployed.
110 private String packaging;
113 * The classifier of the artifact to be deployed.
115 private String classifier;
118 * The temporary file representing the artifact to be deployed.
120 private File artifactFile;
123 * The content type of the artifact to be deployed.
125 private String artifactContentType;
128 * The original filename of the uploaded artifact file.
130 private String artifactFilename;
133 * The temporary file representing the pom to be deployed alongside the artifact.
135 private File pomFile;
138 * The content type of the pom file.
140 private String pomContentType;
143 * The original filename of the uploaded pom file.
145 private String pomFilename;
148 * The repository where the artifact is to be deployed.
150 private String repositoryId;
153 * Flag whether to generate a pom for the artifact or not.
155 private boolean generatePom;
158 * List of managed repositories to deploy to.
160 private List<String> managedRepoIdList;
163 * @plexus.requirement
165 private UserRepositories userRepositories;
168 * @plexus.requirement role-hint="default"
170 private ArchivaConfiguration configuration;
173 * @plexus.requirement
175 private RepositoryContentFactory repositoryFactory;
178 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
180 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
182 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[] { ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
184 private ProjectModelWriter pomWriter = new ProjectModel400Writer();
186 public void setArtifact( File file )
188 this.artifactFile = file;
191 public void setArtifactContentType( String contentType )
193 this.artifactContentType = contentType;
196 public void setArtifactFileName( String filename )
198 this.artifactFilename = filename;
201 public void setPom( File file )
206 public void setPomContentType( String contentType )
208 this.pomContentType = contentType;
211 public void setPomFileName( String filename )
213 this.pomFilename = filename;
216 public String getGroupId()
221 public void setGroupId( String groupId )
223 this.groupId = groupId;
226 public String getArtifactId()
231 public void setArtifactId( String artifactId )
233 this.artifactId = artifactId;
236 public String getVersion()
241 public void setVersion( String version )
243 this.version = version;
246 public String getPackaging()
251 public void setPackaging( String packaging )
253 this.packaging = packaging;
256 public String getClassifier()
261 public void setClassifier( String classifier )
263 this.classifier = classifier;
266 public String getRepositoryId()
271 public void setRepositoryId( String repositoryId )
273 this.repositoryId = repositoryId;
276 public boolean isGeneratePom()
281 public void setGeneratePom( boolean generatePom )
283 this.generatePom = generatePom;
286 public List<String> getManagedRepoIdList()
288 return managedRepoIdList;
291 public void setManagedRepoIdList( List<String> managedRepoIdList )
293 this.managedRepoIdList = managedRepoIdList;
296 public void prepare()
299 new ArrayList<String>( configuration.getConfiguration().getManagedRepositoriesAsMap().keySet() );
302 public String input()
309 // reset the fields so the form is clear when
310 // the action returns to the jsp page
317 artifactContentType = "";
318 artifactFilename = "";
326 public String doUpload()
330 ManagedRepositoryConfiguration repoConfig =
331 configuration.getConfiguration().findManagedRepositoryById( repositoryId );
333 ArtifactReference artifactReference = new ArtifactReference();
334 artifactReference.setArtifactId( artifactId );
335 artifactReference.setGroupId( groupId );
336 artifactReference.setVersion( version );
337 artifactReference.setClassifier( classifier );
338 artifactReference.setType( packaging );
340 ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent( repositoryId );
342 String artifactPath = repository.toPath( artifactReference );
344 int lastIndex = artifactPath.lastIndexOf( '/' );
346 File targetPath = new File( repoConfig.getLocation(), artifactPath.substring( 0, lastIndex ) );
348 Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
349 int newBuildNumber = -1;
350 String timestamp = null;
352 File metadataFile = getMetadata( targetPath.getAbsolutePath() );
353 ArchivaRepositoryMetadata metadata = getMetadata( metadataFile );
355 if (VersionUtil.isSnapshot(version))
357 TimeZone timezone = TimeZone.getTimeZone( "UTC" );
358 DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
359 fmt.setTimeZone( timezone );
360 timestamp = fmt.format( lastUpdatedTimestamp );
361 if ( metadata.getSnapshotVersion() != null )
363 newBuildNumber = metadata.getSnapshotVersion().getBuildNumber() + 1;
367 metadata.setSnapshotVersion( new SnapshotVersion() );
372 if ( !targetPath.exists() )
377 String filename = artifactPath.substring( lastIndex + 1 );
378 if ( VersionUtil.isSnapshot( version ) )
380 filename = filename.replaceAll( "SNAPSHOT", timestamp + "-" + newBuildNumber );
385 copyFile( artifactFile, targetPath, filename );
386 consumers.executeConsumers( repoConfig, repository.toFile( artifactReference ) );
388 catch ( IOException ie )
390 addActionError( "Error encountered while uploading file: " + ie.getMessage() );
394 String pomFilename = filename;
395 if( classifier != null && !"".equals( classifier ) )
397 pomFilename = StringUtils.remove( pomFilename, "-" + classifier );
399 pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
405 File generatedPomFile = createPom( targetPath, pomFilename );
406 consumers.executeConsumers( repoConfig, generatedPomFile );
408 catch ( IOException ie )
410 addActionError( "Error encountered while writing pom file: " + ie.getMessage() );
413 catch ( ProjectModelException pe )
415 addActionError( "Error encountered while generating pom file: " + pe.getMessage() );
420 if ( pomFile != null && pomFile.length() > 0 )
424 copyFile( pomFile, targetPath, pomFilename );
425 consumers.executeConsumers( repoConfig, new File( targetPath, pomFilename ) );
427 catch ( IOException ie )
429 addActionError( "Error encountered while uploading pom file: " + ie.getMessage() );
435 updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, timestamp, newBuildNumber );
437 String msg = "Artifact \'" + groupId + ":" + artifactId + ":" + version +
438 "\' was successfully deployed to repository \'" + repositoryId + "\'";
440 triggerAuditEvent( getPrincipal(), repositoryId, groupId + ":" + artifactId + ":" + version, AuditEvent.UPLOAD_FILE );
442 addActionMessage( msg );
447 catch ( RepositoryNotFoundException re )
449 addActionError( "Target repository cannot be found: " + re.getMessage() );
452 catch ( RepositoryException rep )
454 addActionError( "Repository exception: " + rep.getMessage() );
459 private String getPrincipal()
461 return archivaXworkUser.getActivePrincipal( ActionContext.getContext().getSession() );
464 private void copyFile( File sourceFile, File targetPath, String targetFilename )
467 FileOutputStream out = new FileOutputStream( new File( targetPath, targetFilename ) );
471 FileInputStream input = new FileInputStream( sourceFile );
473 while ( ( i = input.read() ) != -1 )
485 private File createPom( File targetPath, String filename )
486 throws IOException, ProjectModelException
488 ArchivaProjectModel projectModel = new ArchivaProjectModel();
489 projectModel.setGroupId( groupId );
490 projectModel.setArtifactId( artifactId );
491 projectModel.setVersion( version );
492 projectModel.setPackaging( packaging );
494 File pomFile = new File( targetPath, filename);
495 pomWriter.write( projectModel, pomFile );
500 private File getMetadata( String targetPath )
502 String artifactPath = targetPath.substring( 0, targetPath.lastIndexOf( File.separatorChar ) );
504 return new File( artifactPath, MetadataTools.MAVEN_METADATA );
507 private ArchivaRepositoryMetadata getMetadata( File metadataFile )
508 throws RepositoryMetadataException
510 ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
511 if ( metadataFile.exists() )
513 metadata = RepositoryMetadataReader.read( metadataFile );
519 * Update artifact level metadata. If it does not exist, create the metadata.
523 private void updateMetadata( ArchivaRepositoryMetadata metadata, File metadataFile, Date lastUpdatedTimestamp,
524 String timestamp, int buildNumber )
525 throws RepositoryMetadataException
527 List<String> availableVersions = new ArrayList<String>();
528 String latestVersion = version;
530 if ( metadataFile.exists() )
532 availableVersions = metadata.getAvailableVersions();
534 Collections.sort( availableVersions, VersionComparator.getInstance() );
536 if ( !availableVersions.contains( version ) )
538 availableVersions.add( version );
541 latestVersion = availableVersions.get( availableVersions.size() - 1 );
545 availableVersions.add( version );
547 metadata.setGroupId( groupId );
548 metadata.setArtifactId( artifactId );
551 if ( metadata.getGroupId() == null )
553 metadata.setGroupId( groupId );
555 if ( metadata.getArtifactId() == null )
557 metadata.setArtifactId( artifactId );
560 metadata.setLatestVersion( latestVersion );
561 metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
562 metadata.setAvailableVersions( availableVersions );
564 if ( !VersionUtil.isSnapshot( version ) )
566 metadata.setReleasedVersion( latestVersion );
570 metadata.getSnapshotVersion().setBuildNumber( buildNumber );
572 metadata.getSnapshotVersion().setTimestamp( timestamp );
575 RepositoryMetadataWriter.write( metadata, metadataFile );
576 ChecksummedFile checksum = new ChecksummedFile( metadataFile );
577 checksum.fixChecksums( algorithms );
580 public void validate()
584 // is this enough check for the repository permission?
585 if ( !userRepositories.isAuthorizedToUploadArtifacts( getPrincipal(), repositoryId ) )
587 addActionError( "User is not authorized to upload in repository " + repositoryId );
590 if ( artifactFile == null || artifactFile.length() == 0 )
592 addActionError( "Please add a file to upload." );
595 if ( !VersionUtil.isVersion( version ) )
597 addActionError( "Invalid version." );
600 catch ( PrincipalNotFoundException pe )
602 addActionError( pe.getMessage() );
604 catch ( ArchivaSecurityException ae )
606 addActionError( ae.getMessage() );
610 public void addAuditListener( AuditListener listener )
612 this.auditListeners.add( listener );
615 public void clearAuditListeners()
617 this.auditListeners.clear();
620 public void removeAuditListener( AuditListener listener )
622 this.auditListeners.remove( listener );
625 private void triggerAuditEvent( String user, String repositoryId, String resource, String action )
627 AuditEvent event = new AuditEvent( repositoryId, user, resource, action );
628 event.setRemoteIP( ServletActionContext.getRequest().getRemoteAddr() );
630 for ( AuditListener listener : auditListeners )
632 listener.auditEvent( event );