List of usage examples for org.apache.maven.project MavenProject getArtifact
public Artifact getArtifact()
From source file:com.tvarit.plugin.TvaritTomcatDeployerMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { final MavenProject project = (MavenProject) this.getPluginContext().getOrDefault("project", null); if (templateUrl == null) try {// w w w . j a v a 2 s . com templateUrl = new TemplateUrlMaker().makeUrl(project, "newinstance.template").toString(); } catch (MalformedURLException e) { throw new MojoExecutionException( "Could not create default url for templates. Please open an issue on github.", e); } final BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); AmazonS3Client s3Client = new AmazonS3Client(awsCredentials); final File warFile = project.getArtifact().getFile(); final String key = "deployables/" + project.getGroupId() + "/" + project.getArtifactId() + "/" + project.getVersion() + "/" + warFile.getName(); final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, warFile); final ObjectMetadata metadata = new ObjectMetadata(); final HashMap<String, String> userMetadata = new HashMap<>(); userMetadata.put("project_name", projectName); userMetadata.put("stack_template_url", templateUrl); userMetadata.put("private_key_name", sshKeyName); metadata.setUserMetadata(userMetadata); putObjectRequest.withMetadata(metadata); final PutObjectResult putObjectResult = s3Client.putObject(putObjectRequest); /* AmazonCloudFormationClient amazonCloudFormationClient = new AmazonCloudFormationClient(awsCredentials); final com.amazonaws.services.cloudformation.model.Parameter projectNameParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("projectName").withParameterValue(this.projectName); final com.amazonaws.services.cloudformation.model.Parameter publicSubnetsParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("publicSubnets").withParameterValue(commaSeparatedSubnetIds); final com.amazonaws.services.cloudformation.model.Parameter tvaritRoleParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("tvaritRole").withParameterValue(tvaritRole); final com.amazonaws.services.cloudformation.model.Parameter tvaritInstanceProfileParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("tvaritInstanceProfile").withParameterValue(this.tvaritInstanceProfile); final com.amazonaws.services.cloudformation.model.Parameter tvaritBucketNameParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("bucketName").withParameterValue(this.bucketName); final com.amazonaws.services.cloudformation.model.Parameter instanceSecurityGroupIdParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("sgId").withParameterValue(this.instanceSecurityGroupId); final com.amazonaws.services.cloudformation.model.Parameter sshKeyNameParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("keyName").withParameterValue(this.sshKeyName); final String warFileUrl = s3Client.getUrl(bucketName, key).toString(); final com.amazonaws.services.cloudformation.model.Parameter warFileUrlParameter = new com.amazonaws.services.cloudformation.model.Parameter().withParameterKey("warFileUrl").withParameterValue(warFileUrl); final CreateStackRequest createStackRequest = new CreateStackRequest(); if (templateUrl == null) { try { templateUrl = new TemplateUrlMaker().makeUrl(project, "newinstance.template").toString(); } catch (MalformedURLException e) { throw new MojoExecutionException("Could not create default url for templates. Please open an issue on github.", e); } } createStackRequest. withStackName(projectName + "-instance-" + project.getVersion().replace(".", "-")). withParameters( projectNameParameter, publicSubnetsParameter, tvaritInstanceProfileParameter, tvaritRoleParameter, tvaritBucketNameParameter, instanceSecurityGroupIdParameter, warFileUrlParameter, sshKeyNameParameter ). withDisableRollback(true). withTemplateURL(templateUrl); createStackRequest.withDisableRollback(true); final Stack stack = new StackMaker().makeStack(createStackRequest, amazonCloudFormationClient, getLog()); AmazonAutoScalingClient amazonAutoScalingClient = new AmazonAutoScalingClient(awsCredentials); final AttachInstancesRequest attachInstancesRequest = new AttachInstancesRequest(); attachInstancesRequest.withInstanceIds(stack.getOutputs().get(0).getOutputValue(), stack.getOutputs().get(1).getOutputValue()).withAutoScalingGroupName(autoScalingGroupName); amazonAutoScalingClient.attachInstances(attachInstancesRequest); */ }
From source file:de.adorsys.cmer.ProjectNamingConverntions.java
License:Apache License
private void checkGroupIdPrefix(MavenProject project) throws EnforcerRuleException { if (!project.getGroupId().startsWith(allowedGroupPrefix)) { throw new EnforcerRuleException("The groupId of project " + project.getArtifact() + " have to start with :" + allowedGroupPrefix); }/* ww w . jav a 2 s . c om*/ }
From source file:de.eacg.ecs.plugin.ProjectFix.java
public static void fixProject(MavenProject model) { Artifact a = model.getArtifact(); String str = String.format("%s:%s:%s:%s:%s", a.getGroupId(), a.getArtifactId(), a.getType(), a.hasClassifier() ? a.getClassifier() : "", a.getVersion()); String fixed = lookup.get(str); if (fixed != null) { String[] parts = fixed.split(":"); if (parts.length == 5) { model.setGroupId(parts[0]);/* w ww . jav a 2 s.co m*/ model.setArtifactId(parts[1]); model.setPackaging(parts[2]); model.setVersion(parts[4]); model.setArtifact(new DefaultArtifact(parts[0], parts[1], parts[4], model.getArtifact().getScope(), parts[2], parts[3].isEmpty() ? null : parts[3], model.getArtifact().getArtifactHandler())); } } }
From source file:de.fct.companian.analyze.mvn.VersionRangeAnalysis.java
License:Apache License
public void analyseVersionRange(MavenProject mvnProject) { logger.info("analyseVersionRanges() start"); if (mvnProject != null) { logger.info("analyseVersionRanges() project=" + mvnProject.getArtifact().getArtifactId()); Set<Artifact> artifactSet = mvnProject.getArtifacts(); boolean versionRangeUsed = false; if (artifactSet != null) { for (Artifact artifact : artifactSet) { if (!artifact.getScope().equalsIgnoreCase(Artifact.SCOPE_TEST)) { if (artifact.getType().equalsIgnoreCase("jar")) { if (isRangeSet(artifact.getVersionRange().toString())) { logger.info("analyseVersionRanges() artifact=" + artifact.getArtifactId() + ", versionRange=" + artifact.getVersionRange()); versionRangeUsed = true; }//from ww w. ja v a 2 s.c o m } } } } else { logger.info("analyseVersionRanges() no artifacts found for this Maven project"); } if (!versionRangeUsed) { logger.info("analyseVersionRanges() no version ranges where used by the dependencies of project " + mvnProject.getArtifact().getDependencyConflictId()); } } else { logger.error("analyseVersionRanges() no Maven project found"); } logger.info("analyseVersionRanges() finished"); }
From source file:de.hwbllmnn.maven.DistMojo.java
License:GNU General Public License
public void execute() throws MojoExecutionException, MojoFailureException { Log log = getLog();/*w ww. j a va 2 s .c om*/ File basedir = project.getBasedir(); File target = new File(basedir, "target/dist"); if (!target.isDirectory() && !target.mkdirs()) { log.warn("Could not create target directory: " + target); } List<Artifact> artifacts = new LinkedList<Artifact>(); @SuppressWarnings("unchecked") List<Object> modules = project.getCollectedProjects(); if (includeProjectArtifacts) { modules.add(project); } for (Object o : modules) { MavenProject module = (MavenProject) o; List<?> arts = module.getAttachedArtifacts(); for (Object obj : arts) { artifacts.add((Artifact) obj); } if (!includeOnlyAttachedArtifacts) { artifacts.add(module.getArtifact()); } } log.info("Collected artifacts: " + artifacts); for (Artifact a : artifacts) { File file = a.getFile(); if (file == null) { log.warn("Skipping non-existing artifact: " + a); continue; } try { copyFile(file, new File(target, file.getName())); log.info("Copied artifact " + file.getName()); } catch (IOException e) { log.warn("Could not copy artifact: " + file); } } }
From source file:de.jiac.micro.mojo.ConfiguratorMojo.java
License:Open Source License
private Set transitivelyResolvePomDependencies(String groupId, String artifactId, String version) throws ProjectBuildingException, InvalidDependencyVersionException, ArtifactResolutionException, ArtifactNotFoundException {//from w ww. j av a2s . c o m //get the pom as an Artifact Artifact pomArtifact = artifactFactory.createPluginArtifact(groupId, artifactId, VersionRange.createFromVersion(version)); //load the pom as a MavenProject MavenProject tempProject = mavenProjectBuilder.buildFromRepository(pomArtifact, remoteRepositories, localRepository); //get all of the dependencies for the project List dependencies = tempProject.getDependencies(); //make Artifacts of all the dependencies Set dependencyArtifacts = MavenMetadataSource.createArtifacts(artifactFactory, dependencies, null, null, null); //not forgetting the Artifact of the project itself dependencyArtifacts.add(tempProject.getArtifact()); //resolve all dependencies transitively to obtain a comprehensive list of jars ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts, pomArtifact, Collections.EMPTY_MAP, localRepository, remoteRepositories, metadataSource, null, Collections.EMPTY_LIST); return result.getArtifacts(); }
From source file:de.jiac.micro.util.ReducedArchiver.java
License:Open Source License
public void createArchive(MavenProject project, MavenArchiveConfiguration archiveConfiguration) throws ArchiverException, ManifestException, IOException, DependencyResolutionRequiredException { // ---------------------------------------------------------------------- // We want to add the metadata for the project to the JAR in two forms: ////from w w w.j a v a 2 s . co m // The first form is that of the POM itself. Applications that wish to // access the POM for an artifact using maven tools they can. // // The second form is that of a properties file containing the basic // top-level POM elements so that applications that wish to access // POM information without the use of maven tools can do so. // ---------------------------------------------------------------------- // we have to clone the project instance so we can write out the pom with the deployment version, // without impacting the main project instance... MavenProject workingProject = new MavenProject(project); if (workingProject.getArtifact().isSnapshot()) { workingProject.setVersion(workingProject.getArtifact().getVersion()); } // ---------------------------------------------------------------------- // Create the manifest // ---------------------------------------------------------------------- File manifestFile = archiveConfiguration.getManifestFile(); if (manifestFile != null) { archiver.setManifest(manifestFile); } Manifest manifest = getManifest(workingProject, archiveConfiguration.getManifest()); // any custom manifest entries in the archive configuration manifest? if (!archiveConfiguration.isManifestEntriesEmpty()) { Map entries = archiveConfiguration.getManifestEntries(); Set entrySet = entries.entrySet(); for (Iterator iter = entrySet.iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); Manifest.Attribute attr = new Manifest.Attribute(key, value); manifest.addConfiguredAttribute(attr); } } // any custom manifest sections in the archive configuration manifest? if (!archiveConfiguration.isManifestSectionsEmpty()) { List sections = archiveConfiguration.getManifestSections(); for (Iterator iter = sections.iterator(); iter.hasNext();) { ManifestSection section = (ManifestSection) iter.next(); Manifest.Section theSection = new Manifest.Section(); theSection.setName(section.getName()); if (!section.isManifestEntriesEmpty()) { Map entries = section.getManifestEntries(); Set keys = entries.keySet(); for (Iterator it = keys.iterator(); it.hasNext();) { String key = (String) it.next(); String value = (String) entries.get(key); Manifest.Attribute attr = new Manifest.Attribute(key, value); theSection.addConfiguredAttribute(attr); } } manifest.addConfiguredSection(theSection); } } // Configure the jar archiver.addConfiguredManifest(manifest); archiver.setCompress(archiveConfiguration.isCompress()); archiver.setIndex(archiveConfiguration.isIndex()); archiver.setDestFile(archiveFile); // create archive archiver.createArchive(); }
From source file:de.lightful.maven.plugins.drools.impl.OutputFileWriter.java
License:Apache License
public void writeOutputFile(Collection<KnowledgePackage> knowledgePackages, PluginLogger logger, MavenProjectDecorator mavenProjectDecorator, MavenProjectHelper projectHelper, String classifier) throws MojoFailureException { MavenProject mavenProject = mavenProjectDecorator.getProject(); ensureCorrectPackaging(mavenProject); Build build = mavenProject.getBuild(); File buildDirectory = new File(build.getDirectory()); File outputFile = new File(buildDirectory, build.getFinalName() + "." + WellKnownNames.FILE_EXTENSION_DROOLS_KNOWLEDGE_MODULE); final String absoluteOutputFileName = outputFile.getAbsolutePath(); logger.info().write("Writing " + knowledgePackages.size() + " knowledge packages into output file " + mavenProjectDecorator.relativeToBasedir(outputFile)).nl(); int counter = 1; for (KnowledgePackage knowledgePackage : knowledgePackages) { String declaredTypesCount = "(unknown)"; String globalsCount = "(unknown)"; String rulesCount = "(unknown)"; if (knowledgePackage instanceof KnowledgePackageImp) { final KnowledgePackageImp packageImp = (KnowledgePackageImp) knowledgePackage; rulesCount = String.valueOf(knowledgePackage.getRules().size()); declaredTypesCount = String.valueOf(packageImp.pkg.getTypeDeclarations().size()); globalsCount = String.valueOf(packageImp.pkg.getGlobals().size()); }/*w w w. j a v a2 s . co m*/ logger.info().write(" #" + counter + ": " + knowledgePackage.getName()).write(" (" + rulesCount + " rules, " + declaredTypesCount + " type declarations, " + globalsCount + " globals)").nl(); counter++; } ensureTargetDirectoryExists(buildDirectory); prepareOutputFileForWriting(outputFile, absoluteOutputFileName); KnowledgeIoFactory factory = new KnowledgeIoFactory(); try { final KnowledgeModuleWriter writer = factory .createKnowledgeModuleWriter(new FileOutputStream(outputFile)); writer.writeKnowledgePackages(knowledgePackages); } catch (IOException e) { throw new MojoFailureException("Unable to write compiled knowledge into output file!", e); } if (classifier != null && !"".equals(classifier)) { debug.write("Attaching file " + outputFile.getAbsolutePath() + " as artifact with classifier '" + classifier + "'."); projectHelper.attachArtifact(mavenProject, outputFile, classifier); } else { debug.write(("Setting project main artifact to " + outputFile.getAbsolutePath())).nl(); final Artifact artifact = mavenProject.getArtifact(); artifact.setFile(outputFile); } }
From source file:de.smartics.maven.enforcer.rule.NoSnapshotsInDependencyManagementRule.java
License:Apache License
/** * {@inheritDoc}//from w ww . ja v a 2 s.c om */ public void execute(final EnforcerRuleHelper helper) throws EnforcerRuleException { final Log log = helper.getLog(); try { final MavenProject project = (MavenProject) helper.evaluate("${project}"); final boolean isSnapshot = project.getArtifact().isSnapshot(); if (onlyWhenRelease && isSnapshot) { log.info(getCacheId() + ": Skipping since not a release."); return; } final DependencyManagement dependencyManagement = project.getModel().getDependencyManagement(); if (dependencyManagement == null) { log.debug(getCacheId() + ": No dependency management block found."); return; } if (!checkOnlyResolvedDependencies) { final DependencyManagement originalDependencyManagement = project.getOriginalModel() .getDependencyManagement(); if (originalDependencyManagement != null) { final List<Dependency> declaredDependencies = originalDependencyManagement.getDependencies(); if (declaredDependencies != null && !declaredDependencies.isEmpty()) { checkDependenciesForSnapshots(helper, log, declaredDependencies); } } } final List<Dependency> dependencies = dependencyManagement.getDependencies(); if (dependencies == null || dependencies.isEmpty()) { log.debug(getCacheId() + ": No dependencies in dependency management block found."); return; } checkDependenciesForSnapshots(helper, log, dependencies); } catch (final ExpressionEvaluationException e) { throw new EnforcerRuleException("Unable to evaluate expression '" + e.getLocalizedMessage() + "'.", e); } }
From source file:fr.brouillard.oss.jgitver.JGitverExtension.java
License:Apache License
@Override public void afterProjectsRead(MavenSession mavenSession) throws MavenExecutionException { MavenProject rootProject = mavenSession.getTopLevelProject(); List<MavenProject> projects = locateProjects(mavenSession, rootProject.getModules()); Map<GAV, String> newProjectVersions = new LinkedHashMap<>(); if (JGitverModelProcessor.class.isAssignableFrom(modelProcessor.getClass())) { JGitverModelProcessor jGitverModelProcessor = JGitverModelProcessor.class.cast(modelProcessor); JGitverModelProcessorWorkingConfiguration workingConfiguration = jGitverModelProcessor .getWorkingConfiguration(); if (workingConfiguration == null) { logger.warn(""); logger.warn("jgitver has changed!"); logger.warn(""); logger.warn(/*from ww w. j a v a 2 s . c o m*/ "it now requires the usage of maven core extensions instead of standard plugin extensions."); logger.warn("The plugin must be now declared in a `.mvn/extensions.xml` file."); logger.warn(""); logger.warn(" read https://github.com/jgitver/jgitver-maven-plugin for further information"); logger.warn(""); throw new MavenExecutionException("detection of jgitver old setting mechanism", new IllegalStateException("jgitver must now use maven core extensions")); } newProjectVersions = workingConfiguration.getNewProjectVersions(); } else { logger.info("jgitver-maven-plugin is about to change project(s) version(s)"); String newVersion = null; try { newVersion = JGitverUtils .calculateVersionForProject(rootProject, mavenSession.getUserProperties(), logger) .getCalculatedVersion(); } catch (IOException ex) { throw new MavenExecutionException("failure calculating version from git information", ex); } // Let's modify in memory resolved projects model for (MavenProject project : projects) { GAV projectGAV = GAV.from(project); // SUPPRESS CHECKSTYLE AbbreviationAsWordInName logger.debug("about to change in memory POM for: " + projectGAV); // First the project itself project.setVersion(newVersion); logger.debug(" version set to " + newVersion); VersionRange newVersionRange = VersionRange.createFromVersion(newVersion); project.getArtifact().setVersionRange(newVersionRange); logger.debug(" artifact version range set to " + newVersionRange); newProjectVersions.put(projectGAV, newVersion); // No need to worry about parent link, because model is in memory } try { JGitverUtils.attachModifiedPomFilesToTheProject(projects, newProjectVersions, mavenSession, logger); } catch (IOException | XmlPullParserException ex) { throw new MavenExecutionException("cannot attach updated POMs during project execution", ex); } } newProjectVersions.entrySet() .forEach(e -> logger.info(" " + e.getKey().toString() + " -> " + e.getValue())); }