Example usage for org.apache.maven.artifact ArtifactUtils key

List of usage examples for org.apache.maven.artifact ArtifactUtils key

Introduction

In this page you can find the example usage for org.apache.maven.artifact ArtifactUtils key.

Prototype

public static String key(Artifact artifact) 

Source Link

Usage

From source file:com.github.s4u.plugins.PGPVerifyMojo.java

License:Apache License

private boolean verifyPGPSignature(Artifact artifact, File artifactFile, File signatureFile)
        throws MojoFailureException {

    final Map<Integer, String> weakSignatures = ImmutableMap.<Integer, String>builder().put(1, "MD5")
            .put(4, "DOUBLE_SHA").put(5, "MD2").put(6, "TIGER_192").put(7, "HAVAL_5_160").put(11, "SHA224")
            .build();//from   w w w  .j a v  a 2  s  . co  m

    getLog().debug("Artifact file: " + artifactFile);
    getLog().debug("Artifact sign: " + signatureFile);

    try {
        InputStream sigInputStream = PGPUtil.getDecoderStream(new FileInputStream(signatureFile));
        PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(sigInputStream,
                new BcKeyFingerprintCalculator());
        PGPSignatureList sigList = (PGPSignatureList) pgpObjectFactory.nextObject();
        if (sigList == null) {
            throw new MojoFailureException("Invalid signature file: " + signatureFile);
        }
        PGPSignature pgpSignature = sigList.get(0);

        PGPPublicKey publicKey = pgpKeysCache.getKey(pgpSignature.getKeyID());

        if (!keysMap.isValidKey(artifact, publicKey)) {
            String msg = String.format("%s=0x%X", ArtifactUtils.key(artifact), publicKey.getKeyID());
            String keyUrl = pgpKeysCache.getUrlForShowKey(publicKey.getKeyID());
            getLog().error(String.format("Not allowed artifact %s and keyID:\n\t%s\n\t%s\n", artifact.getId(),
                    msg, keyUrl));
            return false;
        }

        pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);

        try (InputStream inArtifact = new BufferedInputStream(new FileInputStream(artifactFile))) {

            int t;
            while ((t = inArtifact.read()) >= 0) {
                pgpSignature.update((byte) t);
            }
        }

        String msgFormat = "%s PGP Signature %s\n       KeyId: 0x%X UserIds: %s";
        if (pgpSignature.verify()) {
            getLog().info(String.format(msgFormat, artifact.getId(), "OK", publicKey.getKeyID(),
                    Lists.newArrayList(publicKey.getUserIDs())));
            if (weakSignatures.containsKey(pgpSignature.getHashAlgorithm())) {
                if (failWeakSignature) {
                    getLog().error("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                    throw new MojoFailureException("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                } else {
                    getLog().warn("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                }
            }
            return true;
        } else {
            getLog().warn(String.format(msgFormat, artifact.getId(), "ERROR", publicKey.getKeyID(),
                    Lists.newArrayList(publicKey.getUserIDs())));
            getLog().warn(artifactFile.toString());
            getLog().warn(signatureFile.toString());
            return false;
        }

    } catch (IOException | PGPException e) {
        throw new MojoFailureException(e.getMessage(), e);
    }
}

From source file:com.mcleodmoores.mvn.natives.UnpackDependenciesMojo.java

License:Open Source License

private InputStream open(final Artifact artifact) throws MojoFailureException {
    try {//from   www .j  av a2s  .  c  om
        return new FileInputStream(artifact.getFile());
    } catch (final IOException e) {
        throw new MojoFailureException("Can't read from artifact " + ArtifactUtils.key(artifact));
    }
}

From source file:com.mcleodmoores.mvn.natives.UnpackDependenciesMojo.java

License:Open Source License

private void check(final Artifact artifact, final Boolean result) throws MojoFailureException {
    if (result != Boolean.TRUE) {
        throw new MojoFailureException("Error unpacking " + ArtifactUtils.key(artifact));
    }//  www  .j  a v  a  2  s  .c  o  m
}

From source file:com.mcleodmoores.mvn.natives.UnpackDependenciesMojo.java

License:Open Source License

private void gatherNames(final Artifact artifact, final Map<String, Set<Artifact>> names)
        throws MojoFailureException {
    getLog().debug("Scanning " + ArtifactUtils.key(artifact));
    check(artifact, (new IOCallback<InputStream, Boolean>(open(artifact)) {

        @Override/*from w w w  .j  ava2  s.  c  o  m*/
        protected Boolean apply(final InputStream input) throws IOException {
            final ZipInputStream zip = new ZipInputStream(new BufferedInputStream(input));
            ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                gatherName(artifact, entry.getName(), names);
            }
            return Boolean.TRUE;
        }

    }).call(new MojoLoggingErrorCallback(this)));
}

From source file:com.mcleodmoores.mvn.natives.UnpackDependenciesMojo.java

License:Open Source License

private void unpack(final Artifact artifact, final Map<String, Set<Artifact>> names, final File targetDir)
        throws MojoFailureException {
    getLog().info("Unpacking " + ArtifactUtils.key(artifact));
    final IOExceptionHandler errorLog = new MojoLoggingErrorCallback(this);
    check(artifact, (new IOCallback<InputStream, Boolean>(open(artifact)) {

        @Override/*from  ww  w  . j  ava2  s . co m*/
        protected Boolean apply(final InputStream input) throws IOException {
            final byte[] buffer = new byte[4096];
            final ZipInputStream zip = new ZipInputStream(new BufferedInputStream(input));
            ZipEntry entry;
            while ((entry = zip.getNextEntry()) != null) {
                final String dest = createUniqueName(artifact, entry.getName(), names.get(entry.getName()));
                getLog().debug("Writing " + entry.getName() + " as " + dest);
                File targetFile = targetDir;
                for (final String component : dest.split("/")) {
                    targetFile.mkdir();
                    targetFile = new File(targetFile, component);
                }
                targetFile.getParentFile().mkdirs();
                if ((new IOCallback<OutputStream, Boolean>(getOutputStreams().open(targetFile)) {

                    @Override
                    protected Boolean apply(final OutputStream output) throws IOException {
                        int bytes;
                        while ((bytes = zip.read(buffer, 0, buffer.length)) > 0) {
                            output.write(buffer, 0, bytes);
                        }
                        output.close();
                        return Boolean.TRUE;
                    }

                }).call(errorLog) != Boolean.TRUE) {
                    return Boolean.FALSE;
                }
            }
            return Boolean.TRUE;
        }

    }).call(errorLog));
}

From source file:org.arakhne.maven.plugins.tagreplacer.AbstractReplaceMojo.java

License:Open Source License

/**
 * Replace the Javadoc tags in the given file.
 * //from   ww w .j  ava2  s  .co  m
 * @param sourceFile
 *            is the name of the file to read out. It may be <code>null</code>
 * @param targetFile
 *            is the name of the file to write in. It cannot be <code>null</code>
 * @param replacementType
 *            is the type of replacement to be done.
 * @param classpath
 *            are the directories from which the file is extracted.
 * @param detectEncoding
 *            when <code>true</code> the encoding of the file will be detected and preserved. When <code>false</code> the encoding may be loose.
 * @throws MojoExecutionException
 * @see #replaceInFileBuffered(File, File, ReplacementType, File[], boolean)
 */
protected synchronized void replaceInFile(File sourceFile, File targetFile, ReplacementType replacementType,
        File[] classpath, boolean detectEncoding) throws MojoExecutionException {
    File outputFile, inputFile;
    assert (targetFile != null);

    if (sourceFile == null) {
        inputFile = targetFile;
        outputFile = new File(targetFile.getAbsolutePath() + ".maven.tmp"); //$NON-NLS-1$
    } else {
        inputFile = sourceFile;
        outputFile = targetFile;
    }

    BuildContext buildContext = getBuildContext();
    buildContext.removeMessages(sourceFile);
    buildContext.removeMessages(targetFile);

    ExtendedArtifact artifact = searchArtifact(inputFile);

    String filename = removePathPrefix(getBaseDirectory(), inputFile);

    String shortFilename = null;
    for (int i = 0; shortFilename == null && i < classpath.length; ++i) {
        if (inputFile.getAbsolutePath().startsWith(classpath[i].getAbsolutePath())) {
            shortFilename = removePathPrefix(classpath[i], inputFile);
        }
    }

    if (artifact != null) {
        getLog().debug("Replacing in " + filename + " with artifact " + //$NON-NLS-1$ //$NON-NLS-2$
                ArtifactUtils.key(artifact));
    } else {
        getLog().debug("Replacing in " + filename + " without artifact"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    try {
        outputFile.getParentFile().mkdirs();
        Reader r = null;

        Charset charset = null;

        if (detectEncoding) {
            charset = detectEncoding(inputFile);
        }

        if (charset == null)
            charset = Charset.defaultCharset();

        getLog().debug("Copying file '" //$NON-NLS-1$
                + inputFile.getName() + "' with '" //$NON-NLS-1$
                + charset.displayName() + "' encoding"); //$NON-NLS-1$

        FileInputStream fis = new FileInputStream(inputFile);
        ReadableByteChannel channel = Channels.newChannel(fis);
        try {
            r = Channels.newReader(channel, charset.newDecoder(), -1);

            if (r == null) {
                r = new FileReader(inputFile);
            }

            BufferedReader br = new BufferedReader(r);
            FileOutputStream fos = new FileOutputStream(outputFile);
            WritableByteChannel wChannel = Channels.newChannel(fos);
            Writer w = Channels.newWriter(wChannel, charset.newEncoder(), -1);
            try {
                String line;
                int nLine = 1;

                while ((line = br.readLine()) != null) {
                    line = replaceInString(inputFile, nLine, shortFilename, artifact, line, replacementType);
                    w.write(line);
                    w.write("\n"); //$NON-NLS-1$
                    ++nLine;
                }
                w.flush();
            } finally {
                w.close();
                wChannel.close();
                fos.close();
                br.close();
            }
        } finally {
            if (r != null)
                r.close();
            channel.close();
            fis.close();
        }

        if (sourceFile == null) {
            fileCopy(outputFile, targetFile);
            outputFile.delete();
            buildContext.refresh(outputFile.getParentFile());
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    } finally {
        if (sourceFile == null && outputFile.exists()) {
            outputFile.delete();
            buildContext.refresh(outputFile.getParentFile());
        } else if (outputFile.exists()) {
            buildContext.refresh(outputFile);
        }
    }
}

From source file:org.debian.dependency.sources.JavaSourcesJarSourceRetrieval.java

License:Apache License

@Override
public String getSourceDirname(final Artifact artifact, final MavenSession session)
        throws SourceRetrievalException {
    return ArtifactUtils.key(artifact);
}

From source file:org.debian.dependency.sources.SCMSourceRetrieval.java

License:Apache License

@Override
public String getSourceDirname(final Artifact artifact, final MavenSession session)
        throws SourceRetrievalException {
    MavenProject project = findProjectRoot(constructProject(artifact, session));
    return ArtifactUtils.key(project.getArtifact());
}

From source file:org.jszip.maven.RunMojo.java

License:Apache License

private void addCssEngineResources(MavenProject project, List<MavenProject> reactorProjects, Mapping[] mappings,
        List<Resource> _resources) throws MojoExecutionException, IOException {
    List<PseudoFileSystem.Layer> layers = new ArrayList<PseudoFileSystem.Layer>();
    layers.add(new PseudoFileSystem.FileLayer("/virtual", warSourceDirectory));
    FilterArtifacts filter = new FilterArtifacts();

    filter.addFilter(new ProjectTransitivityFilter(project.getDependencyArtifacts(), false));

    filter.addFilter(new ScopeFilter("runtime", ""));

    filter.addFilter(new TypeFilter(JSZIP_TYPE, ""));

    // start with all artifacts.
    Set<Artifact> artifacts = project.getArtifacts();

    // perform filtering
    try {/*from   w  ww .  j  a  v  a 2 s . c om*/
        artifacts = filter.filter(artifacts);
    } catch (ArtifactFilterException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

    for (Artifact artifact : artifacts) {
        String path = Mapping.getArtifactPath(mappings, artifact);
        getLog().info("Adding " + ArtifactUtils.key(artifact) + " to virtual filesystem");
        File file = artifact.getFile();
        if (file.isDirectory()) {
            MavenProject fromReactor = findProject(reactorProjects, artifact);
            if (fromReactor != null) {
                MavenSession session = this.session.clone();
                session.setCurrentProject(fromReactor);
                Plugin plugin = findThisPluginInProject(fromReactor);
                try {
                    // we cheat here and use our version of the plugin... but this is less of a cheat than the only
                    // other way which is via reflection.
                    MojoDescriptor jszipDescriptor = findMojoDescriptor(this.pluginDescriptor, JSZipMojo.class);

                    for (PluginExecution pluginExecution : plugin.getExecutions()) {
                        if (!pluginExecution.getGoals().contains(jszipDescriptor.getGoal())) {
                            continue;
                        }
                        MojoExecution mojoExecution = createMojoExecution(plugin, pluginExecution,
                                jszipDescriptor);
                        JSZipMojo mojo = (JSZipMojo) mavenPluginManager
                                .getConfiguredMojo(org.apache.maven.plugin.Mojo.class, session, mojoExecution);
                        try {
                            File contentDirectory = mojo.getContentDirectory();
                            if (contentDirectory.isDirectory()) {
                                getLog().debug("Merging directory " + contentDirectory + " into " + path);
                                layers.add(new PseudoFileSystem.FileLayer(path, contentDirectory));
                            }
                            File resourcesDirectory = mojo.getResourcesDirectory();
                            if (resourcesDirectory.isDirectory()) {
                                getLog().debug("Merging directory " + contentDirectory + " into " + path);
                                layers.add(new PseudoFileSystem.FileLayer(path, resourcesDirectory));
                            }
                        } finally {
                            mavenPluginManager.releaseMojo(mojo, mojoExecution);
                        }
                    }
                } catch (PluginConfigurationException e) {
                    throw new MojoExecutionException(e.getMessage(), e);
                } catch (PluginContainerException e) {
                    throw new MojoExecutionException(e.getMessage(), e);
                }
            } else {
                throw new MojoExecutionException("Cannot find jzsip artifact: " + artifact.getId());
            }
        } else {
            try {
                getLog().debug("Merging .zip file " + file + " into " + path);
                layers.add(new PseudoFileSystem.ZipLayer(path, file));
            } catch (IOException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }
    }

    final PseudoFileSystem fs = new PseudoFileSystem(layers);

    CssEngine engine = new LessEngine(fs, encoding == null ? "utf-8" : encoding, getLog(), lessCompress,
            customLessScript, showErrorExtracts);

    // look for files to compile

    PseudoDirectoryScanner scanner = new PseudoDirectoryScanner();

    scanner.setFileSystem(fs);

    scanner.setBasedir(fs.getPseudoFile("/virtual"));

    if (lessIncludes != null && !lessIncludes.isEmpty()) {
        scanner.setIncludes(processIncludesExcludes(lessIncludes));
    } else {
        scanner.setIncludes(new String[] { "**/*.less" });
    }

    if (lessExcludes != null && !lessExcludes.isEmpty()) {
        scanner.setExcludes(processIncludesExcludes(lessExcludes));
    } else {
        scanner.setExcludes(new String[0]);
    }

    scanner.scan();

    for (String fileName : new ArrayList<String>(Arrays.asList(scanner.getIncludedFiles()))) {
        final CssEngineResource child = new CssEngineResource(fs, engine, "/virtual/" + fileName,
                new File(webappDirectory, engine.mapName(fileName)));
        final String path = FileUtils.dirname(fileName);
        if (StringUtils.isBlank(path)) {
            _resources.add(
                    new VirtualDirectoryResource(new VirtualDirectoryResource(child, child.getName()), ""));
        } else {
            _resources.add(
                    new VirtualDirectoryResource(new VirtualDirectoryResource(child, child.getName()), path));
        }
    }

    engine = new SassEngine(fs, encoding == null ? "utf-8" : encoding);

    if (sassIncludes != null && !sassIncludes.isEmpty()) {
        scanner.setIncludes(processIncludesExcludes(sassIncludes));
    } else {
        scanner.setIncludes(new String[] { "**/*.sass", "**/*.scss" });
    }

    if (sassExcludes != null && !sassExcludes.isEmpty()) {
        scanner.setExcludes(processIncludesExcludes(sassExcludes));
    } else {
        scanner.setExcludes(new String[] { "**/_*.sass", "**/_*.scss" });
    }

    scanner.scan();

    for (String fileName : new ArrayList<String>(Arrays.asList(scanner.getIncludedFiles()))) {
        final CssEngineResource child = new CssEngineResource(fs, engine, "/virtual/" + fileName,
                new File(webappDirectory, engine.mapName(fileName)));
        final String path = FileUtils.dirname(fileName);
        if (StringUtils.isBlank(path)) {
            _resources.add(
                    new VirtualDirectoryResource(new VirtualDirectoryResource(child, child.getName()), ""));
        } else {
            _resources.add(
                    new VirtualDirectoryResource(new VirtualDirectoryResource(child, child.getName()), path));
        }
    }

}

From source file:org.jszip.maven.UnpackMojo.java

License:Apache License

/**
 * @see org.apache.maven.plugin.Mojo#execute()
 *//*  w w  w  . ja  v  a 2s  .  co m*/
public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("Starting unpack into " + webappDirectory);
    FilterArtifacts filter = new FilterArtifacts();

    filter.addFilter(new ProjectTransitivityFilter(project.getDependencyArtifacts(), false));

    filter.addFilter(new ScopeFilter("runtime", ""));

    filter.addFilter(new TypeFilter(JSZIP_TYPE, ""));

    // start with all artifacts.
    Set<Artifact> artifacts = project.getArtifacts();

    // perform filtering
    try {
        artifacts = filter.filter(artifacts);
    } catch (ArtifactFilterException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

    String includes;
    String excludes;
    if (unpackIncludes != null && !unpackIncludes.isEmpty()) {
        includes = StringUtils.join(unpackIncludes.iterator(), ",");
    } else {
        includes = null;
    }

    if (unpackExcludes != null && !unpackExcludes.isEmpty()) {
        excludes = StringUtils.join(unpackExcludes.iterator(), ",");
    } else {
        excludes = "META-INF/maven/**/pom.*,package.json,**/*.less,**/*.sass,**/*.scss";
    }

    for (Artifact artifact : artifacts) {
        String path = getPath(artifact);
        File artifactDirectory;
        if (StringUtils.isBlank(path)) {
            getLog().info("Unpacking " + ArtifactUtils.key(artifact));
            artifactDirectory = webappDirectory;
        } else {
            getLog().info("Unpacking " + ArtifactUtils.key(artifact) + " at path " + path);
            artifactDirectory = new File(webappDirectory, path);
        }
        unpack(artifact, artifactDirectory, includes, excludes);
    }
}