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.AccessDeniedException;
61 import org.apache.maven.archiva.security.ArchivaSecurityException;
62 import org.apache.maven.archiva.security.PrincipalNotFoundException;
63 import org.apache.maven.archiva.security.UserRepositories;
64 import org.apache.maven.archiva.security.ArchivaXworkUser;
66 import org.apache.struts2.ServletActionContext;
67 import com.opensymphony.xwork2.ActionContext;
68 import com.opensymphony.xwork2.Preparable;
69 import com.opensymphony.xwork2.Validateable;
70 import org.apache.commons.io.FilenameUtils;
71 import org.apache.commons.lang.StringUtils;
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.
77 * @plexus.component role="com.opensymphony.xwork2.Action" role-hint="uploadAction" instantiation-strategy="per-lookup"
79 public class UploadAction
80 extends PlexusActionSupport
81 implements Validateable, Preparable, Auditable
86 private RepositoryContentConsumers consumers;
91 private ArchivaXworkUser archivaXworkUser;
94 * The groupId of the artifact to be deployed.
96 private String groupId;
99 * The artifactId of the artifact to be deployed.
101 private String artifactId;
104 * The version of the artifact to be deployed.
106 private String version;
109 * The packaging of the artifact to be deployed.
111 private String packaging;
114 * The classifier of the artifact to be deployed.
116 private String classifier;
119 * The temporary file representing the artifact to be deployed.
121 private File artifactFile;
124 * The content type of the artifact to be deployed.
126 private String artifactContentType;
129 * The original filename of the uploaded artifact file.
131 private String artifactFilename;
134 * The temporary file representing the pom to be deployed alongside the artifact.
136 private File pomFile;
139 * The content type of the pom file.
141 private String pomContentType;
144 * The original filename of the uploaded pom file.
146 private String pomFilename;
149 * The repository where the artifact is to be deployed.
151 private String repositoryId;
154 * Flag whether to generate a pom for the artifact or not.
156 private boolean generatePom;
159 * List of managed repositories to deploy to.
161 private List<String> managedRepoIdList;
164 * @plexus.requirement
166 private UserRepositories userRepositories;
169 * @plexus.requirement role-hint="default"
171 private ArchivaConfiguration configuration;
174 * @plexus.requirement
176 private RepositoryContentFactory repositoryFactory;
179 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
181 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
183 private ChecksumAlgorithm[] algorithms = new ChecksumAlgorithm[] { ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 };
185 private ProjectModelWriter pomWriter = new ProjectModel400Writer();
187 public void setArtifact( File file )
189 this.artifactFile = file;
192 public void setArtifactContentType( String contentType )
194 this.artifactContentType = StringUtils.trim( contentType );
197 public void setArtifactFileName( String filename )
199 this.artifactFilename = StringUtils.trim( filename );
202 public void setPom( File file )
207 public void setPomContentType( String contentType )
209 this.pomContentType = StringUtils.trim( contentType );
212 public void setPomFileName( String filename )
214 this.pomFilename = StringUtils.trim( filename );
217 public String getGroupId()
222 public void setGroupId( String groupId )
224 this.groupId = StringUtils.trim( groupId );
227 public String getArtifactId()
232 public void setArtifactId( String artifactId )
234 this.artifactId = StringUtils.trim( artifactId );
237 public String getVersion()
242 public void setVersion( String version )
244 this.version = StringUtils.trim( version );
247 public String getPackaging()
252 public void setPackaging( String packaging )
254 this.packaging = StringUtils.trim( packaging );
257 public String getClassifier()
262 public void setClassifier( String classifier )
264 this.classifier = StringUtils.trim( classifier );
267 public String getRepositoryId()
272 public void setRepositoryId( String repositoryId )
274 this.repositoryId = repositoryId;
277 public boolean isGeneratePom()
282 public void setGeneratePom( boolean generatePom )
284 this.generatePom = generatePom;
287 public List<String> getManagedRepoIdList()
289 return managedRepoIdList;
292 public void setManagedRepoIdList( List<String> managedRepoIdList )
294 this.managedRepoIdList = managedRepoIdList;
297 public void prepare()
299 managedRepoIdList = getManagableRepos();
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 List<String> getManagableRepos()
629 return userRepositories.getManagableRepositoryIds( getPrincipal() );
631 catch ( PrincipalNotFoundException e )
633 log.warn( e.getMessage(), e );
635 catch ( AccessDeniedException e )
637 log.warn( e.getMessage(), e );
638 // TODO: pass this onto the screen.
640 catch ( ArchivaSecurityException e )
642 log.warn( e.getMessage(), e );
644 return Collections.emptyList();
647 private void triggerAuditEvent( String user, String repositoryId, String resource, String action )
649 AuditEvent event = new AuditEvent( repositoryId, user, resource, action );
650 event.setRemoteIP( ServletActionContext.getRequest().getRemoteAddr() );
652 for ( AuditListener listener : auditListeners )
654 listener.auditEvent( event );