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

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

Introduction

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

Prototype

public String getGroupId() 

Source Link

Usage

From source file:org.jboss.maven.plugins.qstools.checkers.ValidXMLSchemaChecker.java

License:Apache License

@Override
public Map<String, List<Violation>> check(MavenProject project, MavenSession mavenSession,
        List<MavenProject> reactorProjects, Log log) throws QSToolsException {
    log.info("--> This Checker can take several minutes to run");
    this.log = log;
    Map<String, List<Violation>> results = new TreeMap<String, List<Violation>>();
    Rules rules = configurationProvider.getQuickstartsRules(project.getGroupId());
    try {/* ww  w. j  a  v  a 2  s . co m*/
        if (rules.isCheckerIgnored(this.getClass())) {
            checkerMessage = "This checker is ignored for this groupId in config file.";
        } else {
            // get all xml to process but excludes hidden files and /target and /bin folders
            List<File> xmlFiles = FileUtils.getFiles(project.getBasedir(), "**/*.xml", rules.getExcludes());
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema();
            for (File xml : xmlFiles) {
                // Get relative path based on maven work dir
                String rootDirectory = (mavenSession.getExecutionRootDirectory() + File.separator).replace("\\",
                        "\\\\");
                String fileAsString = xml.getAbsolutePath().replace(rootDirectory, "");
                Validator validator = schema.newValidator();
                validator.setResourceResolver(new URLBasedResourceResolver(xml));
                validator.setErrorHandler(new XMLErrorHandler(fileAsString, results));

                log.info("Validating " + fileAsString);
                try {
                    validator.validate(new StreamSource(new BufferedInputStream(new FileInputStream(xml))));
                } catch (SAXException e) {
                    // validator.validate can throw a SAXException coming from the ErrorHandler
                    addViolation(fileAsString, 0, e.getMessage(), results);
                }
            }
            if (getCheckerMessage() != null) {
                log.info("--> Checker Message: " + getCheckerMessage());
            }
            if (violationsQtd > 0) {
                log.info("There are " + violationsQtd + " checkers violations");
            }
        }
    } catch (Exception e) {
        throw new QSToolsException(e);
    }
    return results;

}

From source file:org.jboss.maven.plugins.qstools.common.ArtifactIdNameUtil.java

License:Apache License

/**
 * (non-Javadoc)//from   ww w  .j  a v  a 2  s  .  c o  m
 * <p/>
 * Walks up the parent directories looking for the last containing a pom.xml with the same groupId as the specified project.
 */
private File getRootDirOfQuickstarts(MavenProject project) throws Exception {

    File dirToCheck = project.getBasedir();
    File resultDir = project.getBasedir();
    while (containsPomWithGroupId(dirToCheck, project.getGroupId())) {
        resultDir = dirToCheck;
        dirToCheck = dirToCheck.getParentFile();
    }

    return resultDir;
}

From source file:org.jboss.maven.plugins.qstools.fixers.ArtifactIdNameFixer.java

License:Apache License

@Override
public void fix(MavenProject project, MavenSession mavenSession, List<MavenProject> reactorProjects, Log log)
        throws QSToolsException {

    try {//from ww w. j  a va  2 s  .c  o m
        Rules rules = configurationProvider.getQuickstartsRules(project.getGroupId());
        List<ArtifactIdNameUtil.PomInformation> pomsWithInvalidArtifactIds = artifactIdNameUtil
                .findAllIncorrectArtifactIdNames(reactorProjects, rules);

        // Update each incorrect artifactId
        for (ArtifactIdNameUtil.PomInformation pi : pomsWithInvalidArtifactIds) {
            Document doc = PositionalXMLReader.readXML(new FileInputStream(pi.getProject().getFile()));
            Node artifactIdNode = (Node) xPath.evaluate("/project/artifactId", doc, XPathConstants.NODE);
            artifactIdNode.setTextContent(pi.getExpectedArtifactId());
            XMLUtil.writeXML(doc, pi.getProject().getFile());
        }

        // Update all the parents, to use the changed artifactId
        for (MavenProject subProject : reactorProjects) {
            Document doc = PositionalXMLReader.readXML(new FileInputStream(subProject.getFile()));
            Node parentArtifactIdNode = (Node) xPath.evaluate("/project/parent/artifactId", doc,
                    XPathConstants.NODE);
            if (parentArtifactIdNode != null && subProject.getParentFile() != null) {
                Document parentDoc = PositionalXMLReader
                        .readXML(new FileInputStream(subProject.getParentFile()));
                Node artifactIdNode = (Node) xPath.evaluate("/project/artifactId", parentDoc,
                        XPathConstants.NODE);

                if (!parentArtifactIdNode.getTextContent().equals(artifactIdNode.getTextContent())) {
                    parentArtifactIdNode.setTextContent(artifactIdNode.getTextContent());
                }
            }

            // Update each incorrect artifactId dependency
            for (ArtifactIdNameUtil.PomInformation pi : pomsWithInvalidArtifactIds) {
                // It can have more than one occurrence on the same file
                NodeList artfactIdNodes = (NodeList) xPath.evaluate(
                        "//artifactId[text()='" + pi.getActualArtifactId() + "']", doc, XPathConstants.NODESET);
                for (int x = 0; x < artfactIdNodes.getLength(); x++) {
                    Node artfactIdNode = artfactIdNodes.item(x);
                    if (artfactIdNode != null) {
                        artfactIdNode.setTextContent(pi.getExpectedArtifactId());
                    }

                }
            }
            XMLUtil.writeXML(doc, subProject.getFile());
        }
    } catch (Exception e) {
        throw new QSToolsException(e);
    }
}

From source file:org.jboss.maven.plugins.qstools.fixers.FileHeaderFixer.java

License:Apache License

@Override
public void fix(MavenProject project, MavenSession mavenSession, List<MavenProject> reactorProjects, Log log)
        throws QSToolsException {
    Rules rules = configurationProvider.getQuickstartsRules(project.getGroupId());
    // Execute License-Maven-Plugin - http://code.mycila.com/license-maven-plugin/reports/2.3/format-mojo.html
    try {// ww  w .j  a  v  a 2 s. co  m
        // Get Excluded files
        List<Element> excludes = new ArrayList<Element>();
        for (String exclude : rules.getExcludesArray()) {
            excludes.add(element("exclude", exclude));
        }
        for (String exclude : rules.getFixerSpecificExcludesArray(this)) {
            excludes.add(element("exclude", exclude));
        }
        List<Element> includes = new ArrayList<Element>();

        // Get includes extensions
        String[] includesExtensions = new String[] { "**/*.xml", "**/*.xsd", "**/*.java", "**/*.js",
                "**/*.properties", "**/*.html", "**/*.xhtml", "**/*.sql", "**/*.css" };

        for (String include : includesExtensions) {
            includes.add(element("include", include));
        }

        pluginManager = (BuildPluginManager) context.get(Constants.PLUGIN_MANAGER);
        executeMojo(plugin(groupId("com.mycila"), artifactId("license-maven-plugin"), version("2.5")),
                goal("format"),
                configuration(element(name("header"), rules.getLicenseFileLocation()),
                        element(name("aggregate"), "true"), element(name("strictCheck"), "true"),
                        element(name("encoding"), "utf-8"),
                        element(name("headerDefinitions"),
                                element(name("headerDefinition"), rules.getHeaderDefinitionLocation())),
                        element(name("includes"), includes.toArray(new Element[] {})),
                        element(name("excludes"), excludes.toArray(new Element[] {}))),
                executionEnvironment(project, mavenSession, pluginManager));
    } catch (Exception e) {
        throw new QSToolsException(e);
    }

}

From source file:org.jboss.maven.plugins.qstools.fixers.FinalNameFixer.java

License:Apache License

@Override
public void fixProject(MavenProject project, Document doc) throws Exception {

    String packaging = project.getPackaging();
    String expectedFinalName = getConfigurationProvider().getQuickstartsRules(project.getGroupId())
            .getFinalNamePatterns().get(packaging);

    Node finalNameNode = (Node) getxPath().evaluate("//finalName", doc, XPathConstants.NODE);
    String declaredFinalName = finalNameNode == null ? project.getBuild().getFinalName()
            : finalNameNode.getTextContent();

    if (expectedFinalName != null && !expectedFinalName.equals(declaredFinalName)) {

        Node buildNode = (Node) getxPath().evaluate("/project/build", doc, XPathConstants.NODE);
        if (buildNode == null) {
            buildNode = doc.createElement("build");
            Node projectNode = (Node) getxPath().evaluate("/project", doc, XPathConstants.NODE);
            projectNode.appendChild(doc.createTextNode("    "));
            projectNode.appendChild(buildNode);
        }/*from w w  w.j a  va2s.c o m*/

        finalNameNode = (Node) getxPath().evaluate("/project/build/finalName", doc, XPathConstants.NODE);
        if (finalNameNode == null) {
            finalNameNode = doc.createElement("finalName");
            buildNode.insertBefore(finalNameNode, buildNode.getFirstChild());
        }

        finalNameNode.setTextContent(expectedFinalName);
    }

    XMLUtil.writeXML(doc, project.getFile());
}

From source file:org.jboss.maven.plugins.qstools.fixers.JavaSourcesFormatFixer.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*w w w.java  2s .  c  o  m*/
public void fixProject(MavenProject project, Document doc) throws Exception {
    Rules rules = getConfigurationProvider().getQuickstartsRules(project.getGroupId());
    // Read DefaultEclipseSettings
    Map<String, String> options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

    // initialize the compiler settings to be able to format 1.6 code
    String compilerSource = rules.getExpectedCompilerSource();
    options.put(JavaCore.COMPILER_COMPLIANCE, compilerSource);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, compilerSource);
    options.put(JavaCore.COMPILER_SOURCE, compilerSource);

    // Configure CodeFormatter with Eclipse XML Formatter Profile
    InputStream xmlInputStream = resources
            .getFileInputStream(new URL(rules.getEclipseFormatterProfileLocation()));
    Document formatterSettingsDoc = PositionalXMLReader.readXML(xmlInputStream);
    NodeList settingsNodes = formatterSettingsDoc.getElementsByTagName("setting");
    for (int i = 0; i < settingsNodes.getLength(); i++) {
        Node node = settingsNodes.item(i);
        String id = node.getAttributes().getNamedItem("id").getTextContent();
        String value = node.getAttributes().getNamedItem("value").getTextContent();
        options.put(id, value);
    }

    // Instantiate the default code formatter with the given options
    CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);

    // Apply the formatter to every Java source under the project's folder
    List<File> javaSources = FileUtils.getFiles(project.getBasedir(), "**/*.java", "");
    for (File javaSource : javaSources) {
        getLog().debug("Formating " + javaSource);
        String source = Files.toString(javaSource, Charset.forName("UTF-8"));
        TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, // format a compilation unit
                source, // source to format
                0, // starting position
                source.length(), // length
                0, // initial indentation
                System.getProperty("line.separator") // line separator
        );

        IDocument document = new org.eclipse.jface.text.Document(source);
        edit.apply(document);
        Files.write(document.get(), javaSource, Charset.forName("UTF-8"));
    }
}

From source file:org.jboss.maven.plugins.qstools.fixers.MavenCompilerFixer.java

License:Apache License

@Override
public void fixProject(MavenProject project, Document doc) throws Exception {

    String compilerSource = getConfigurationProvider().getQuickstartsRules(project.getGroupId())
            .getExpectedCompilerSource();

    ensurePropertiesElementExists(doc);/*from w ww  .j  av a2s  .  c o m*/
    ensurePropertySet(doc, "maven.compiler.target", compilerSource);
    ensurePropertySet(doc, "maven.compiler.source", compilerSource);

    Node compilerNode = (Node) getxPath().evaluate("//plugin[artifactId='maven-compiler-plugin']", doc,
            XPathConstants.NODE);
    Node compilerConfigNode = (Node) getxPath()
            .evaluate("//plugin[artifactId='maven-compiler-plugin']/./configuration", doc, XPathConstants.NODE);

    if (compilerNode != null && compilerConfigNode == null) {
        XMLUtil.removePreviousWhiteSpace(compilerNode);
        compilerNode.getParentNode().removeChild(compilerNode);
    } else if (compilerConfigNode != null) {
        removeConfigIfPresent(compilerConfigNode, "target");
        removeConfigIfPresent(compilerConfigNode, "source");
    }

    // Get comment over the element
    Node commentNode = null;
    if (compilerNode != null && compilerNode.getPreviousSibling() != null
            && compilerNode.getPreviousSibling() != null
            && compilerNode.getPreviousSibling().getPreviousSibling().getNodeType() == Node.COMMENT_NODE) {
        commentNode = compilerNode.getPreviousSibling().getPreviousSibling();
    }

    // Remove compiler plugin if it doesn't have any configuration
    if (compilerConfigNode != null && !XMLUtil.hasChildElements(compilerConfigNode)) {
        // If the element had a comment, remove it too.
        if (commentNode != null) {
            XMLUtil.removePreviousWhiteSpace(commentNode);
            commentNode.getParentNode().removeChild(commentNode);
        }
        XMLUtil.removePreviousWhiteSpace(compilerNode);
        compilerNode.getParentNode().removeChild(compilerNode);
    }

    XMLUtil.writeXML(doc, project.getFile());
}

From source file:org.jboss.maven.plugins.qstools.fixers.PomElementOrderFixer.java

License:Apache License

@Override
public void fixProject(MavenProject project, Document doc) throws Exception {
    List<String> pomElementsOrder = getConfigurationProvider().getQuickstartsRules(project.getGroupId())
            .getPomOrder();/*www . j  a  v a2s.c om*/
    Map<String, Node> elementsFound = pomOrderUtil.getElementsOrder(project, doc, pomElementsOrder);
    List<String> elementsList = new ArrayList<String>(elementsFound.keySet());

    for (String element : elementsList) {
        Node commentNode = null;
        Node elementNode = (Node) getxPath().evaluate("/project/" + element, doc, XPathConstants.NODE);
        // Get comment over the element
        if (elementNode.getPreviousSibling() != null
                && elementNode.getPreviousSibling().getNodeType() == Node.COMMENT_NODE) {
            commentNode = elementNode.getPreviousSibling();
        }
        for (String anotherElement : elementsList) {
            if (elementsList.indexOf(element) < elementsList.indexOf(anotherElement)) {

                Node anotherElementNode = (Node) getxPath().evaluate("/project/" + anotherElement, doc,
                        XPathConstants.NODE);
                XMLUtil.removePreviousWhiteSpace(anotherElementNode);
                anotherElementNode.getParentNode().insertBefore(elementNode, anotherElementNode);

                // If the element had a comment, move it too.
                if (commentNode != null) {
                    XMLUtil.removePreviousWhiteSpace(commentNode);
                    elementNode.getParentNode().insertBefore(commentNode, elementNode);
                }
            }
        }
    }
    XMLUtil.writeXML(doc, project.getFile());
    doc = PositionalXMLReader.readXML(new FileInputStream(project.getFile()));
    for (String element : elementsList) {
        Node commentNode = null;
        Node elementNode = (Node) getxPath().evaluate("/project/" + element, doc, XPathConstants.NODE);
        if (elementNode.getChildNodes().getLength() > 1) {
            commentNode = null;
            // Get comment over the element
            if (elementNode.getPreviousSibling() != null
                    && elementNode.getPreviousSibling().getPreviousSibling() != null && elementNode
                            .getPreviousSibling().getPreviousSibling().getNodeType() == Node.COMMENT_NODE) {
                commentNode = elementNode.getPreviousSibling().getPreviousSibling();
                XMLUtil.removePreviousWhiteSpace(commentNode);
                elementNode.getParentNode().insertBefore(doc.createTextNode("\n\n    "), commentNode);
            } else {
                XMLUtil.removePreviousWhiteSpace(elementNode);
                elementNode.getParentNode().insertBefore(doc.createTextNode("\n\n    "), elementNode);
            }
        }
    }
    XMLUtil.writeXML(doc, project.getFile());
}

From source file:org.jboss.maven.plugins.qstools.fixers.PomNameFixer.java

License:Apache License

@Override
public void fixProject(MavenProject project, Document doc) throws Exception {
    Rules rules = getConfigurationProvider().getQuickstartsRules(project.getGroupId());
    String pattern = pomNameUtil.getExpectedPattern(project, rules);
    if (!pattern.equals(project.getName())) {
        Node nameNode = (Node) getxPath().evaluate("/project/name", doc, XPathConstants.NODE);
        if (nameNode == null) {
            nameNode = doc.createElement("name");
            Node projectNode = (Node) getxPath().evaluate("/project", doc, XPathConstants.NODE);
            projectNode.appendChild(doc.createTextNode("    "));
            projectNode.appendChild(nameNode);
        }/*from w  ww . j av a  2  s.c o  m*/
        nameNode.setTextContent(pattern);
        XMLUtil.writeXML(doc, project.getFile());
    }

}

From source file:org.jboss.maven.plugins.qstools.fixers.ReadmeMetadataFixer.java

License:Apache License

@Override
public void fixProject(MavenProject project, Document doc) throws Exception {
    File readme = new File(project.getBasedir(), "README.md");
    regexPattern = readmeUtil.setupRegexPattern(project.getGroupId(), null);
    if (readme.exists()) {
        fixReadmeFile(project.getGroupId(), readme);
    }//w ww  .  j a v  a2s. c  o m

}