/** * Get a resolved Artifact from the coordinates provided * * @return the artifact, which has been resolved. * @throws MojoExecutionException */ protected Artifact getArtifact( String groupId, String artifactId, String version, String type, String classifier) throws MojoExecutionException { Artifact artifact; VersionRange vr; try { vr = VersionRange.createFromVersionSpec(version); } catch (InvalidVersionSpecificationException e) { vr = VersionRange.createFromVersion(version); } if (StringUtils.isEmpty(classifier)) { artifact = factory.createDependencyArtifact( groupId, artifactId, vr, type, null, Artifact.SCOPE_COMPILE); } else { artifact = factory.createDependencyArtifact( groupId, artifactId, vr, type, classifier, Artifact.SCOPE_COMPILE); } try { resolver.resolve(artifact, remoteRepos, local); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Unable to resolve artifact.", e); } catch (ArtifactNotFoundException e) { throw new MojoExecutionException("Unable to find artifact.", e); } return artifact; }
@SuppressWarnings("unchecked") private Set<Artifact> getAllArtifacts() throws MojoExecutionException { Set<Artifact> artifacts = new LinkedHashSet<Artifact>(); for (Dependency dep : (List<Dependency>) project.getDependencies()) { VersionRange versionRange; try { versionRange = VersionRange.createFromVersionSpec(dep.getVersion()); } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException( String.format( "%1s: unable to parse version '%2s' for dependency '%3s': %4s", dep.getArtifactId(), dep.getVersion(), dep.getManagementKey(), e.getMessage()), e); } String type = dep.getType() == null ? "jar" : dep.getType(); boolean optional = dep.isOptional(); String scope = dep.getScope() == null ? Artifact.SCOPE_COMPILE : dep.getScope(); Artifact artifact = artifactFactory.createDependencyArtifact( dep.getGroupId(), dep.getArtifactId(), versionRange, type, dep.getClassifier(), scope, optional); if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) { artifact.setFile(new File(dep.getSystemPath())); } handleExclusions(artifact, dep); artifacts.add(artifact); } return artifacts; }
private Map<String, Artifact> createManagedVersionMap() throws MojoExecutionException { Map<String, Artifact> map = new HashMap<String, Artifact>(); DependencyManagement dependencyManagement = project.getDependencyManagement(); if (dependencyManagement != null && dependencyManagement.getDependencies() != null) { for (Dependency d : dependencyManagement.getDependencies()) { try { VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion()); Artifact artifact = artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), d.getClassifier(), d.getScope(), d.isOptional()); handleExclusions(artifact, d); map.put(d.getManagementKey(), artifact); } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException( String.format( "%1s: unable to parse version '%2s' for dependency '%3s': %4s", project.getId(), d.getVersion(), d.getManagementKey(), e.getMessage()), e); } } } return map; }
protected void downloadRemoteDocs(List<WadlOption> effectiveOptions) throws MojoExecutionException { List<?> remoteRepos; try { remoteRepos = ProjectUtils.buildArtifactRepositories( repositories, artifactRepositoryFactory, mavenSession.getContainer()); } catch (InvalidRepositoryException e) { throw new MojoExecutionException("Error build repositories for remote wsdls", e); } for (WadlOption option : effectiveOptions) { DocumentArtifact wsdlA = option.getWadlArtifact(); if (wsdlA == null) { return; } Artifact wsdlArtifact = artifactFactory.createArtifact( wsdlA.getGroupId(), wsdlA.getArtifactId(), wsdlA.getVersion(), Artifact.SCOPE_COMPILE, wsdlA.getType()); wsdlArtifact = resolveRemoteWsdlArtifact(remoteRepos, wsdlArtifact); if (wsdlArtifact != null) { String path = wsdlArtifact.getFile().getAbsolutePath(); getLog().info("Resolved WSDL artifact to file " + path); option.setWadl(path); } } }
/** * @param artifactString should respect the format <code>groupId:artifactId[:version][:classifier] * </code> * @return the <code>Artifact</code> object for the <code>artifactString</code> parameter. * @throws MojoExecutionException if the <code>artifactString</code> doesn't respect the format. */ private Artifact getArtifact(String artifactString) throws MojoExecutionException { if (StringUtils.isEmpty(artifactString)) { throw new IllegalArgumentException("artifact parameter could not be empty"); } String groupId = null; // required String artifactId = null; // required String version = null; // optional String classifier = null; // optional String[] artifactParts = artifactString.split(":"); switch (artifactParts.length) { case 2: groupId = artifactParts[0]; artifactId = artifactParts[1]; version = Artifact.LATEST_VERSION; break; case 3: groupId = artifactParts[0]; artifactId = artifactParts[1]; version = artifactParts[2]; break; case 4: groupId = artifactParts[0]; artifactId = artifactParts[1]; version = artifactParts[2]; classifier = artifactParts[3]; break; default: throw new MojoExecutionException( "The artifact parameter '" + artifactString + "' should be conform to: " + "'groupId:artifactId[:version][:classifier]'."); } if (StringUtils.isNotEmpty(classifier)) { return artifactFactory.createArtifactWithClassifier( groupId, artifactId, version, "jar", classifier); } return artifactFactory.createArtifact( groupId, artifactId, version, Artifact.SCOPE_COMPILE, "jar"); }
private Artifact makeArtifact(String groupId, String artifactId, String version) { Artifact artifact = artifactFactory.createBuildArtifact(groupId, artifactId, version, "jar"); artifact.setFile( getTestFile( "src/test/repository/" + groupId + "/jars/" + artifactId + "-" + version + ".jar")); return artifact; }
protected Artifact getMavenArtifact(MavenArtifact mavenArtifact) throws MojoExecutionException, MojoFailureException { Artifact artifact; if (mavenArtifact.getVersion() != null) { artifact = artifactFactory.createArtifactWithClassifier( mavenArtifact.getGroupId(), mavenArtifact.getArtifactId(), mavenArtifact.getVersion(), mavenArtifact.getType(), mavenArtifact.getClassifier()); } else { Set<Artifact> projectArtifacts = getFilteredArtifacts( mavenArtifact.getGroupId(), mavenArtifact.getArtifactId(), mavenArtifact.getType(), mavenArtifact.getClassifier()); if (projectArtifacts.isEmpty()) { throw new MojoFailureException( "Maven artifact: '" + mavenArtifact.toString() + "' not found on dependencies list"); } else if (projectArtifacts.size() != 1) { throw new MojoFailureException( "More then one artifact found on dependencies list: '" + mavenArtifact.toString() + "'"); } artifact = projectArtifacts.iterator().next(); } if ("nexus-plugin".equals(mavenArtifact.getType())) { artifact = artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), "zip", "bundle"); } return resolve(artifact); }
public void shouldFindArtifact() { when(artifactFactory.createArtifact( coord.getGroupId(), coord.getArtifactId(), coord.getVersion(), "", coord.getFileType())) .thenReturn(goodArtifact); try { assertSame(locator.getAbsolutePathToArtifact(coord), A_PATH); } catch (Exception e) { fail("Should not have thrown an exception."); } }
private Set<Artifact> processTransientDependencies(Dependency dependency, boolean sharedLibraries) throws MojoExecutionException { try { final Set<Artifact> artifacts = new LinkedHashSet<Artifact>(); final CollectRequest collectRequest = new CollectRequest(); collectRequest.setRoot(dependency); collectRequest.setRepositories(projectRepos); final DependencyNode node = repoSystem.collectDependencies(repoSession, collectRequest).getRoot(); final DependencyRequest dependencyRequest = new DependencyRequest( node, new AndDependencyFilter( new ScopeDependencyFilter( Arrays.asList("compile", "runtime"), Arrays.asList("test")), // Also exclude any optional dependencies new DependencyFilter() { @Override public boolean accept( DependencyNode dependencyNode, List<DependencyNode> dependencyNodes) { return !dependencyNode.getDependency().isOptional(); } })); repoSystem.resolveDependencies(repoSession, dependencyRequest); PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); node.accept(nlg); final List<Dependency> dependencies = nlg.getDependencies(false); for (Dependency dep : dependencies) { final org.sonatype.aether.artifact.Artifact depAetherArtifact = dep.getArtifact(); if (isNativeLibrary(sharedLibraries, depAetherArtifact.getExtension())) { final Artifact mavenArtifact = artifactFactory.createDependencyArtifact( depAetherArtifact.getGroupId(), depAetherArtifact.getArtifactId(), VersionRange.createFromVersion(depAetherArtifact.getVersion()), depAetherArtifact.getExtension(), depAetherArtifact.getClassifier(), dep.getScope()); mavenArtifact.setFile(depAetherArtifact.getFile()); artifacts.add(mavenArtifact); } } return artifacts; } catch (Exception e) { throw new MojoExecutionException("Error while processing transient dependencies", e); } }
@SuppressWarnings("unchecked") private Collection<Artifact> getNonTransitivePlugins(Set<Artifact> projectArtifacts) throws MojoExecutionException { Collection<Artifact> deps = new LinkedHashSet<Artifact>(); for (Artifact artifact : projectArtifacts) { Artifact pomArtifact = artifactFactory.createArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getClassifier(), "pom"); Set<Artifact> result; try { MavenProject pomProject = mavenProjectBuilder.buildFromRepository( pomArtifact, remoteRepositories, localRepository); Set<Artifact> artifacts = pomProject.createArtifacts(artifactFactory, null, null); artifacts = filterOutSystemDependencies(artifacts); ArtifactResolutionResult arr = resolver.resolveTransitively( artifacts, pomArtifact, localRepository, remoteRepositories, artifactMetadataSource, null); result = arr.getArtifacts(); } catch (Exception e) { throw new MojoExecutionException( "Failed to resolve non-transitive deps " + e.getMessage(), e); } LinkedHashSet<Artifact> plugins = new LinkedHashSet<Artifact>(); plugins.addAll(filtterArtifacts(result, getFilters(null, null, "nexus-plugin", null))); plugins.addAll(filtterArtifacts(result, getFilters(null, null, "zip", "bundle"))); plugins.addAll(getNonTransitivePlugins(plugins)); if (!plugins.isEmpty()) { getLog() .debug( "Adding non-transitive dependencies for: " + artifact + " -\n" + plugins.toString().replace(',', '\n')); } deps.addAll(plugins); } return deps; }
public void shouldThrowExceptionForInvalidFileType() { String badFileType = "jstestdriver-invalid-artifact"; when(artifactFactory.createArtifact( coord.getGroupId(), coord.getArtifactId(), coord.getVersion(), "", badFileType)) .thenReturn(badArtifact); when(coord.getFileType()).thenReturn(badFileType); try { locator.getAbsolutePathToArtifact(coord); fail("Should have thrown an exception for invalid artifactId"); } catch (ArtifactNotFoundException ignored) { } }
public void shouldThrowExceptionForInvalidGroupId() { String badGroupId = "com.google.jstestdriver.some.invalid.group"; when(artifactFactory.createArtifact( badGroupId, coord.getArtifactId(), coord.getVersion(), "", coord.getFileType())) .thenReturn(badArtifact); when(coord.getGroupId()).thenReturn(badGroupId); try { locator.getAbsolutePathToArtifact(coord); fail("Should have thrown an exception for invalid groupId"); } catch (ArtifactNotFoundException ignored) { } }
protected Artifact resolve( String groupId, String artifactId, String version, String type, String classifier) throws MojoExecutionException { // return project.getArtifactMap().get( groupId + ":" + artifactId ); Artifact artifact = artifactFactory.createArtifactWithClassifier( groupId, artifactId, version, type, classifier); try { resolver.resolve(artifact, remoteRepositories, localRepository); } catch (ArtifactNotFoundException e) { throw new MojoExecutionException("artifact not found - " + e.getMessage(), e); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("artifact resolver problem - " + e.getMessage(), e); } return artifact; }
/** * @param artifactObj not null * @return the POM for the given artifact. * @throws MojoExecutionException if the artifact has a system scope. * @throws ProjectBuildingException when building pom. */ private MavenProject getMavenProject(Artifact artifactObj) throws MojoExecutionException, ProjectBuildingException { if (Artifact.SCOPE_SYSTEM.equals(artifactObj.getScope())) { throw new MojoExecutionException("System artifact is not be handled."); } Artifact copyArtifact = ArtifactUtils.copyArtifact(artifactObj); if (!"pom".equals(copyArtifact.getType())) { copyArtifact = artifactFactory.createProjectArtifact( copyArtifact.getGroupId(), copyArtifact.getArtifactId(), copyArtifact.getVersion(), copyArtifact.getScope()); } return mavenProjectBuilder.buildFromRepository( copyArtifact, remoteRepositories, localRepository); }
private void addProvider( SurefireBooter surefireBooter, String provider, String version, Artifact filteredArtifact) throws ArtifactNotFoundException, ArtifactResolutionException { Artifact providerArtifact = artifactFactory.createDependencyArtifact( "org.apache.maven.surefire", provider, VersionRange.createFromVersion(version), "jar", null, Artifact.SCOPE_TEST); ArtifactResolutionResult result = resolveArtifact(filteredArtifact, providerArtifact); for (Iterator i = result.getArtifacts().iterator(); i.hasNext(); ) { Artifact artifact = (Artifact) i.next(); getLog().debug("Adding to surefire test classpath: " + artifact.getFile().getAbsolutePath()); surefireBooter.addSurefireClassPathUrl(artifact.getFile().getAbsolutePath()); } }
protected Collection<Artifact> getNexusPlugins() throws MojoExecutionException { Set<Artifact> projectArtifacts = new LinkedHashSet<Artifact>(); projectArtifacts.addAll(getFilteredArtifacts(null, null, "zip", "bundle")); projectArtifacts.addAll(getFilteredArtifacts(null, null, "nexus-plugin", null)); projectArtifacts.addAll(getNonTransitivePlugins(projectArtifacts)); List<Artifact> resolvedArtifacts = new ArrayList<Artifact>(); for (Artifact artifact : projectArtifacts) { Artifact ra = artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getType(), artifact.getClassifier()); resolvedArtifacts.add(resolve(ra)); } return resolvedArtifacts; }
private ArtifactResolutionResult resolveArtifact( Artifact filteredArtifact, Artifact providerArtifact) throws ArtifactResolutionException, ArtifactNotFoundException { ArtifactFilter filter = null; if (filteredArtifact != null) { filter = new ExcludesArtifactFilter( Collections.singletonList( filteredArtifact.getGroupId() + ":" + filteredArtifact.getArtifactId())); } Artifact originatingArtifact = artifactFactory.createBuildArtifact("dummy", "dummy", "1.0", "jar"); // DUNS, use access method rather than "localRepository" field. return artifactResolver.resolveTransitively( Collections.singleton(providerArtifact), originatingArtifact, getLocalRepository(), getRemoteRepositories(), metadataSource, filter); }
private Map createManagedVersionMap( ArtifactFactory artifactFactory, String projectId, DependencyManagement dependencyManagement) throws MojoExecutionException { Map map; if (dependencyManagement != null && dependencyManagement.getDependencies() != null) { map = new HashMap(); for (Iterator i = dependencyManagement.getDependencies().iterator(); i.hasNext(); ) { Dependency d = (Dependency) i.next(); try { VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion()); Artifact artifact = artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), d.getClassifier(), d.getScope(), d.isOptional()); map.put(d.getManagementKey(), artifact); } catch (InvalidVersionSpecificationException e) { throw new MojoExecutionException( Messages.getString( "unabletoparseversion", new Object[] { // $NON-NLS-1$ projectId, d.getVersion(), d.getManagementKey(), e.getMessage() }), e); } } } else { map = Collections.EMPTY_MAP; } return map; }
private void executeServerDeploy(final Wagon wagon) throws MojoExecutionException { // alpha|nuclei|beta|electron|gamma|production deployment goes through scpexe try { if (ensureNoLocalModifications()) { @SuppressWarnings("unchecked") final List<ArtifactItem> theArtifactItems = getProcessedArtifactItems(stripVersion); for (ArtifactItem item : theArtifactItems) { final Artifact artifact = factory.createArtifactWithClassifier( item.getGroupId(), item.getArtifactId(), item.getVersion(), item.getType(), profile); resolver.resolve(artifact, getRemoteRepos(), getLocal()); final String sesamSite = project.getProperties().getProperty("sesam.site"); final String destName = null != sesamSite ? sesamSite : project.getBuild().getFinalName(); // tag the code final boolean tagOnDeploy = Boolean.parseBoolean( System.getProperty( TAG_ON_DEPLOY, project.getProperties().getProperty("tag.on.deploy"))); if (tagOnDeploy && !Boolean.getBoolean(DRY_RUN)) { tagDeploy(); } // do the upload getLog() .info( "Uploading " + artifact.getFile().getAbsolutePath() + " to " + wagon.getRepository().getUrl() + '/' + destName + ".war"); if (!Boolean.getBoolean(DRY_RUN)) { wagon.put(artifact.getFile(), destName + ".war"); } // update the version.txt getLog().info("Updating " + wagon.getRepository().getUrl() + "/version.txt"); if (Boolean.getBoolean(DRY_RUN)) { final StringWriter sb = new StringWriter(); final BufferedWriter w = new BufferedWriter(sb); updateArtifactEntry(new BufferedReader(new StringReader("")), w); w.flush(); getLog().info("version.txt entry will be \n" + sb.toString()); } else { updateVersionFile(wagon); } } } } catch (TransferFailedException ex) { getLog().error(ex); throw new MojoExecutionException("transfer failed", ex); } catch (ResourceDoesNotExistException ex) { getLog().error(ex); throw new MojoExecutionException("resource does not exist", ex); } catch (AuthorizationException ex) { getLog().error(ex); throw new MojoExecutionException("authorisation exception", ex); } catch (ArtifactNotFoundException ex) { getLog().error(ex); throw new MojoExecutionException("artifact not found", ex); } catch (ArtifactResolutionException ex) { getLog().error(ex); throw new MojoExecutionException("artifact resolution exception", ex); } catch (ScmException ex) { getLog().error(ex); throw new MojoExecutionException("scm exception", ex); } catch (ComponentLookupException ex) { getLog().error(ex); throw new MojoExecutionException("failed to lookup ScmManager", ex); } catch (IOException ex) { getLog().error(ex); throw new MojoExecutionException("IOException", ex); } }
public void execute() throws MojoExecutionException, MojoFailureException { if (skipNbm) { getLog().info("Skipping generation of NBM file."); return; } if ("pom".equals(project.getPackaging())) { getLog().info("Skipping " + project.getId() + ", no nbm:nbm execution for 'pom' packaging"); return; } super.execute(); // 3. generate nbm File nbmFile = new File(nbmBuildDir, finalName + ".nbm"); MakeNBM nbmTask = (MakeNBM) antProject.createTask("makenbm"); nbmTask.setFile(nbmFile); nbmTask.setProductDir(clusterDir); nbmTask.setModule("modules" + File.separator + moduleJarName + ".jar"); boolean reqRestart = requiresRestart; if (!reqRestart && module.isRequiresRestart()) { reqRestart = module.isRequiresRestart(); getLog() .warn( "Module descriptor's requiresRestart field is deprecated, use plugin's configuration in pom.xml"); } nbmTask.setNeedsrestart(Boolean.toString(reqRestart)); String moduleAuthor = author; if (module.getAuthor() != null) { moduleAuthor = module.getAuthor(); getLog() .warn( "Module descriptor's requiresRestart field is deprecated, use plugin's configuration in pom.xml"); } nbmTask.setModuleauthor(moduleAuthor); if (keystore != null && keystorealias != null && keystorepassword != null) { File ks = new File(keystore); if (!ks.exists()) { getLog().warn("Cannot find keystore file at " + ks.getAbsolutePath()); } else { Signature sig = nbmTask.createSignature(); sig.setKeystore(ks); sig.setAlias(keystorealias); sig.setStorepass(keystorepassword); getLog().debug("Setup the Ant task to sign the NBM file."); } } else if (keystore != null || keystorepassword != null || keystorealias != null) { getLog() .warn( "If you want to sign the nbm file, you need to define all three keystore related parameters."); } String licName = licenseName; File licFile = licenseFile; if (module.getLicenseName() != null) { licName = module.getLicenseName(); getLog() .warn( "Module descriptor's licenseName field is deprecated, use plugin's configuration in pom.xml"); } if (module.getLicenseFile() != null) { File lf = new File(project.getBasedir(), module.getLicenseFile()); licFile = lf; getLog() .warn( "Module descriptor's licenseFile field is deprecated, use plugin's configuration in pom.xml"); } if (licName != null && licFile != null) { if (!licFile.exists() || !licFile.isFile()) { getLog().warn("Cannot find license file at " + licFile.getAbsolutePath()); } else { Blurb lb = nbmTask.createLicense(); lb.setFile(licFile); lb.addText(licName); } } else if (licName != null || licFile != null) { getLog() .warn( "To set license for the nbm, you need to specify both licenseName and licenseFile parameters."); } else { Blurb lb = nbmTask.createLicense(); lb.addText(createDefaultLicenseHeader()); lb.addText(createDefaultLicenseText()); } String hpUrl = homePageUrl; if (module.getHomepageUrl() != null) { getLog() .warn( "Module descriptor's homePageUrl field is deprecated, use plugin's configuration in pom.xml"); hpUrl = module.getHomepageUrl(); } if (hpUrl != null) { nbmTask.setHomepage(hpUrl); } String distribUrl = distributionUrl; if (module.getDistributionUrl() != null) { distribUrl = module.getDistributionUrl(); getLog() .warn( "Module descriptor's distributionUrl field is deprecated, use plugin's configuration in pom.xml"); } if (distribUrl != null) { ArtifactRepository distRepository = CreateUpdateSiteMojo.getDeploymentRepository(distribUrl, container, getLog()); String dist = null; if (distRepository == null) { if (!distribUrl.contains("::")) { dist = distribUrl + (distribUrl.endsWith("/") ? "" : "/") + nbmFile.getName(); } } else { Artifact art = artifactFactory.createArtifact( project.getGroupId(), project.getArtifactId(), project.getVersion(), null, "nbm-file"); dist = distRepository.getUrl() + (distRepository.getUrl().endsWith("/") ? "" : "/") + distRepository.pathOf(art); } nbmTask.setDistribution(dist); } else { nbmTask.setDistribution(nbmFile.getName()); } if (!"extra".equals(cluster)) { nbmTask.setTargetcluster(cluster); } // MNBMODULE-217 avoid using the static DATE_FORMAT variable in MavenNBM.java (in ant harness) nbmTask.setReleasedate(DATE_FORMAT.format(new Date(System.currentTimeMillis()))); try { nbmTask.execute(); } catch (BuildException e) { throw new MojoExecutionException("Cannot Generate nbm file:" + e.getMessage(), e); } try { File nbmfile = new File(buildDir, nbmFile.getName()); FileUtils.getFileUtils().copyFile(nbmFile, nbmfile); projectHelper.attachArtifact(project, "nbm-file", null, nbmfile); } catch (IOException ex) { throw new MojoExecutionException("Cannot copy nbm to build directory", ex); } }
@Override public void execute(final EnforcerRuleHelper helper) throws EnforcerRuleException { final MavenProject project; try { project = (MavenProject) helper.evaluate("${project}"); } catch (ExpressionEvaluationException e) { throw new EnforcerRuleException("Failed to access ${project} variable", e); } final String type = project.getArtifact().getType(); if (!AbstractEnforcerRule.JAR_ARTIFACT_TYPE.equals(type)) { helper .getLog() .debug("Skipping non " + AbstractEnforcerRule.JAR_ARTIFACT_TYPE + " artifact."); return; } final Artifact previousArtifact; final Artifact currentArtifact = project.getArtifact(); validateArtifact(currentArtifact); final Version current = Version.parse(currentArtifact.getVersion()); final File currentJar = currentArtifact.getFile(); try { final ArtifactRepository localRepository = (ArtifactRepository) helper.evaluate("${localRepository}"); final String version; if (this.previousVersion != null) { version = this.previousVersion; helper.getLog().info("Version specified as <" + version + ">"); } else { final ArtifactMetadataSource artifactMetadataSource = (ArtifactMetadataSource) helper.getComponent(ArtifactMetadataSource.class); final List<ArtifactVersion> availableVersions = getAvailableReleasedVersions(artifactMetadataSource, project, localRepository); final List<ArtifactVersion> availablePreviousVersions = filterNonPreviousVersions(availableVersions, current); if (availablePreviousVersions.isEmpty()) { helper .getLog() .warn("No previously released version. Backward compatibility check not performed."); return; } version = availablePreviousVersions.iterator().next().toString(); helper .getLog() .info( "Version deduced as <" + version + "> (among all availables: " + availablePreviousVersions + ")"); } final ArtifactFactory artifactFactory = (ArtifactFactory) helper.getComponent(ArtifactFactory.class); previousArtifact = artifactFactory.createArtifact( project.getGroupId(), project.getArtifactId(), version, null, type); final ArtifactResolver resolver = (ArtifactResolver) helper.getComponent(ArtifactResolver.class); resolver.resolve(previousArtifact, project.getRemoteArtifactRepositories(), localRepository); validateArtifact(previousArtifact); } catch (Exception e) { helper.getLog().warn("Exception while accessing artifacts; skipping check.", e); return; } final Version previous = Version.parse(previousArtifact.getVersion()); final File previousJar = previousArtifact.getFile(); helper.getLog().info("Using <" + previousJar + "> as previous JAR"); helper.getLog().info("Using <" + currentJar + "> as current JAR"); try { final Comparer comparer = new Comparer( previousJar, currentJar, extractFilters(this.includes), extractFilters(this.excludes)); final Delta delta = comparer.diff(); enforce(helper, delta, previous, current); } catch (IOException e) { throw new EnforcerRuleException("Exception while checking compatibility: " + e.toString(), e); } }
public void execute() throws MojoExecutionException, MojoFailureException { if (this.skip) { getLog().info("skip execution"); return; } // project.addAttachedArtifact( ); File warExecFile = new File(buildDirectory, finalName); if (warExecFile.exists()) { warExecFile.delete(); } File execWarJar = new File(buildDirectory, finalName); FileOutputStream execWarJarOutputStream = null; ArchiveOutputStream os = null; File tmpPropertiesFile = null; File tmpManifestFile = null; FileOutputStream tmpPropertiesFileOutputStream = null; PrintWriter tmpManifestWriter = null; try { tmpPropertiesFile = new File(buildDirectory, "war-exec.properties"); if (tmpPropertiesFile.exists()) { tmpPropertiesFile.delete(); } tmpPropertiesFile.getParentFile().mkdirs(); tmpManifestFile = new File(buildDirectory, "war-exec.manifest"); if (tmpManifestFile.exists()) { tmpManifestFile.delete(); } tmpPropertiesFileOutputStream = new FileOutputStream(tmpPropertiesFile); execWarJar.getParentFile().mkdirs(); execWarJar.createNewFile(); execWarJarOutputStream = new FileOutputStream(execWarJar); tmpManifestWriter = new PrintWriter(tmpManifestFile); // store : // * wars in the root: foo.war // * tomcat jars // * file tomcat.standalone.properties with possible values : // * useServerXml=true/false to use directly the one provided // * enableNaming=true/false // * wars=foo.war|contextpath;bar.war ( |contextpath is optionnal if empty use the war name // ) // * accessLogValveFormat= // * connectorhttpProtocol: HTTP/1.1 or org.apache.coyote.http11.Http11NioProtocol // * optionnal: conf/ with usual tomcat configuration files // * MANIFEST with Main-Class Properties properties = new Properties(); properties.put( Tomcat7Runner.ARCHIVE_GENERATION_TIMESTAMP_KEY, Long.toString(System.currentTimeMillis())); properties.put(Tomcat7Runner.ENABLE_NAMING_KEY, Boolean.toString(enableNaming)); properties.put(Tomcat7Runner.ACCESS_LOG_VALVE_FORMAT_KEY, accessLogValveFormat); properties.put(Tomcat7Runner.HTTP_PROTOCOL_KEY, connectorHttpProtocol); os = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.JAR, execWarJarOutputStream); if ("war".equals(project.getPackaging())) { os.putArchiveEntry(new JarArchiveEntry(StringUtils.removeStart(path, "/") + ".war")); IOUtils.copy(new FileInputStream(projectArtifact.getFile()), os); os.closeArchiveEntry(); properties.put(Tomcat7Runner.WARS_KEY, StringUtils.removeStart(path, "/") + ".war|" + path); } else if (warRunDependencies != null && !warRunDependencies.isEmpty()) { for (WarRunDependency warRunDependency : warRunDependencies) { if (warRunDependency.dependency != null) { Dependency dependency = warRunDependency.dependency; Artifact artifact = artifactFactory.createArtifactWithClassifier( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getType(), dependency.getClassifier()); artifactResolver.resolve(artifact, this.remoteRepos, this.local); File warFileToBundle = new File(resolvePluginWorkDir(), artifact.getFile().getName()); FileUtils.copyFile(artifact.getFile(), warFileToBundle); if (warRunDependency.contextXml != null) { warFileToBundle = addContextXmlToWar(warRunDependency.contextXml, warFileToBundle); } final String warFileName = artifact.getFile().getName(); os.putArchiveEntry(new JarArchiveEntry(warFileName)); IOUtils.copy(new FileInputStream(warFileToBundle), os); os.closeArchiveEntry(); String propertyWarValue = properties.getProperty(Tomcat7Runner.WARS_KEY); String contextPath = StringUtils.isEmpty(warRunDependency.contextPath) ? "/" : warRunDependency.contextPath; if (propertyWarValue != null) { properties.put( Tomcat7Runner.WARS_KEY, propertyWarValue + ";" + warFileName + "|" + contextPath); } else { properties.put(Tomcat7Runner.WARS_KEY, warFileName + "|" + contextPath); } } } } if (serverXml != null && serverXml.exists()) { os.putArchiveEntry(new JarArchiveEntry("conf/server.xml")); IOUtils.copy(new FileInputStream(serverXml), os); os.closeArchiveEntry(); properties.put(Tomcat7Runner.USE_SERVER_XML_KEY, Boolean.TRUE.toString()); } else { properties.put(Tomcat7Runner.USE_SERVER_XML_KEY, Boolean.FALSE.toString()); } os.putArchiveEntry(new JarArchiveEntry("conf/web.xml")); IOUtils.copy(getClass().getResourceAsStream("/conf/web.xml"), os); os.closeArchiveEntry(); properties.store(tmpPropertiesFileOutputStream, "created by Apache Tomcat Maven plugin"); tmpPropertiesFileOutputStream.flush(); tmpPropertiesFileOutputStream.close(); os.putArchiveEntry(new JarArchiveEntry(Tomcat7RunnerCli.STAND_ALONE_PROPERTIES_FILENAME)); IOUtils.copy(new FileInputStream(tmpPropertiesFile), os); os.closeArchiveEntry(); // add tomcat classes for (Artifact pluginArtifact : pluginArtifacts) { if (StringUtils.equals("org.apache.tomcat", pluginArtifact.getGroupId()) || StringUtils.equals("org.apache.tomcat.embed", pluginArtifact.getGroupId()) || StringUtils.equals("org.eclipse.jdt.core.compiler", pluginArtifact.getGroupId()) || StringUtils.equals("commons-cli", pluginArtifact.getArtifactId()) || StringUtils.equals("tomcat7-war-runner", pluginArtifact.getArtifactId())) { JarFile jarFile = new JarFile(pluginArtifact.getFile()); extractJarToArchive(jarFile, os); } } // add extra dependencies if (extraDependencies != null && !extraDependencies.isEmpty()) { for (Dependency dependency : extraDependencies) { // String groupId, String artifactId, String version, String scope, String type Artifact artifact = artifactFactory.createArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getScope(), dependency.getType()); artifactResolver.resolve(artifact, this.remoteRepos, this.local); JarFile jarFile = new JarFile(artifact.getFile()); extractJarToArchive(jarFile, os); } } Manifest manifest = new Manifest(); Manifest.Attribute mainClassAtt = new Manifest.Attribute(); mainClassAtt.setName("Main-Class"); mainClassAtt.setValue(mainClass); manifest.addConfiguredAttribute(mainClassAtt); manifest.write(tmpManifestWriter); tmpManifestWriter.flush(); tmpManifestWriter.close(); os.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF")); IOUtils.copy(new FileInputStream(tmpManifestFile), os); os.closeArchiveEntry(); if (attachArtifact) { // MavenProject project, String artifactType, String artifactClassifier, File artifactFile projectHelper.attachArtifact( project, attachArtifactClassifierType, attachArtifactClassifier, execWarJar); } if (extraResources != null) { for (ExtraResource extraResource : extraResources) { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(extraResource.getDirectory()); directoryScanner.addDefaultExcludes(); directoryScanner.setExcludes(toStringArray(extraResource.getExcludes())); directoryScanner.setIncludes(toStringArray(extraResource.getIncludes())); directoryScanner.scan(); for (String includeFile : directoryScanner.getIncludedFiles()) { getLog().debug("include file:" + includeFile); os.putArchiveEntry(new JarArchiveEntry(includeFile)); IOUtils.copy( new FileInputStream(new File(extraResource.getDirectory(), includeFile)), os); os.closeArchiveEntry(); } } } if (tomcatConfigurationFilesDirectory != null && tomcatConfigurationFilesDirectory.exists()) { // Because its the tomcat default dir for configs String aConfigOutputDir = "conf/"; copyDirectoryContentIntoArchive(tomcatConfigurationFilesDirectory, aConfigOutputDir, os); } } catch (ManifestException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (ArchiveException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (ArtifactNotFoundException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(tmpManifestWriter); IOUtils.closeQuietly(execWarJarOutputStream); IOUtils.closeQuietly(tmpPropertiesFileOutputStream); } }