List of usage examples for org.apache.maven.project MavenProject getArtifact
public Artifact getArtifact()
From source file:org.fluidity.deployment.maven.DependenciesSupportImpl.java
License:Apache License
@Override public Collection<Artifact> runtimeDependencies(final RepositorySystemSession session, final List<RemoteRepository> repositories, final MavenProject project, final boolean optionals) throws MojoExecutionException { return dependencyClosure(session, repositories, project.getArtifact(), false, optionals, null); }
From source file:org.fluidity.deployment.maven.DependenciesSupportImpl.java
License:Apache License
@Override public Collection<Artifact> compileDependencies(final RepositorySystemSession session, final List<RemoteRepository> repositories, final MavenProject project, final boolean optionals) throws MojoExecutionException { return dependencyClosure(session, repositories, project.getArtifact(), true, optionals, null); }
From source file:org.fluidity.deployment.maven.DependenciesSupportImpl.java
License:Apache License
@Override public void saveArtifact(final MavenProject project, final File file, final String finalName, final String classifier, final String packaging, final Logger log) throws MojoExecutionException { final boolean unclassified = classifier == null || classifier.isEmpty(); final String outputName = unclassified ? String.format("%s.%s", finalName, packaging) : String.format("%s-%s.%s", finalName, classifier, packaging); final File outputFile = new File(outputName); final String outputPath = outputFile.getAbsolutePath(); final Artifact artifact = project.getArtifact(); assert artifact != null; final File artifactFile = artifact.getFile(); if (artifactFile != null && artifactFile.getAbsolutePath().equals(outputPath)) { log.info(String.format("Replacing %s: %s", packaging, artifactFile.getAbsolutePath())); if (!artifactFile.delete()) { throw new MojoExecutionException(String.format("Could not delete %s", artifactFile)); }/*w ww. j a v a 2 s. c o m*/ if (!file.renameTo(artifactFile)) { throw new MojoExecutionException(String.format("Could not create %s", artifactFile)); } } else { boolean replacing = false; for (final Artifact attached : project.getAttachedArtifacts()) { if (attached.getFile().getAbsolutePath().equals(outputPath)) { replacing = true; break; } } log.info(String.format("%s %s: %s", replacing ? "Replacing" : "Saving", packaging, outputPath)); if (outputFile.exists() && !outputFile.delete()) { throw new MojoExecutionException(String.format("Could not delete %s", outputFile)); } if (!file.renameTo(outputFile)) { throw new MojoExecutionException(String.format("Could not create %s", outputFile)); } if (!replacing) { final DefaultArtifact attachment = new DefaultArtifact(project.getGroupId(), project.getArtifactId(), project.getVersion(), artifact.getScope(), packaging, classifier, artifact.getArtifactHandler()); attachment.setFile(outputFile); project.addAttachedArtifact(attachment); } } }
From source file:org.fluidity.foundation.impl.BundleJarManifest.java
License:Apache License
public SecurityPolicy processManifest(final MavenProject project, final Attributes attributes, final SecurityPolicy policy, final Logger log, final Dependencies dependencies) throws MojoExecutionException { dependencies.attribute(BUNDLE_CLASSPATH, ","); addEntry(attributes, BUNDLE_MANIFESTVERSION, "2"); addEntry(attributes, BUNDLE_NAME, project::getName); addEntry(attributes, BUNDLE_SYMBOLICNAME, project::getArtifactId); addEntry(attributes, BUNDLE_VERSION, project::getVersion); addEntry(attributes, BUNDLE_DESCRIPTION, project::getDescription); addEntry(attributes, BUNDLE_DOCURL, project::getUrl); addEntry(attributes, BUNDLE_VENDOR, () -> { return project.getOrganization().getName(); });/* www . j a v a 2 s .co m*/ addEntry(attributes, BUNDLE_COPYRIGHT, () -> { final String year = project.getInceptionYear(); return year == null ? null : String.format("Copyright %s (c) %s. All rights reserved.", project.getOrganization().getName(), year); }); addEntry(attributes, REQUIRE_CAPABILITY, () -> { // https://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html final String[] version = System.getProperty("java.version").split("\\."); return String.format("osgi.ee;filter:=(&(osgi.ee=JavaSE)(version>=%s.%s))", version[0], version[1]); }); final String version = attributes.getValue(BUNDLE_VERSION); if (version != null) { attributes.putValue(BUNDLE_VERSION, verify(version)); } else { addEntry(attributes, BUNDLE_VERSION, DEFAULT_BUNDLE_VERSION); } final RegexBasedInterpolator interpolator = new RegexBasedInterpolator(); final List<String> prefixes = Collections.singletonList("project."); interpolator.addValueSource(new PropertiesBasedValueSource(System.getProperties())); interpolator.addValueSource(new PrefixedPropertiesValueSource(prefixes, project.getProperties(), true)); interpolator.addValueSource(new PrefixedObjectValueSource(prefixes, project.getModel(), true)); final RecursionInterceptor interceptor = new PrefixAwareRecursionInterceptor(prefixes, true); interpolator.setCacheAnswers(true); interpolator.setReusePatterns(true); interpolator.addPostProcessor((ignored, value) -> verify((String) value)); try { interpolateHeaders(attributes, interpolator, interceptor, EXPORT_PACKAGE, IMPORT_PACKAGE, DYNAMICIMPORT_PACKAGE, FRAGMENT_HOST, REQUIRE_BUNDLE, BUNDLE_NATIVECODE); } catch (final InterpolationException e) { throw new IllegalStateException(e); } final Collection<Artifact> artifacts = dependencies.compiler(); // if embedding project dependencies, see if Fluid Tools composition is included and if so, add a bundle activator to bootstrap the system. if (!artifacts.isEmpty()) { try { // create a class loader that sees the project's compile-time dependencies final Set<URL> urls = new HashSet<>(); final String skippedId = project.getArtifact().getId(); for (final Artifact dependency : artifacts) { // we don't need the project artifact and don't want to prevent the caller from overwriting it by locking the file... if (!skippedId.equals(dependency.getId())) { urls.add(dependency.getFile().toURI().toURL()); } } final Method method = Methods.get(BootstrapDiscovery.class, BootstrapDiscovery::activator)[0]; urls.add((Archives.containing(BootstrapDiscovery.class))); urls.add((Archives.containing(BootstrapDiscoveryImpl.class))); urls.add((Archives.containing(ComponentContainer.class))); final String activator = isolate(null, urls, BootstrapDiscoveryImpl.class, method); if (activator != null) { addEntry(attributes, BUNDLE_ACTIVATOR, activator); } if (log.active()) { final String value = attributes.getValue(BUNDLE_ACTIVATOR); log.detail("Bundle activator: %s", value == null ? "none" : value.equals(BundleBootstrap.class.getName()) ? "built in" : value); } } catch (final ClassNotFoundException e) { // that's OK } catch (final Exception e) { throw new IllegalStateException(e); } } return new OsgiLocalPermissions(policy, artifacts, attributes.getValue(DYNAMICIMPORT_PACKAGE), attributes.getValue(IMPORT_PACKAGE), attributes.getValue(EXPORT_PACKAGE)); }
From source file:org.fusesource.mvnplugins.bundlesummary.SummaryMojo.java
License:Apache License
public void execute() throws MojoExecutionException, MojoFailureException { // symbolicName:version -> metadata Map<String, BundleMetadata> bundles = new TreeMap<String, BundleMetadata>(); // imported package without version -> map(version -> List<BundleMetadata>) Map<String, Map<String, Set<BundleMetadata>>> imports = new TreeMap<String, Map<String, Set<BundleMetadata>>>(); // exported package without version -> map(version -> List<BundleMetadata>) Map<String, Map<String, Set<BundleMetadata>>> exports = new TreeMap<String, Map<String, Set<BundleMetadata>>>(); getLog().info("Gathering metadata of reactor's bundles (" + session.getProjects().size() + " artifacts)"); for (MavenProject project : session.getProjects()) { Artifact artifact = project.getArtifact(); if (artifact == null || !"bundle".equals(artifact.getType())) { continue; }/*from w ww . j a v a 2 s . c o m*/ if (getLog().isDebugEnabled()) { getLog().debug("Verifying bundle " + artifact.getArtifactId()); } File bundle = artifact.getFile(); if (bundle == null) { getLog().info("No file for artifact " + artifact.getArtifactId()); continue; } JarFile jar = null; try { jar = new JarFile(bundle); Manifest m = jar.getManifest(); if (m == null || m.getMainAttributes() == null) { continue; } Attributes mainAttributes = m.getMainAttributes(); String symbolicName = mainAttributes.getValue("Bundle-SymbolicName"); if (symbolicName.contains(";")) { // to remove ";blueprint.graceperiod:=false" symbolicName = symbolicName.substring(0, symbolicName.indexOf(';')); } String version = mainAttributes.getValue("Bundle-Version"); String exportsInfo = mainAttributes.getValue("Export-Package"); String importsInfo = mainAttributes.getValue("Import-Package"); String reqs = mainAttributes.getValue("Require-Capability"); String provides = mainAttributes.getValue("Provide-Capability"); String key = String.format("%s:%s", symbolicName, version); BundleMetadata metadata = new BundleMetadata(); bundles.put(key, metadata); metadata.setSymbolicName(symbolicName); metadata.setVersion(version); // Import-Package Parameters importParameters = OSGiHeader.parseHeader(importsInfo); for (String packageName : importParameters.keySet()) { String packageVersion = importParameters.get(packageName).getVersion(); if (packageVersion == null) { packageVersion = ""; } PackageImport packageImport = new PackageImport(packageName, packageVersion); packageImport.setOtherAttributes(importParameters.get(packageName)); metadata.getImports().add(packageImport); if (!imports.containsKey(packageName)) { imports.put(packageName, new TreeMap<String, Set<BundleMetadata>>()); } if (!imports.get(packageName).containsKey(packageVersion)) { imports.get(packageName).put(packageVersion, new TreeSet<BundleMetadata>()); } imports.get(packageName).get(packageVersion).add(metadata); } // Export-Package Parameters exportParameters = OSGiHeader.parseHeader(exportsInfo); for (String packageName : exportParameters.keySet()) { String packageVersion = exportParameters.get(packageName).getVersion(); if (packageVersion == null) { packageVersion = ""; } PackageExport packageExport = new PackageExport(packageName, packageVersion); packageExport.setOtherAttributes(exportParameters.get(packageName)); metadata.getExports().add(packageExport); if (!exports.containsKey(packageName)) { exports.put(packageName, new TreeMap<String, Set<BundleMetadata>>()); } if (!exports.get(packageName).containsKey(packageVersion)) { exports.get(packageName).put(packageVersion, new TreeSet<BundleMetadata>()); } exports.get(packageName).get(packageVersion).add(metadata); } // private packages - all found packages, which are not exported for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); if (entry.getName() != null && entry.getName().endsWith(".class")) { String packageName = entry.getName().substring(0, entry.getName().lastIndexOf("/")); packageName = packageName.replaceAll("/", "."); if (!exports.containsKey(packageName)) { metadata.getPrivatePackages().add(packageName); } } } // Provide-Capability/Require-Capability Parameters reqsParameters = OSGiHeader.parseHeader(reqs); for (String capabilityName : reqsParameters.keySet()) { Capability capability = new Capability(capabilityName); capability.setOtherAttributes(exportParameters.get(capabilityName)); metadata.getRequiredCapabilities().add(capability); // TODO: report on matching reqs/provides to resolve conflicts } Parameters providesParameters = OSGiHeader.parseHeader(provides); for (String capabilityName : providesParameters.keySet()) { Capability capability = new Capability(capabilityName); capability.setOtherAttributes(exportParameters.get(capabilityName)); metadata.getProvidedCapabilities().add(capability); // TODO: report on matching reqs/provides to resolve conflicts } } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } } } // report & verification time getLog().info("Verifying metadata of reactor's bundles"); Writer writer = null; try { writer = new OutputStreamWriter(new FileOutputStream(this.xmlReport), "UTF-8"); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<?xml-stylesheet type=\"text/xsl\" href=\"bundle-report.xslt\"?>\n"); writer.write("<bundle-report xmlns=\"http://fabric8.io/bundle-report\">\n"); writer.write(" <bundles>\n"); for (String id : bundles.keySet()) { BundleMetadata bm = bundles.get(id); writer.write(" <bundle symbolic-name=\"" + bm.getSymbolicName() + "\" version=\"" + bm.getVersion() + "\">\n"); writer.write(" <imports>\n"); for (PackageImport pi : bm.getImports()) { writer.write(" <import package=\"" + pi.getPackageName() + "\" version=\"" + pi.getVersion() + "\" />\n"); } writer.write(" </imports>\n"); writer.write(" <exports>\n"); for (PackageExport pe : bm.getExports()) { writer.write(" <export package=\"" + pe.getPackageName() + "\" version=\"" + pe.getVersion() + "\" />\n"); } writer.write(" </exports>\n"); writer.write(" <privates>\n"); for (String p : bm.getPrivatePackages()) { writer.write(" <private package=\"" + p + "\" />\n"); } writer.write(" </privates>\n"); writer.write(" <provided-capabilities>\n"); for (Capability c : bm.getProvidedCapabilities()) { writer.write(" <capability name=\"" + c.getName() + "\" />\n"); } writer.write(" </provided-capabilities>\n"); writer.write(" <required-capabilities>\n"); for (Capability c : bm.getRequiredCapabilities()) { writer.write(" <capability name=\"" + c.getName() + "\" />\n"); } writer.write(" </required-capabilities>\n"); writer.write(" </bundle>\n"); } writer.write(" </bundles>\n"); writer.write(" <imports>\n"); // for imports we should have no imports with different versions/version ranges importInformation(imports, writer); writer.write(" </imports>\n"); writer.write(" <exports>\n"); // for exports we should have only one bundle which exports any symbolicName:version to avoid split-packages exportInformation(exports, writer); writer.write(" </exports>\n"); // are there any conflicts left? if (imports.size() > 0) { writer.write(" <import-conflicts>\n"); importInformation(imports, writer); writer.write(" </import-conflicts>\n"); } if (exports.size() > 0) { writer.write(" <export-conflicts>\n"); exportInformation(exports, writer); writer.write(" </export-conflicts>\n"); } writer.write("</bundle-report>\n"); FileOutputStream fos = new FileOutputStream(this.stylesheet); IOUtil.copy(getClass().getResourceAsStream("/bundle-report.xslt"), fos); fos.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } } }
From source file:org.grails.maven.plugin.AbstractGrailsMojo.java
License:Apache License
/** * Resolves the given Maven artifact (by getting its transitive dependencies and eliminating conflicts) against * the supplied list of dependencies./*from w ww.java 2s .co m*/ * @param artifact The artifact to be resolved. * @param dependencies The list of dependencies for the "project" (to aid with conflict resolution). * @return The resolved set of artifacts from the given artifact. This includes the artifact itself AND its transitive artifacts. * @throws MojoExecutionException if an error occurs while attempting to resolve the artifact. */ @SuppressWarnings("unchecked") private Set<Artifact> resolveDependenciesToArtifacts(final Artifact artifact, final List<Dependency> dependencies) throws MojoExecutionException { try { final MavenProject project = this.projectBuilder.buildFromRepository(artifact, this.remoteRepositories, this.localRepository); //make Artifacts of all the dependencies final Set<Artifact> artifacts = MavenMetadataSource.createArtifacts(this.artifactFactory, dependencies, null, null, null); final ArtifactResolutionResult result = artifactCollector.collect(artifacts, project.getArtifact(), this.localRepository, this.remoteRepositories, this.artifactMetadataSource, null, Collections.EMPTY_LIST); artifacts.addAll(result.getArtifacts()); //not forgetting the Artifact of the project itself artifacts.add(project.getArtifact()); //resolve all dependencies transitively to obtain a comprehensive list of assemblies for (final Iterator<Artifact> iter = artifacts.iterator(); iter.hasNext();) { final Artifact currentArtifact = iter.next(); if (!currentArtifact.getArtifactId().equals("tools") && !currentArtifact.getGroupId().equals("com.sun")) { this.artifactResolver.resolve(currentArtifact, this.remoteRepositories, this.localRepository); } } return artifacts; } catch (final Exception ex) { throw new MojoExecutionException("Encountered problems resolving dependencies of the executable " + "in preparation for its execution.", ex); } }
From source file:org.guvnor.ala.build.maven.executor.MavenProjectConfigExecutor.java
License:Apache License
@Override public Optional<ProjectConfig> apply(final Source source, final MavenProjectConfig mavenProjectConfig) { final Path projectRoot = source.getPath().resolve(mavenProjectConfig.getProjectDir()); final InputStream pomStream = Files.newInputStream(projectRoot.resolve("pom.xml")); final MavenProject project = MavenProjectLoader.parseMavenPom(pomStream); final Collection<PlugIn> buildPlugins = extractPlugins(project); final String expectedBinary = project.getArtifact().getArtifactId() + "-" + project.getArtifact().getVersion() + "." + calculateExtension(project.getArtifact().getType()); final String _tempDir = mavenProjectConfig.getProjectTempDir().trim(); final RepositoryVisitor repositoryVisitor; if (_tempDir.isEmpty()) { repositoryVisitor = new RepositoryVisitor(projectRoot, project.getName()); } else {//from w w w . j a va2 s. c o m repositoryVisitor = new RepositoryVisitor(projectRoot, _tempDir, mavenProjectConfig.recreateTempDir()); } final org.guvnor.ala.build.maven.model.MavenProject mavenProject = new MavenProjectImpl(project.getId(), project.getArtifact().getType(), project.getName(), expectedBinary, source.getPath(), source.getPath().resolve(mavenProjectConfig.getProjectDir()), source.getPath().resolve("target").resolve(expectedBinary).toAbsolutePath(), repositoryVisitor.getRoot().getAbsolutePath(), buildPlugins); sourceRegistry.registerProject(source, mavenProject); return Optional.of(mavenProject); }
From source file:org.hardisonbrewing.maven.cxx.flex.PropertiesService.java
License:Open Source License
public static final String getFlexPropertiesPath() { MavenProject project = JoJoMojo.getMojo().getProject(); Artifact artifact = project.getArtifact(); StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(TargetDirectoryService.getTargetDirectoryPath()); stringBuffer.append(File.separator); stringBuffer.append(artifact.getArtifactId()); stringBuffer.append(".flex.properties"); return stringBuffer.toString(); }
From source file:org.hardisonbrewing.maven.cxx.generic.PackageMojo.java
License:Open Source License
@Override public final void execute() throws MojoExecutionException, MojoFailureException { File src = new File(TargetDirectoryService.getTempPackagePath()); File dest = new File(TargetDirectoryService.getTempPackagePath() + ".zip"); getLog().info("Archiving " + src + " to " + dest); try {//from w w w.j ava 2 s . com ArchiveService.archive(src, dest); } catch (ArchiverException e) { throw new IllegalStateException(e); } MavenProject project = getProject(); if (classifier == null) { project.getArtifact().setFile(dest); } else { projectHelper.attachArtifact(project, dest, classifier); } }
From source file:org.hardisonbrewing.maven.cxx.msbuild.PackageMojo.java
License:Open Source License
@Override public final void execute() throws MojoExecutionException, MojoFailureException { File file;//from w w w. j ava2s . co m if (!PropertiesService.hasXapOutput()) { StringBuffer filePath = new StringBuffer(); filePath.append(TargetDirectoryService.getBinDirectoryPath()); filePath.append(File.separator); filePath.append(PropertiesService.getBuildSetting(MSBuildService.BUILD_ASSEMBLY_NAME)); filePath.append(".dll"); file = new File(filePath.toString()); } else { StringBuffer filePath = new StringBuffer(); filePath.append(TargetDirectoryService.getBinDirectoryPath()); filePath.append(File.separator); filePath.append(PropertiesService.getBuildSetting(MSBuildService.BUILD_XAP_FILENAME)); file = new File(filePath.toString()); } MavenProject project = getProject(); Artifact artifact = project.getArtifact(); MSBuildArtifactHandler artifactHandler = new MSBuildArtifactHandler(artifact.getArtifactHandler()); artifactHandler.setExtension(FileUtils.extension(file.getName())); artifact.setArtifactHandler(artifactHandler); if (classifier == null) { project.getArtifact().setFile(file); } else { projectHelper.attachArtifact(project, file, classifier); } }