Example usage for org.apache.maven.project MavenProject getArtifactId

List of usage examples for org.apache.maven.project MavenProject getArtifactId

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getArtifactId.

Prototype

public String getArtifactId() 

Source Link

Usage

From source file:hudson.maven.reporters.MavenArtifactArchiver.java

License:Open Source License

public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener)
        throws InterruptedException, IOException {
    // artifacts that are known to Maven.
    Set<File> mavenArtifacts = new HashSet<File>();

    if (pom.getFile() != null) {// goals like 'clean' runs without loading POM, apparently.
        // record POM
        final MavenArtifact pomArtifact = new MavenArtifact(pom.getGroupId(), pom.getArtifactId(),
                pom.getVersion(), null, "pom", pom.getFile().getName(), Util.getDigestOf(pom.getFile()));

        final String repositoryUrl = pom.getDistributionManagementArtifactRepository() == null ? null
                : Util.fixEmptyAndTrim(pom.getDistributionManagementArtifactRepository().getUrl());
        final String repositoryId = pom.getDistributionManagementArtifactRepository() == null ? null
                : Util.fixEmptyAndTrim(pom.getDistributionManagementArtifactRepository().getId());

        mavenArtifacts.add(pom.getFile());
        pomArtifact.archive(build, pom.getFile(), listener);

        // record main artifact (if packaging is POM, this doesn't exist)
        final MavenArtifact mainArtifact = MavenArtifact.create(pom.getArtifact());
        if (mainArtifact != null) {
            File f = pom.getArtifact().getFile();
            mavenArtifacts.add(f);//from w  w  w.ja  va  2s  . c om
            mainArtifact.archive(build, f, listener);
        }

        // record attached artifacts
        final List<MavenArtifact> attachedArtifacts = new ArrayList<MavenArtifact>();
        for (Artifact a : pom.getAttachedArtifacts()) {
            MavenArtifact ma = MavenArtifact.create(a);
            if (ma != null) {
                mavenArtifacts.add(a.getFile());
                ma.archive(build, a.getFile(), listener);
                attachedArtifacts.add(ma);
            }
        }

        // record the action
        build.executeAsync(new MavenBuildProxy.BuildCallable<Void, IOException>() {
            private static final long serialVersionUID = -7955474564875700905L;

            public Void call(MavenBuild build) throws IOException, InterruptedException {
                // if a build forks lifecycles, this method can be called multiple times
                List<MavenArtifactRecord> old = build.getActions(MavenArtifactRecord.class);
                if (!old.isEmpty())
                    build.getActions().removeAll(old);

                MavenArtifactRecord mar = new MavenArtifactRecord(build, pomArtifact, mainArtifact,
                        attachedArtifacts, repositoryUrl, repositoryId);
                build.addAction(mar);

                // TODO kutzi: why are the fingerprints recorded here?
                // I thought that is the job of MavenFingerprinter
                mar.recordFingerprints();

                return null;
            }
        });
    }

    // do we have any assembly artifacts?
    //        System.out.println("Considering "+assemblies+" at "+MavenArtifactArchiver.this);
    //        new Exception().fillInStackTrace().printStackTrace();
    if (build.isArchivingDisabled()) {
        listener.getLogger().println("[JENKINS] Archiving disabled");
    } else if (assemblies != null) {
        for (File assembly : assemblies) {
            if (mavenArtifacts.contains(assembly))
                continue; // looks like this is already archived
            FilePath target = build.getArtifactsDir().child(assembly.getName());
            listener.getLogger().println("[JENKINS] Archiving " + assembly + " to " + target);
            new FilePath(assembly).copyTo(target);
            // TODO: fingerprint
        }
    }

    return true;
}

From source file:io.earcam.maven.site.skin.scalp.SkinConfigTool.java

License:Apache License

/**
 * {@inheritDoc}/*from  w ww  .  ja v a2  s  . c o  m*/
 * @see SafeConfig#configure(ValueParser)
 */
@Override
protected void configure(ValueParser values) {
    String altkey = values.getString("key");
    if (altkey != null) {
        setKey(altkey);
    }

    // allow changing skin key in the configuration
    String altSkinKey = values.getString("skinKey");
    if (altSkinKey != null) {
        this.skinKey = altSkinKey;
    }

    // retrieve the decoration model from Velocity context
    Object velocityContext = values.get("velocityContext");

    if (!(velocityContext instanceof ToolContext)) {
        return;
    }

    ToolContext ctxt = (ToolContext) velocityContext;

    Object projectObj = ctxt.get("project");
    if (projectObj instanceof MavenProject) {
        MavenProject project = (MavenProject) projectObj;
        String artifactId = project.getArtifactId();
        // use artifactId "sluggified" as the projectId
        projectId = HtmlTool.slug(artifactId);
    }

    // calculate the page ID from the current file name
    Object currentFileObj = ctxt.get("currentFileName");
    if (currentFileObj instanceof String) {

        String currentFile = (String) currentFileObj;

        // drop the extension
        int lastDot = currentFile.lastIndexOf(".");
        if (lastDot >= 0) {
            currentFile = currentFile.substring(0, lastDot);
        }

        // full file ID includes the nested dirs
        // replace nesting "/" with "-"
        fileId = HtmlTool.slug(currentFile.replace("/", "-").replace("\\", "-"));
    }

    Object decorationObj = ctxt.get("decoration");

    if (!(decorationObj instanceof DecorationModel)) {
        return;
    }

    DecorationModel decoration = (DecorationModel) decorationObj;
    Object customObj = decoration.getCustom();

    if (!(customObj instanceof Xpp3Dom)) {
        return;
    }

    // Now that we have the custom node, get the global properties
    // under the skin tag
    Xpp3Dom customNode = (Xpp3Dom) customObj;
    Xpp3Dom skinNode = customNode.getChild(skinKey);
    String namespaceKey = ":" + skinKey;

    if (skinNode == null) {
        // try searching with any namespace
        for (Xpp3Dom child : customNode.getChildren()) {
            if (child.getName().endsWith(namespaceKey)) {
                skinNode = child;
                break;
            }
        }
    }

    if (skinNode != null) {
        globalProperties = skinNode;

        if (skinNode.getName().endsWith(namespaceKey)) {
            // extract the namespace (including the colon)
            namespace = skinNode.getName().substring(0,
                    skinNode.getName().length() - namespaceKey.length() + 1);
        }

        // for page properties, retrieve the file name and drop the `.html`
        // extension - this will be used, i.e. `index` instead of `index.html`
        Xpp3Dom pagesNode = getChild(skinNode, "pages");
        if (pagesNode != null) {

            // Get the page for the file
            // TODO try fileShortId as well?
            Xpp3Dom page = getChild(pagesNode, fileId);

            // Now check if the project artifact ID is set, and if so, if it matches the
            // current project. This allows preventing accidental reuse of parent page
            // configs in children modules
            if (page != null && projectId != null) {
                String pageProject = page.getAttribute("project");
                if (pageProject != null && !projectId.equals(pageProject)) {
                    // project ID indicated, and is different - do not use the config
                    page = null;
                }
            }

            if (page != null) {
                pageProperties = page;
            }
        }
    }
}

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

License:Apache License

/**
 * Tries to default some environment variables if they are not already defined.
 *
 * This can happen if using Jenkins Workflow which doens't seem to define BUILD_URL or GIT_URL for example
 *
 * @return the value of the environment variable name if it can be found or calculated
 *///w  w  w  . j ava 2 s .  com
protected String tryDefaultAnnotationEnvVar(String envVarName) {
    // only do this if enabled
    if (extendedMetadata != null && !extendedMetadata) {
        return null;
    }

    MavenProject rootProject = getRootProject();
    File basedir = rootProject.getBasedir();
    if (basedir == null) {
        basedir = getProject().getBasedir();
    }
    if (basedir == null) {
        basedir = new File(System.getProperty("basedir", "."));
    }
    ProjectConfig projectConfig = ProjectConfigs.loadFromFolder(basedir);
    String repoName = rootProject.getArtifactId();

    String userEnvVar = "JENKINS_GOGS_USER";
    String username = Systems.getEnvVarOrSystemProperty(userEnvVar);

    if (Objects.equal("BUILD_URL", envVarName)) {
        String jobUrl = projectConfig.getLink("Job");
        if (Strings.isNullOrBlank(jobUrl)) {
            String name = projectConfig.getBuildName();
            if (Strings.isNullOrBlank(name)) {
                // lets try deduce the jenkins build name we'll generate
                if (Strings.isNotBlank(repoName)) {
                    name = repoName;
                    if (Strings.isNotBlank(username)) {
                        name = ProjectRepositories.createBuildName(username, repoName);
                    } else {
                        warnIfInCDBuild("Cannot auto-default BUILD_URL as there is no environment variable `"
                                + userEnvVar + "` defined so we can't guess the Jenkins build URL");
                    }
                }
            }
            if (Strings.isNotBlank(name)) {
                try {
                    // this requires online access to kubernetes so we should silently fail if no connection
                    String jenkinsUrl = KubernetesHelper.getServiceURLInCurrentNamespace(getKubernetes(),
                            ServiceNames.JENKINS, "http", null, true);
                    jobUrl = URLUtils.pathJoin(jenkinsUrl, "/job", name);
                } catch (Throwable e) {
                    Throwable cause = e;

                    boolean notFound = false;
                    boolean connectError = false;
                    Iterable<Throwable> it = createExceptionIterable(e);
                    for (Throwable t : it) {
                        connectError = t instanceof ConnectException
                                || "No route to host".equals(t.getMessage());
                        notFound = t instanceof IllegalArgumentException || t.getMessage() != null
                                && t.getMessage().startsWith("No kubernetes service could be found for name");
                        if (connectError || notFound) {
                            cause = t;
                            break;
                        }
                    }

                    if (connectError) {
                        warnIfInCDBuild("Cannot connect to Kubernetes to find jenkins service URL: "
                                + cause.getMessage());
                    } else if (notFound) {
                        // the message from the exception is good as-is
                        warnIfInCDBuild(cause.getMessage());
                    } else {
                        warnIfInCDBuild("Cannot find jenkins service URL: " + cause, cause);
                    }
                }
            }
        }
        if (Strings.isNotBlank(jobUrl)) {
            String buildId = Systems.getEnvVarOrSystemProperty("BUILD_ID");
            if (Strings.isNotBlank(buildId)) {
                jobUrl = URLUtils.pathJoin(jobUrl, buildId);
            } else {
                warnIfInCDBuild(
                        "Cannot find BUILD_ID to create a specific jenkins build URL. So using: " + jobUrl);
            }
        }
        return jobUrl;
    } else if (Objects.equal("GIT_URL", envVarName)) {
        if (Strings.isNotBlank(repoName) && Strings.isNotBlank(username)) {
            try {
                // this requires online access to kubernetes so we should silently fail if no connection
                String gogsUrl = KubernetesHelper.getServiceURLInCurrentNamespace(getKubernetes(),
                        ServiceNames.GOGS, "http", null, true);
                String rootGitUrl = URLUtils.pathJoin(gogsUrl, username, repoName);
                String gitCommitId = getGitCommitId(envVarName, basedir);
                if (Strings.isNotBlank(gitCommitId)) {
                    rootGitUrl = URLUtils.pathJoin(rootGitUrl, "commit", gitCommitId);
                }
                return rootGitUrl;
            } catch (Throwable e) {
                Throwable cause = e;

                boolean notFound = false;
                boolean connectError = false;
                Iterable<Throwable> it = createExceptionIterable(e);
                for (Throwable t : it) {
                    notFound = t instanceof IllegalArgumentException || t.getMessage() != null
                            && t.getMessage().startsWith("No kubernetes service could be found for name");
                    connectError = t instanceof ConnectException || "No route to host".equals(t.getMessage());
                    if (connectError) {
                        cause = t;
                        break;
                    }
                }

                if (connectError) {
                    warnIfInCDBuild(
                            "Cannot connect to Kubernetes to find gogs service URL: " + cause.getMessage());
                } else if (notFound) {
                    // the message from the exception is good as-is
                    warnIfInCDBuild(cause.getMessage());
                } else {
                    warnIfInCDBuild("Cannot find gogs service URL: " + cause, cause);
                }
            }
        } else {
            warnIfInCDBuild("Cannot auto-default GIT_URL as there is no environment variable `" + userEnvVar
                    + "` defined so we can't guess the Gogs build URL");
        }
        /*
                    TODO this is the git clone url; while we could try convert from it to a browse URL its probably too flaky?
                
                    try {
        url = GitHelpers.extractGitUrl(basedir);
                    } catch (IOException e) {
        warnIfInCDBuild("Failed to find git url in directory " + basedir + ". " + e, e);
                    }
                    if (Strings.isNotBlank(url)) {
        // for gogs / github style repos we trim the .git suffix for browsing
        return Strings.stripSuffix(url, ".git");
                    }
        */
    } else if (Objects.equal("GIT_COMMIT", envVarName)) {
        return getGitCommitId(envVarName, basedir);
    } else if (Objects.equal("GIT_BRANCH", envVarName)) {
        Repository repository = getGitRepository(basedir, envVarName);
        try {
            if (repository != null) {
                return repository.getBranch();
            }
        } catch (IOException e) {
            warnIfInCDBuild("Failed to find git commit id. " + e, e);
        } finally {
            if (repository != null) {
                repository.close();
            }
        }
    }
    return null;
}

From source file:io.fabric8.maven.core.util.kubernetes.KubernetesResourceUtil.java

License:Apache License

public static String extractContainerName(MavenProject project, ImageConfiguration imageConfig) {
    String alias = imageConfig.getAlias();
    return alias != null ? alias
            : extractImageUser(imageConfig.getName(), project) + "-" + project.getArtifactId();
}

From source file:io.fabric8.maven.core.util.MavenUtil.java

License:Apache License

public static String createDefaultResourceName(MavenProject project, String... suffixes) {
    String suffix = StringUtils.join(suffixes, "-");
    String ret = project.getArtifactId() + (suffix.length() > 0 ? "-" + suffix : "");
    if (ret.length() > 63) {
        ret = ret.substring(0, 63);// w w  w  .j  ava  2  s .c o m
    }
    return ret.toLowerCase();
}

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

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {//  w w  w. j  a v a2  s  . c o  m
        if (isIgnoreProject())
            return;

        generateZip();

        if (reactorProjects != null) {
            List<MavenProject> pomZipProjects = new ArrayList<>();
            List<MavenProject> fabricZipGoalProjects = new ArrayList<>();
            List<MavenProject> fabricHasParentZipGoalProject = new ArrayList<MavenProject>();
            for (MavenProject reactorProject : reactorProjects) {

                if ("pom".equals(reactorProject.getPackaging())) {
                    pomZipProjects.add(reactorProject);
                }

                List<Plugin> buildPlugins = reactorProject.getBuildPlugins();
                for (Plugin buildPlugin : buildPlugins) {
                    String artifactId = buildPlugin.getArtifactId();
                    // TODO I guess we could try find if the "zip" goal is being invoked?
                    if ("fabric8-maven-plugin".equals(artifactId)) {
                        // TODO should we only consider reactorProjects which have a fabric8:zip goal?
                        Object goals = buildPlugin.getGoals();
                        boolean hasZipGoal = goals != null && goals.toString().contains("zip");
                        List<PluginExecution> executions = buildPlugin.getExecutions();
                        for (PluginExecution execution : executions) {
                            List<String> execGoals = execution.getGoals();
                            if (execGoals.contains("zip")) {
                                hasZipGoal = true;
                            }
                        }
                        getLog().debug(
                                "project " + reactorProject.getArtifactId() + " has zip goal: " + hasZipGoal);

                        fabricZipGoalProjects.add(reactorProject);
                    }
                }
            }

            // we want a list of projects which has a parent that has a zip goal too
            // as that helps us detect the 'last' project when we do a full build from the entire project
            for (MavenProject project : fabricZipGoalProjects) {
                if (fabricZipGoalProjects.contains(project.getParent())) {
                    fabricHasParentZipGoalProject.add(project);
                }
            }

            // are we the last project?
            boolean last = reactorProjects.size() > 1
                    && project == reactorProjects.get(reactorProjects.size() - 1);
            if (!last) {
                // are we the last project with the zip goal, part of a group as they have a parent?
                // TODO: there can be multiple groups, so when we switch to a new group we should aggregate
                last = fabricHasParentZipGoalProject.size() > 1 && project == fabricHasParentZipGoalProject
                        .get(fabricHasParentZipGoalProject.size() - 1);
            }
            if (!last) {
                // are we the last project with the zip goal?
                last = fabricZipGoalProjects.size() > 1
                        && project == fabricZipGoalProjects.get(fabricZipGoalProjects.size() - 1);
            }

            // we need to generate the aggregated zip last, so we have all the generated profiles in the other modules
            // which we can aggregate
            if (last) {
                getLog().info("");
                getLog().info("Creating aggregated profile zip");
                getLog().info("built the last fabric8:zip project so generating a combined zip for all "
                        + fabricZipGoalProjects.size() + " projects with a fabric8:zip goal");

                // favor root project as the 1st project with fabric8:zip goal
                MavenProject rootProject = fabricZipGoalProjects.size() > 0 ? fabricZipGoalProjects.get(0)
                        : reactorProjects.get(0);

                // we got the root project, now filter out pom projects which has the rootProject as one of their parents
                List<MavenProject> ourPomZipProjects = new ArrayList<MavenProject>();
                // include the root project if its a zip as well
                if (pomZipProjects.contains(rootProject)) {
                    ourPomZipProjects.add(rootProject);
                }
                ourPomZipProjects.add(rootProject);
                for (MavenProject zip : pomZipProjects) {
                    if (hasParent(zip, rootProject, true)) {
                        ourPomZipProjects.add(zip);
                    }
                }

                getLog().info("Choosing root project " + rootProject.getArtifactId()
                        + " for generation of aggregated zip");
                generateAggregatedZip(rootProject, fabricZipGoalProjects, ourPomZipProjects);
            }
        }

    } catch (MojoFailureException e) {
        throw e;
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException("Error executing", e);
    }
}

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  ww.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.enricher.fabric8.CdEnricher.java

License:Apache License

@Override
public Map<String, String> getAnnotations(Kind kind) {
    if (isOnline() && (kind.isController() || kind == Kind.SERVICE)) {
        Map<String, String> annotations = new HashMap<>();
        MavenProject rootProject = MavenUtil.getRootProject(getProject());
        String repoName = rootProject.getArtifactId();
        try (Repository repository = GitUtil.getGitRepository(getProject())) {
            // Git annotations (if git is used as SCM)
            if (repository != null) {
                String gitCommitId = GitUtil.getGitCommitId(repository);
                if (gitCommitId != null) {
                    addGitServiceUrl(annotations, repoName, gitCommitId);
                } else {
                    log.debug("No Git commit id found");
                }//from www.j  av a 2s  .c o m
            } else {
                log.debug("No local Git repository found");
            }
        } catch (IOException | GitAPIException e) {
            log.error("Cannot extract Git information for adding to annotations: " + e, e);
        }
        // Jenkins annotations
        addJenkinsServiceUrl(annotations, repoName);
        return annotations;

    }
    return null;
}

From source file:io.fabric8.maven.enricher.fabric8.GrafanaLinkEnricher.java

License:Apache License

private String findGrafanaLink() {
    MavenProject project = getProject();
    String defaultDashboard = detectDefaultDashboard(project);
    String query = "";
    String projectName = null;/*from ww w.  j  av a 2  s .co  m*/
    String version = null;

    // TODO - use the docker names which may differ from project metadata!
    if (Strings.isNullOrBlank(projectName)) {
        projectName = project.getArtifactId();
    }
    if (Strings.isNullOrBlank(version)) {
        version = project.getVersion();
    }

    if (Strings.isNotBlank(projectName)) {
        query += "&var-project=" + projectName;
    }
    if (Strings.isNotBlank(version)) {
        query += "&var-version=" + version;
    }
    if (query.startsWith("&")) {
        query = "?" + query.substring(1);
    }
    return URLUtils.pathJoin("dashboard/file", defaultDashboard, query);
}

From source file:io.fabric8.maven.enricher.standard.ProjectEnricher.java

License:Apache License

private Map<String, String> createLabels(boolean withoutVersion) {
    MavenProject project = getProject();
    Map<String, String> ret = new HashMap<>();
    ret.put("project", project.getArtifactId());
    ret.put("group", project.getGroupId());
    ret.put("provider", "fabric8");
    if (!withoutVersion) {
        ret.put("version", project.getVersion());
    }/*from ww  w  . ja  va 2 s  . c  o  m*/
    return ret;
}