Example usage for org.apache.maven.artifact Artifact hasClassifier

List of usage examples for org.apache.maven.artifact Artifact hasClassifier

Introduction

In this page you can find the example usage for org.apache.maven.artifact Artifact hasClassifier.

Prototype

boolean hasClassifier();

Source Link

Usage

From source file:br.com.uggeri.maven.builder.mojo.ArtifactUtil.java

public final static String artifactName(Artifact artifact) {
    StringBuilder sb = new StringBuilder();
    sb.append(artifact.getArtifactId()).append('-');
    if (artifact.getVersion().isEmpty()) {
        sb.append(artifact.getBaseVersion());
    } else {/*ww w. j  a va 2 s.  com*/
        sb.append(artifact.getVersion());
    }
    if (artifact.hasClassifier()) {
        sb.append('-').append(artifact.getClassifier());
    }
    sb.append('.').append(artifact.getType());
    return sb.toString();
}

From source file:br.com.uggeri.maven.builder.mojo.ArtifactUtil.java

public final static String artifactPomName(Artifact artifact) {
    StringBuilder sb = new StringBuilder();
    sb.append(artifact.getArtifactId()).append('-');
    if (artifact.getVersion().isEmpty()) {
        sb.append(artifact.getBaseVersion());
    } else {/*  www  . ja  v a 2s.  co m*/
        sb.append(artifact.getVersion());
    }
    if (artifact.hasClassifier()) {
        sb.append('-').append(artifact.getClassifier());
    }
    sb.append(".pom");
    return sb.toString();
}

From source file:com.fizzed.stork.maven.AssemblyMojo.java

public boolean shouldArtifactBeStaged(Artifact a) {
    return !a.hasClassifier() && (a.getType() == null || a.getType().equalsIgnoreCase("jar"));
}

From source file:com.github.batkinson.plugins.PackMojo.java

License:Apache License

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {

    getLog().debug("starting pack");

    Packer packer = Pack200.newPacker();
    Unpacker unpacker = null;//from  w w  w.j a  v a2s . c o  m

    if (normalizeOnly)
        unpacker = Pack200.newUnpacker();

    String type = "jar.pack";
    if (compress)
        type = "jar.pack.gz";

    Map<String, String> packerProps = packer.properties();

    packerProps.put(Packer.EFFORT, effort);
    packerProps.put(Packer.SEGMENT_LIMIT, segmentLimit);
    packerProps.put(Packer.KEEP_FILE_ORDER, keepFileOrder);
    packerProps.put(Packer.MODIFICATION_TIME, modificationTime);
    packerProps.put(Packer.DEFLATE_HINT, deflateHint);

    if (stripCodeAttributes != null) {
        for (String attributeName : stripCodeAttributes) {
            getLog().debug("stripping " + attributeName);
            packerProps.put(Packer.CODE_ATTRIBUTE_PFX + attributeName, Packer.STRIP);
        }
    }

    if (failOnUnknownAttributes)
        packerProps.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR);

    List<Artifact> artifactsToPack = new ArrayList<Artifact>();

    if (processMainArtifact)
        artifactsToPack.add(project.getArtifact());

    if (includeClassifiers != null && !includeClassifiers.isEmpty()) {
        for (Artifact secondaryArtifact : (List<Artifact>) project.getAttachedArtifacts())
            if ("jar".equals(secondaryArtifact.getType()) && secondaryArtifact.hasClassifier()
                    && includeClassifiers.contains(secondaryArtifact.getClassifier()))
                artifactsToPack.add(secondaryArtifact);
    }

    String action = normalizeOnly ? "normalizing" : "packing";

    getLog().info(action + " " + artifactsToPack.size() + " artifacts");

    for (Artifact artifactToPack : artifactsToPack) {

        File origFile = artifactToPack.getFile();
        File packFile = new File(origFile.getAbsolutePath() + ".pack");
        File zipFile = new File(packFile.getAbsolutePath() + ".gz");

        try {
            JarFile jar = new JarFile(origFile);
            FileOutputStream fos = new FileOutputStream(packFile);

            getLog().debug("packing " + origFile + " to " + packFile);
            packer.pack(jar, fos);

            getLog().debug("closing handles ...");
            jar.close();
            fos.close();

            if (normalizeOnly) {
                getLog().debug("unpacking " + packFile + " to " + origFile);
                JarOutputStream origJarStream = new JarOutputStream(new FileOutputStream(origFile));
                unpacker.unpack(packFile, origJarStream);

                getLog().debug("closing handles...");
                origJarStream.close();

                getLog().debug("unpacked file");
            } else {

                Artifact newArtifact = new DefaultArtifact(artifactToPack.getGroupId(),
                        artifactToPack.getArtifactId(), artifactToPack.getVersionRange(),
                        artifactToPack.getScope(), type, artifactToPack.getClassifier(),
                        new DefaultArtifactHandler(type));

                if (compress) {
                    getLog().debug("compressing " + packFile + " to " + zipFile);
                    GZIPOutputStream zipOut = new GZIPOutputStream(new FileOutputStream(zipFile));
                    IOUtil.copy(new FileInputStream(packFile), zipOut);
                    zipOut.close();
                    newArtifact.setFile(zipFile);
                } else {
                    newArtifact.setFile(packFile);
                }

                if (attachPackedArtifacts) {
                    getLog().debug("attaching " + newArtifact);
                    project.addAttachedArtifact(newArtifact);
                }
            }

            getLog().debug("finished " + action + " " + packFile);

        } catch (IOException e) {
            throw new MojoExecutionException("Failed to pack jar.", e);
        }
    }
}

From source file:com.kumuluz.ee.maven.plugin.AbstractPackageMojo.java

License:MIT License

private void renameJars() throws MojoExecutionException {
    try {/*from   w w  w  . ja v a2 s.c o  m*/
        Path sourcePath1 = Paths.get(buildDirectory, finalName + ".jar");

        getLog().info("Repackaging jar: " + sourcePath1.toAbsolutePath());

        if (Files.exists(sourcePath1)) {
            Files.move(sourcePath1, sourcePath1.resolveSibling(finalName + ".jar.original"),
                    StandardCopyOption.REPLACE_EXISTING);
        }

        Path sourcePath2 = Paths.get(buildDirectory, finalName + "-uber.jar");

        if (Files.exists(sourcePath2)) {
            Files.move(sourcePath2, sourcePath2.resolveSibling(finalName + ".jar"),
                    StandardCopyOption.REPLACE_EXISTING);
        }

        List<Artifact> artifacts = project.getAttachedArtifacts();
        for (Artifact artifact : project.getAttachedArtifacts()) {
            if (artifact.hasClassifier() && artifact.getClassifier().equals("uber")) {
                artifacts.remove(artifact);
                break;
            }
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to rename the final build artifact.");
    }
}

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]);//from w  w  w  .jav a 2s.com
            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.ecsec.maven.plugins.AbstractPack200Mojo.java

License:Open Source License

protected List<Artifact> getArtifacts() {
    List<Artifact> artifactList = new ArrayList<>();

    getLog().debug("configuring artifacts to pack");

    if (processMainArtifact) {
        getLog().debug("packing " + project.getArtifact().getFile().getAbsolutePath());
        artifactList.add(project.getArtifact());
    }//  www  .  j  a  v  a2 s . co m

    if (includeClassifiers != null) {
        for (Artifact attachedArtifact : project.getAttachedArtifacts()) {
            getLog().debug(attachedArtifact.getClassifier());
            getLog().debug(attachedArtifact.getType());
            if (("jar".equals(attachedArtifact.getType())
                    || "signed-packed-jar".equals(attachedArtifact.getType()))
                    && attachedArtifact.hasClassifier()
                    && includeClassifiers.contains(attachedArtifact.getClassifier())) {
                getLog().debug("packing " + attachedArtifact.getFile().getAbsolutePath());
                artifactList.add(attachedArtifact);
            }
        }
    }

    getLog().debug("finished configuring artifacts to pack");

    return artifactList;
}

From source file:fr.opensagres.tools.GoogleCodeUploadMojo.java

License:Apache License

/**
 * Uploads the contents of the file {@link #fileName} to the project's
 * Google Code upload url. Performs the basic http authentication required
 * by Google Code.//from w  ww  .  j  av a2s.  com
 */
private void upload() throws IOException {
    if (targetFileName == null) {

        if (classifier != null) {
            List attachedArtifacts = project.getAttachedArtifacts();
            for (Iterator iterator = attachedArtifacts.iterator(); iterator.hasNext();) {
                Artifact artifact = (Artifact) iterator.next();
                if (artifact.hasClassifier()) {
                    if (classifier.equals(artifact.getClassifier())) {
                        targetFileName = artifact.getFile().getAbsolutePath();
                    }
                }
            }
        }

    }
    if (targetFileName == null) {
        log("targetFileName is null, stopping... ");
    } else {
        System.clearProperty("javax.net.ssl.trustStoreProvider"); // fixes
        // open-jdk-issue
        System.clearProperty("javax.net.ssl.trustStoreType");

        final String BOUNDARY = "CowMooCowMooCowCowCow";
        URL url = createUploadURL();

        log("The upload URL is " + url);

        InputStream in = new BufferedInputStream(new FileInputStream(targetFileName));

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        if (this.isIgnoreSslCertificateHostname()) {
            if (conn instanceof HttpsURLConnection) {
                HttpsURLConnection secure = (HttpsURLConnection) conn;
                secure.setHostnameVerifier(new HostnameVerifier() {

                    public boolean verify(String hostname, SSLSession session) {
                        boolean result = true;
                        log("SSL verification ignored for current session and hostname: " + hostname);
                        return result;
                    }
                });
            }
        }
        Server server = settings.getServer("code.google.com");
        String userName = server.getUsername();
        String password = server.getPassword();

        conn.setDoOutput(true);
        conn.setRequestProperty("Authorization", "Basic " + createAuthToken(userName, password));
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        conn.setRequestProperty("User-Agent", "Google Code Upload Mojo 1.0");

        log("Attempting to connect (username is " + userName + ")...");
        conn.connect();

        log("Sending request parameters...");
        OutputStream out = conn.getOutputStream();
        sendLine(out, "--" + BOUNDARY);
        sendLine(out, "content-disposition: form-data; name=\"summary\"");
        sendLine(out, "");
        sendLine(out, summary);

        if (labels != null) {
            String[] labelArray = labels.split("\\,");

            if (labelArray != null && labelArray.length > 0) {
                log("Setting " + labelArray.length + " label(s)");

                for (int n = 0, i = labelArray.length; n < i; n++) {
                    sendLine(out, "--" + BOUNDARY);
                    sendLine(out, "content-disposition: form-data; name=\"label\"");
                    sendLine(out, "");
                    sendLine(out, labelArray[n].trim());
                }
            }
        }

        log("Sending file... " + targetFileName);
        sendLine(out, "--" + BOUNDARY);
        sendLine(out, "content-disposition: form-data; name=\"filename\"; filename=\"" + targetFileName + "\"");
        sendLine(out, "Content-Type: application/octet-stream");
        sendLine(out, "");
        int count;
        byte[] buf = new byte[8192];
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        sendLine(out, "");
        sendLine(out, "--" + BOUNDARY + "--");

        out.flush();
        out.close();

        // For whatever reason, you have to read from the input stream
        // before
        // the url connection will start sending
        in = conn.getInputStream();

        log("Upload finished. Reading response.");

        log("HTTP Response Headers: " + conn.getHeaderFields());
        StringBuilder responseBody = new StringBuilder();
        while ((count = in.read(buf)) >= 0) {
            responseBody.append(new String(buf, 0, count, "ascii"));
        }
        log(responseBody.toString());
        in.close();

        conn.disconnect();
    }
}

From source file:io.fabric8.maven.CreateProfileZipMojo.java

License:Apache License

protected void generateAggregatedZip(MavenProject rootProject, List<MavenProject> reactorProjects,
        List<MavenProject> pomZipProjects) throws IOException, MojoExecutionException {
    File projectBaseDir = rootProject.getBasedir();
    File projectOutputFile = new File(projectBaseDir, "target/profile.zip");
    getLog().info("Generating " + projectOutputFile.getAbsolutePath() + " from root project "
            + rootProject.getArtifactId());
    File projectBuildDir = new File(projectBaseDir, reactorProjectOutputPath);

    createAggregatedZip(reactorProjects, projectBaseDir, projectBuildDir, reactorProjectOutputPath,
            projectOutputFile, includeReadMe, pomZipProjects);
    if (rootProject.getAttachedArtifacts() != null) {
        // need to remove existing as otherwise we get a WARN
        Artifact found = null;//w  w  w. j  av  a  2s .c  o m
        for (Artifact artifact : rootProject.getAttachedArtifacts()) {
            if (artifactClassifier != null && artifact.hasClassifier()
                    && artifact.getClassifier().equals(artifactClassifier)) {
                found = artifact;
                break;
            }
        }
        if (found != null) {
            rootProject.getAttachedArtifacts().remove(found);
        }
    }

    getLog().info("Attaching aggregated zip " + projectOutputFile + " to root project "
            + rootProject.getArtifactId());
    projectHelper.attachArtifact(rootProject, artifactType, artifactClassifier, projectOutputFile);

    // if we are doing an install goal, then also install the aggregated zip manually
    // as maven will install the root project first, and then build the reactor projects, and at this point
    // it does not help to attach artifact to root project, as those artifacts will not be installed
    // so we need to install manually
    if (rootProject.hasLifecyclePhase("install")) {
        getLog().info("Installing aggregated zip " + projectOutputFile);
        InvocationRequest request = new DefaultInvocationRequest();
        request.setBaseDirectory(rootProject.getBasedir());
        request.setPomFile(new File("./pom.xml"));
        request.setGoals(Collections.singletonList("install:install-file"));
        request.setRecursive(false);
        request.setInteractive(false);

        Properties props = new Properties();
        props.setProperty("file", "target/profile.zip");
        props.setProperty("groupId", rootProject.getGroupId());
        props.setProperty("artifactId", rootProject.getArtifactId());
        props.setProperty("version", rootProject.getVersion());
        props.setProperty("classifier", "profile");
        props.setProperty("packaging", "zip");
        request.setProperties(props);

        getLog().info(
                "Installing aggregated zip using: mvn install:install-file" + serializeMvnProperties(props));
        Invoker invoker = new DefaultInvoker();
        try {
            InvocationResult result = invoker.execute(request);
            if (result.getExitCode() != 0) {
                throw new IllegalStateException("Error invoking Maven goal install:install-file");
            }
        } catch (MavenInvocationException e) {
            throw new MojoExecutionException("Error invoking Maven goal install:install-file", e);
        }
    }
}

From source file:io.fabric8.maven.ZipMojo.java

License:Apache License

protected void generateAggregatedZip(MavenProject rootProject, List<MavenProject> reactorProjects,
        Set<MavenProject> pomZipProjects) throws IOException, MojoExecutionException {
    File projectBaseDir = rootProject.getBasedir();
    String rootProjectGroupId = rootProject.getGroupId();
    String rootProjectArtifactId = rootProject.getArtifactId();
    String rootProjectVersion = rootProject.getVersion();

    String aggregatedZipFileName = "target/" + rootProjectArtifactId + "-" + rootProjectVersion + "-app.zip";
    File projectOutputFile = new File(projectBaseDir, aggregatedZipFileName);
    getLog().info("Generating " + projectOutputFile.getAbsolutePath() + " from root project "
            + rootProjectArtifactId);//ww  w  .j ava  2 s .c  o m
    File projectBuildDir = new File(projectBaseDir, reactorProjectOutputPath);

    if (projectOutputFile.exists()) {
        projectOutputFile.delete();
    }
    createAggregatedZip(projectBaseDir, projectBuildDir, reactorProjectOutputPath, projectOutputFile,
            includeReadMe, pomZipProjects);
    if (rootProject.getAttachedArtifacts() != null) {
        // need to remove existing as otherwise we get a WARN
        Artifact found = null;
        for (Artifact artifact : rootProject.getAttachedArtifacts()) {
            if (artifactClassifier != null && artifact.hasClassifier()
                    && artifact.getClassifier().equals(artifactClassifier)) {
                found = artifact;
                break;
            }
        }
        if (found != null) {
            rootProject.getAttachedArtifacts().remove(found);
        }
    }

    getLog().info("Attaching aggregated zip " + projectOutputFile + " to root project "
            + rootProject.getArtifactId());
    projectHelper.attachArtifact(rootProject, artifactType, artifactClassifier, projectOutputFile);

    // if we are doing an install goal, then also install the aggregated zip manually
    // as maven will install the root project first, and then build the reactor projects, and at this point
    // it does not help to attach artifact to root project, as those artifacts will not be installed
    // so we need to install manually
    List<String> activeProfileIds = new ArrayList<>();
    List<Profile> activeProfiles = rootProject.getActiveProfiles();
    if (activeProfiles != null) {
        for (Profile profile : activeProfiles) {
            String id = profile.getId();
            if (Strings.isNotBlank(id)) {
                activeProfileIds.add(id);
            }
        }
    }
    if (rootProject.hasLifecyclePhase("install")) {
        getLog().info("Installing aggregated zip " + projectOutputFile);
        InvocationRequest request = new DefaultInvocationRequest();
        request.setBaseDirectory(rootProject.getBasedir());
        request.setPomFile(new File("./pom.xml"));
        request.setGoals(Collections.singletonList("install:install-file"));
        request.setRecursive(false);
        request.setInteractive(false);
        request.setProfiles(activeProfileIds);

        Properties props = new Properties();
        props.setProperty("file", aggregatedZipFileName);
        props.setProperty("groupId", rootProjectGroupId);
        props.setProperty("artifactId", rootProjectArtifactId);
        props.setProperty("version", rootProjectVersion);
        props.setProperty("classifier", "app");
        props.setProperty("packaging", "zip");
        props.setProperty("generatePom", "false");
        request.setProperties(props);

        getLog().info(
                "Installing aggregated zip using: mvn install:install-file" + serializeMvnProperties(props));
        Invoker invoker = new DefaultInvoker();
        try {
            InvocationResult result = invoker.execute(request);
            if (result.getExitCode() != 0) {
                throw new IllegalStateException("Error invoking Maven goal install:install-file");
            }
        } catch (MavenInvocationException e) {
            throw new MojoExecutionException("Error invoking Maven goal install:install-file", e);
        }
    }

    if (rootProject.hasLifecyclePhase("deploy")) {

        if (deploymentRepository == null && Strings.isNullOrBlank(altDeploymentRepository)) {
            String msg = "Cannot run deploy phase as Maven project has no <distributionManagement> with the maven url to use for deploying the aggregated zip file, neither an altDeploymentRepository property.";
            getLog().warn(msg);
            throw new MojoExecutionException(msg);
        }

        getLog().info("Deploying aggregated zip " + projectOutputFile + " to root project "
                + rootProject.getArtifactId());
        getLog().info("Using deploy goal: " + deployFileGoal + " with active profiles: " + activeProfileIds);

        InvocationRequest request = new DefaultInvocationRequest();
        request.setBaseDirectory(rootProject.getBasedir());
        request.setPomFile(new File("./pom.xml"));
        request.setGoals(Collections.singletonList(deployFileGoal));
        request.setRecursive(false);
        request.setInteractive(false);
        request.setProfiles(activeProfileIds);
        request.setProperties(getProjectAndFabric8Properties(getProject()));

        Properties props = new Properties();
        props.setProperty("file", aggregatedZipFileName);
        props.setProperty("groupId", rootProjectGroupId);
        props.setProperty("artifactId", rootProjectArtifactId);
        props.setProperty("version", rootProjectVersion);
        props.setProperty("classifier", "app");
        props.setProperty("packaging", "zip");
        String deployUrl = null;

        if (!Strings.isNullOrBlank(deployFileUrl)) {
            deployUrl = deployFileUrl;
        } else if (altDeploymentRepository != null && altDeploymentRepository.contains("::")) {
            deployUrl = altDeploymentRepository.substring(altDeploymentRepository.lastIndexOf("::") + 2);
        } else {
            deployUrl = deploymentRepository.getUrl();
        }

        props.setProperty("url", deployUrl);
        props.setProperty("repositoryId", deploymentRepository.getId());
        props.setProperty("generatePom", "false");
        request.setProperties(props);

        getLog().info("Deploying aggregated zip using: mvn deploy:deploy-file" + serializeMvnProperties(props));
        Invoker invoker = new DefaultInvoker();
        try {
            InvocationResult result = invoker.execute(request);
            if (result.getExitCode() != 0) {
                throw new IllegalStateException("Error invoking Maven goal deploy:deploy-file");
            }
        } catch (MavenInvocationException e) {
            throw new MojoExecutionException("Error invoking Maven goal deploy:deploy-file", e);
        }
    }
}