Java Code Examples for org.apache.maven.artifact.Artifact#getFile()

The following examples show how to use org.apache.maven.artifact.Artifact#getFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ShrinkWrapFatJarPackageService.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void addDependencies(PackageConfig config, Collection<DependencySet> dependencies, JavaArchive jar) {
    Log logger = config.getMojo().getLog();
    for (DependencySet ds : dependencies) {
        ScopeFilter scopeFilter = ServiceUtils.newScopeFilter(ds.getScope());
        ArtifactFilter filter = new ArtifactIncludeFilterTransformer().transform(scopeFilter);
        Set<Artifact> artifacts = ServiceUtils.filterArtifacts(config.getArtifacts(),
            ds.getIncludes(), ds.getExcludes(),
            ds.isUseTransitiveDependencies(), logger, filter);

        for (Artifact artifact : artifacts) {
            File file = artifact.getFile();
            if (file.isFile()) {
                logger.debug("Adding Dependency :" + artifact);
                embedDependency(logger, ds, jar, file);
            } else {
                logger.warn("Cannot embed artifact " + artifact
                    + " - the file does not exist");
            }
        }
    }
}
 
Example 2
Source File: ArtifactsLibraries.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
@Override
public void doWithLibraries(LibraryCallback callback) throws IOException {
    Set<String> duplicates = getDuplicates(artifacts);
    for (Artifact artifact : this.artifacts) {
        LibraryScope scope = SCOPES.get(artifact.getScope());
        if (scope != null && artifact.getFile() != null) {
            String name = getFileName(artifact);
            if (duplicates.contains(name)) {
                this.log.debug(String.format("Duplicate found: %s", name));
                name = artifact.getGroupId() + "-" + name;
                this.log.debug(String.format("Renamed to: %s", name));
            }
            callback.library(new Library(name, artifact.getFile(), scope,
                isUnpackRequired(artifact)));
        }
    }
}
 
Example 3
Source File: ResolveMojoTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
private RepositorySystem newRepositorySystem() {

		RepositorySystem repoSystem = new DefaultRepositorySystem() {
			@Override
			public ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest request )
			throws ArtifactResolutionException {

				ArtifactResult res = new ArtifactResult( request );
				Artifact mavenArtifact = ResolveMojoTest.this.artifactIdToArtifact.get( request.getArtifact().getArtifactId());
				if( mavenArtifact == null )
					throw new ArtifactResolutionException( new ArrayList<ArtifactResult>( 0 ), "Error in test wrapper and settings." );

				org.eclipse.aether.artifact.DefaultArtifact art =
						new org.eclipse.aether.artifact.DefaultArtifact(
								"groupId", "artifactId", "classifier", "extension", "version",
								null, mavenArtifact.getFile());

				res.setArtifact( art );
				return res;
			}
		};

		return repoSystem;
	}
 
Example 4
Source File: AbstractManagementMojo.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
private List<File> getDependencies(Collection<InstallationDependency> artifacts) throws ArtifactNotFoundException, ArtifactResolutionException {
    List<File> list = new ArrayList<File>();
    Iterator<InstallationDependency> it = artifacts.iterator();
    while(it.hasNext()) {
        InstallationDependency dep = it.next();
        Artifact artifact = artifactFactory.createArtifactWithClassifier(
                dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), dep.getType(), null
        );

        artifactResolver.resolve(artifact, remoteRepositories, artifactRepository);
        if(artifact.getFile() == null) {
            getLog().warn("Unable to find file for artifact: "+artifact.getArtifactId());
        }

        list.add(artifact.getFile());
    }
    return list;
}
 
Example 5
Source File: DependencyNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public @Override Action createContextAwareInstance(final Lookup context) {
    return new AbstractAction(BTN_Open_Project()) {
        public @Override void actionPerformed(ActionEvent e) {
            Set<Project> projects = new HashSet<Project>();
            for (Artifact art : context.lookupAll(Artifact.class)) {
                File f = art.getFile();
                if (f != null) {
                    Project p = FileOwnerQuery.getOwner(org.openide.util.Utilities.toURI(f));
                    if (p != null) {
                        projects.add(p);
                    }
                }
            }
            OpenProjects.getDefault().open(projects.toArray(new NbMavenProjectImpl[projects.size()]), false, true);
        }
    };
}
 
Example 6
Source File: FlattenModelResolver.java    From flatten-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ModelSource resolveModel( String groupId, String artifactId, String version )
{
    File pomFile = reactorModelPool.find( groupId, artifactId, version );
    if ( pomFile == null )
    {
        Artifact pomArtifact = this.artifactFactory.createProjectArtifact( groupId, artifactId, version );
        pomArtifact = this.localRepository.find( pomArtifact );
        pomFile = pomArtifact.getFile();
    }

    return new FileModelSource( pomFile );
}
 
Example 7
Source File: MavenEmbedder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static void normalizePath(Artifact a) {
    if (a != null) {
        File f = a.getFile();
        if (f != null) {
            a.setFile(FileUtil.normalizeFile(f));
        }
    }
}
 
Example 8
Source File: ExtensionClassLoaderFactory.java    From nifi-maven with Apache License 2.0 5 votes vote down vote up
private Set<URL> toURLs(final Artifact artifact) throws MojoExecutionException {
    final Set<URL> urls = new HashSet<>();

    final File artifactFile = artifact.getFile();
    if (artifactFile == null) {
        getLog().debug("Attempting to resolve Artifact " + artifact + " because it has no File associated with it");

        final ArtifactResolutionRequest request = new ArtifactResolutionRequest();
        request.setLocalRepository(localRepo);
        request.setArtifact(artifact);

        final ArtifactResolutionResult result = artifactResolver.resolve(request);
        if (!result.isSuccess()) {
            throw new MojoExecutionException("Could not resolve local dependency " + artifact);
        }

        getLog().debug("Resolved Artifact " + artifact + " to " + result.getArtifacts());

        for (final Artifact resolved : result.getArtifacts()) {
            urls.addAll(toURLs(resolved));
        }
    } else {
        try {
            final URL url = artifact.getFile().toURI().toURL();
            getLog().debug("Adding URL " + url + " to ClassLoader");
            urls.add(url);
        } catch (final MalformedURLException mue) {
            throw new MojoExecutionException("Failed to convert File " + artifact.getFile() + " into URL", mue);
        }
    }

    return urls;
}
 
Example 9
Source File: BaratineMojo.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private void addJar(Artifact artifact)
{
  if ("io.baratine".equals(artifact.getGroupId()))
    return;

  File file = artifact.getFile();
  String name = file.getName();

  int lastSlash = name.lastIndexOf(File.separator);

  if (lastSlash > -1)
    name = name.substring(lastSlash + 1);

  this.archiver.addFile(file, "lib/" + name);
}
 
Example 10
Source File: RepositoryMavenCPProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ClassPathImplementation createExecuteCPI(MavenProject project, File binary) {
    List<PathResourceImplementation> items = new ArrayList<PathResourceImplementation>(); 
    items.add(ClassPathSupport.createResource(FileUtil.urlForArchiveOrDir(binary)));
    if (project != null) {
        for (Artifact s : project.getRuntimeArtifacts()) {
            if (s.getFile() == null) continue;
            items.add(ClassPathSupport.createResource(FileUtil.urlForArchiveOrDir(s.getFile())));
        }
    }
    return ClassPathSupport.createClassPathImplementation(items);
}
 
Example 11
Source File: AbstractManagementMojo.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
private File getPortalApplication() throws ArtifactNotFoundException, ArtifactResolutionException  {
    InstallationDependency dep = InstallationDependency.PORTAL;
    Artifact artifact = artifactFactory.createBuildArtifact(
       dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), dep.getType()
    );
    artifactResolver.resolve(artifact, remoteRepositories, artifactRepository);
    return artifact.getFile();
}
 
Example 12
Source File: ArtifactTransformer.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
protected boolean isComponent(final Artifact artifact) {
    final File file = artifact.getFile();
    if (file.isDirectory()) {
        return new File(file, "TALEND-INF/dependencies.txt").exists();
    }
    try (final JarFile jar = new JarFile(file)) {
        return jar.getEntry("TALEND-INF/dependencies.txt") != null;
    } catch (final IOException ioe) {
        return false;
    }
}
 
Example 13
Source File: CapsuleMojo.java    From capsule-maven-plugin with MIT License 5 votes vote down vote up
private void addDependencies(final JarOutputStream jar) throws IOException {

		// go through dependencies
		final Set<Artifact> artifacts = includeTransitiveDep ? includedDependencyArtifacts() : includedDirectDependencyArtifacts();

		for (final Artifact artifact : artifacts) {

			final String scope = artifact.getScope() == null || artifact.getScope().isEmpty() ? "compile" : artifact.getScope();

			boolean optionalMatch = true;
			if (artifact.isOptional()) optionalMatch = includeOptionalDep;

			// check artifact has a file
			if (artifact.getFile() == null)
				warn("\t[Dependency] " + coords(artifact) + "(" + artifact.getScope() + ") file not found, thus will not be added to capsule jar.");

			// ignore capsule jar
			if (artifact.getGroupId().equalsIgnoreCase(CAPSULE_GROUP) && artifact.getArtifactId().equalsIgnoreCase(DEFAULT_CAPSULE_NAME))
				continue;

			// check against requested scopes
			if (
					(includeCompileDep && scope.equals("compile") && optionalMatch) ||
							(includeRuntimeDep && scope.equals("runtime") && optionalMatch) ||
							(includeProvidedDep && scope.equals("provided") && optionalMatch) ||
							(includeSystemDep && scope.equals("system") && optionalMatch) ||
							(includeTestDep && scope.equals("test") && optionalMatch)
					) {
				addToJar(artifact.getFile().getName(), new FileInputStream(artifact.getFile()), jar);
				info("\t[Embedded-Dependency] " + coords(artifact) + "(" + scope + ")");
			} else
				debug("\t[Dependency] " + coords(artifact) + "(" + artifact.getScope() + ") skipped, as it does not match any required scope");
		}
	}
 
Example 14
Source File: AbstractCheckMojo.java    From forbidden-apis with Apache License 2.0 5 votes vote down vote up
private File resolveSignaturesArtifact(SignaturesArtifact signaturesArtifact) throws ArtifactResolutionException, ArtifactNotFoundException {
  final Artifact artifact = signaturesArtifact.createArtifact(artifactFactory);
  artifactResolver.resolve(artifact, this.remoteRepositories, this.localRepository);
  final File f = artifact.getFile();
  // Can this ever be false? Be sure. Found the null check also in other Maven code, so be safe!
  if (f == null) {
    throw new ArtifactNotFoundException("Artifact does not resolve to a file.", artifact);
  }
  return f;
}
 
Example 15
Source File: JApiCmpMojo.java    From japicmp with Apache License 2.0 5 votes vote down vote up
private void setUpClassPathUsingMavenProject(JarArchiveComparatorOptions comparatorOptions, MavenParameters mavenParameters, PluginParameters pluginParameters, ConfigurationVersion configurationVersion) throws MojoFailureException {
	notNull(mavenParameters.getMavenProject(), "Maven parameter mavenProject should be provided by maven container.");
	Set<Artifact> dependencyArtifacts = mavenParameters.getMavenProject().getArtifacts();
	Set<String> classPathEntries = new HashSet<>();
	for (Artifact artifact : dependencyArtifacts) {
		String scope = artifact.getScope();
		if (!"test".equals(scope)) {
			Set<Artifact> artifacts = resolveArtifact(artifact, mavenParameters, false, pluginParameters, configurationVersion);
			for (Artifact resolvedArtifact : artifacts) {
				File resolvedFile = resolvedArtifact.getFile();
				if (resolvedFile != null) {
					String absolutePath = resolvedFile.getAbsolutePath();
					if (!classPathEntries.contains(absolutePath)) {
						if (getLog().isDebugEnabled()) {
							getLog().debug("Adding to classpath: " + absolutePath + "; scope: " + scope);
						}
						classPathEntries.add(absolutePath);
					}
				} else {
					handleMissingArtifactFile(pluginParameters, artifact);
				}
			}
		}
	}
	for (String classPathEntry : classPathEntries) {
		comparatorOptions.getClassPathEntries().add(classPathEntry);
	}
}
 
Example 16
Source File: AbstractCompileMojo.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
private List<File> getClasspath() {
  List<File> classpath = new ArrayList<File>();
  for (Artifact artifact : getClasspathArtifacts()) {
    File file = artifact.getFile();
    if (file != null) {
      classpath.add(file);
    }
  }
  return classpath;
}
 
Example 17
Source File: WebJars.java    From wisdom with Apache License 2.0 4 votes vote down vote up
/**
 * Manage webjars dependencies.
 * <p>
 * This process is executed as follows:
 * <ol>
 * <li>web jars that are also bundles are ignored</li>
 * <li>web jars libraries from a 'provided' dependency (in the 'provided' scope) are copied to the /assets/lib
 * directory.</li>
 * <li>web jars libraries from a 'compile' dependency (in the 'compile' scope) are copied to the application
 * directory.</li>
 * <li>Transitive are also analyzed if enabled (enabled by default).</li>
 * </ol>
 *
 * @param mojo       the mojo
 * @param graph      the dependency graph builder
 * @param transitive whether or not we include the transitive dependencies.
 * @param unpackWebJars whether or not webjars should be extracted to target/webjars
 * @throws java.io.IOException when a web jar cannot be handled correctly
 */
public static void manageWebJars(AbstractWisdomMojo mojo, DependencyGraphBuilder graph,
                                 boolean transitive, boolean unpackWebJars) throws IOException {
    File webjars = new File(mojo.getWisdomRootDirectory(), "assets/libs");
    final File application = new File(mojo.getWisdomRootDirectory(), "application");

    Set<Artifact> artifacts = DependencyCopy.getArtifactsToConsider(mojo, graph, transitive, null);


    for (Artifact artifact : artifacts) {
        if (DependencyCopy.SCOPE_COMPILE.equalsIgnoreCase(artifact.getScope())
                || DependencyCopy.SCOPE_PROVIDED.equalsIgnoreCase(artifact.getScope())) {
            File file = artifact.getFile();

            // Check it's a 'jar file'
            if (!file.getName().endsWith(".jar")) {
                mojo.getLog().debug("Dependency " + file.getName() + " is not a web jar, it's not even a jar file");
                continue;
            }

            // Check that it's a web jar.
            if (!isWebJar(file)) {
                mojo.getLog().debug("Dependency " + file.getName() + " is not a web jar.");
                continue;
            }

            // Check that it's not a bundle.
            if (isBundle(file)) {
                mojo.getLog().debug("Dependency " + file.getName() + " is a web jar, but it's also a bundle, " +
                        "to ignore it.");
                continue;
            }

            // It's a web jar.
            if (DependencyCopy.SCOPE_COMPILE.equalsIgnoreCase(artifact.getScope())) {
                mojo.getLog().info("Copying web jar library " + file.getName() + " to the application directory");
                FileUtils.copyFileToDirectory(file, application);

                // Check whether or not it must be unpacked to target/webjars.
                if (unpackWebJars) {
                    extract(mojo, file, new File(mojo.buildDirectory, "webjars"), true);
                }
                // NOTE: webjars from the 'provided' scope are not unpacked in target/webjars as they are in
                // target/wisdom/assets/libs.
            } else {
                mojo.getLog().info("Extracting web jar libraries from " + file.getName() + " to " + webjars
                        .getAbsolutePath());
                extract(mojo, file, webjars, false);
            }
        }
    }
}
 
Example 18
Source File: ConfigurationMetadataDocumentationMojo.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
public void execute() throws MojoExecutionException {

		File readme = new File(mavenProject.getBasedir(), "README.adoc");
		if (!readme.exists()) {
			getLog().info(String.format("No README.adoc file found in %s, skipping", mavenProject.getBasedir()));
			return;
		}

		Artifact artifact = mavenProject.getArtifact();
		if (artifact.getFile() == null) {
			getLog().info(String.format("Project in %s does not produce a build artifact, skipping", mavenProject.getBasedir()));
			return;
		}

		File tmp = new File(readme.getPath() + ".tmp");
		try (PrintWriter out = new PrintWriter(tmp); BufferedReader reader = new BufferedReader(new FileReader(readme));) {

			String line = null;
			do {
				line = reader.readLine();
				out.println(line);
			}
			while (line != null && !line.startsWith("//tag::configuration-properties[]"));
			if (line == null) {
				getLog().info("No documentation section marker found");
				return;
			}

			ScatteredArchive archive = new ScatteredArchive(mavenProject);
			BootClassLoaderFactory bootClassLoaderFactory = new BootClassLoaderFactory(archive, null);
			ClassLoader classLoader = bootClassLoaderFactory.createClassLoader();
			debug(classLoader);


			List<ConfigurationMetadataProperty> properties = metadataResolver.listProperties(archive, false);
			Collections.sort(properties, new Comparator<ConfigurationMetadataProperty>() {

				@Override
				public int compare(ConfigurationMetadataProperty p1, ConfigurationMetadataProperty p2) {
					return p1.getId().compareTo(p2.getId());
				}
			});

			for (ConfigurationMetadataProperty property : properties) {
				getLog().debug("Documenting " + property.getId());
				out.println(asciidocFor(property, classLoader));
			}

			do {
				line = reader.readLine();
				// drop lines
			}
			while (!line.startsWith("//end::configuration-properties[]"));

			// Copy remaining lines, including //end::configuration-properties[]
			while (line != null) {
				out.println(line);
				line = reader.readLine();
			}
			if (classLoader instanceof Closeable) {
				((Closeable) classLoader).close();
			}
			getLog().info(String.format("Documented %d configuration properties", properties.size()));
			tmp.renameTo(readme);
		}
		catch (Exception e) {
			throw new MojoExecutionException("Error generating documentation", e);
		}
		finally {
			tmp.delete();
		}

	}
 
Example 19
Source File: AbstractJnlpMojo.java    From webstart with MIT License 4 votes vote down vote up
private void processDependency( Artifact artifact )
        throws MojoExecutionException
{
    // TODO: scope handler
    // Include runtime and compile time libraries
    if ( !Artifact.SCOPE_SYSTEM.equals( artifact.getScope() ) &&
            !Artifact.SCOPE_PROVIDED.equals( artifact.getScope() ) &&
            !Artifact.SCOPE_TEST.equals( artifact.getScope() ) )
    {
        String type = artifact.getType();
        if ( "jar".equals( type ) || "ejb-client".equals( type ) )
        {

            boolean mainArtifact = false;
            if ( jnlp.isRequireMainClass() )
            {

                // try to find if this dependency contains the main class
                boolean containsMainClass =
                        getArtifactUtil().artifactContainsClass( artifact, jnlp.getMainClass() );

                if ( containsMainClass )
                {
                    if ( artifactWithMainClass == null )
                    {
                        mainArtifact = true;
                        artifactWithMainClass = artifact;
                        getLog().debug(
                                "Found main jar. Artifact " + artifactWithMainClass + " contains the main class: " +
                                        jnlp.getMainClass() );
                    }
                    else
                    {
                        getLog().warn(
                                "artifact " + artifact + " also contains the main class: " + jnlp.getMainClass() +
                                        ". IGNORED." );
                    }
                }
            }

            if ( skipDependencies && !mainArtifact )
            {
                return;
            }

            // FIXME when signed, we should update the manifest.
            // see http://www.mail-archive.com/[email protected]/msg08081.html
            // and maven1: maven-plugins/jnlp/src/main/org/apache/maven/jnlp/UpdateManifest.java
            // or shouldn't we?  See MOJO-7 comment end of October.
            final File toCopy = artifact.getFile();

            if ( toCopy == null )
            {
                getLog().error( "artifact with no file: " + artifact );
                getLog().error( "artifact download url: " + artifact.getDownloadUrl() );
                getLog().error( "artifact repository: " + artifact.getRepository() );
                getLog().error( "artifact repository: " + artifact.getVersion() );
                throw new IllegalStateException(
                        "artifact " + artifact + " has no matching file, why? Check the logs..." );
            }

            String name =
                    getDependencyFilenameStrategy().getDependencyFilename( artifact, outputJarVersions, isUseUniqueVersions() );

            boolean copied = copyJarAsUnprocessedToDirectoryIfNecessary( toCopy, getLibDirectory(), name );

            if ( copied )
            {

                getModifiedJnlpArtifacts().add( name.substring( 0, name.lastIndexOf( '.' ) ) );

            }

            packagedJnlpArtifacts.add( artifact );

        }
        else
        // FIXME how do we deal with native libs?
        // we should probably identify them and package inside jars that we timestamp like the native lib
        // to avoid repackaging every time. What are the types of the native libs?
        {
            verboseLog( "Skipping artifact of type " + type + " for " + getLibDirectory().getName() );
        }
        // END COPY
    }
    else
    {
        verboseLog( "Skipping artifact of scope " + artifact.getScope() + " for " + getLibDirectory().getName() );
    }
}
 
Example 20
Source File: Utils.java    From usergrid with Apache License 2.0 4 votes vote down vote up
/**
 * Gets all dependency jars of the project specified by 'project' parameter from the local mirror and copies them
 * under targetFolder
 *
 * @param targetFolder The folder which the dependency jars will be copied to
 */
public static void copyArtifactsTo( MavenProject project, String targetFolder )
        throws MojoExecutionException {
    File targetFolderFile = new File( targetFolder );
    for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); ) {
        Artifact artifact = ( Artifact ) it.next();

        File f = artifact.getFile();

        LOG.info( "Artifact {} found.", f.getAbsolutePath() );

        if ( f == null ) {
            throw new MojoExecutionException( "Cannot locate artifact file of " + artifact.getArtifactId() );
        }

        // Check already existing artifacts and replace them if they are of a lower version
        try {

            List<String> existing =
                    FileUtils.getFileNames( targetFolderFile, artifact.getArtifactId() + "-*.jar", null, false );

            if ( existing.size() != 0 ) {
                String version =
                        existing.get( 0 ).split( "(" + artifact.getArtifactId() + "-)" )[1].split( "(.jar)" )[0];
                DefaultArtifactVersion existingVersion = new DefaultArtifactVersion( version );
                DefaultArtifactVersion artifactVersion = new DefaultArtifactVersion( artifact.getVersion() );

                if ( existingVersion.compareTo( artifactVersion ) < 0 ) { // Remove existing version
                    FileUtils.forceDelete( targetFolder + existing.get( 0 ) );
                }
                else {
                    LOG.info( "Artifact " + artifact.getArtifactId() + " with the same or higher " +
                            "version already exists in lib folder, skipping copy" );
                    continue;
                }
            }

            LOG.info( "Copying {} to {}", f.getName(), targetFolder );
            FileUtils.copyFileToDirectory( f.getAbsolutePath(), targetFolder );
        }
        catch ( IOException e ) {
            throw new MojoExecutionException( "Error while copying artifact file of " + artifact.getArtifactId(),
                    e );
        }
    }
}