List of usage examples for org.apache.maven.project MavenProject getBasedir
public File getBasedir()
From source file:org.javagems.core.maven.DebianMojo.java
License:Apache License
/** * @see org.apache.maven.plugin.Mojo#execute() * @since modified by <a href="mailto:christophe@keyade.com">Christophe Cassagnabere</a> on lines 211-227 *//*from w w w.jav a 2 s. c om*/ public void execute() throws MojoExecutionException { if (skip) { getLog().info("Skipping Antrun execution"); return; } MavenProject mavenProject = getMavenProject(); if (target == null && buildFile == null) { getLog().info("No ant target defined - SKIPPED"); return; } if (target == null) { target = new XmlPlexusConfiguration("target"); } if (buildFile != null) { XmlPlexusConfiguration tg = new XmlPlexusConfiguration("target"); tg.setAttribute("name", targetName); XmlPlexusConfiguration ant = new XmlPlexusConfiguration("ant"); ant.setAttribute("antfile", buildFile); ant.addChild(tg); target.addChild(ant); } if (propertyPrefix == null) { propertyPrefix = ""; } try { Project antProject = new Project(); File antBuildFile = this.writeTargetToProjectFile(); ProjectHelper.configureProject(antProject, antBuildFile); antProject.init(); DefaultLogger antLogger = new DefaultLogger(); antLogger.setOutputPrintStream(System.out); antLogger.setErrorPrintStream(System.err); if (getLog().isDebugEnabled()) { antLogger.setMessageOutputLevel(Project.MSG_DEBUG); } else if (getLog().isInfoEnabled()) { antLogger.setMessageOutputLevel(Project.MSG_INFO); } else if (getLog().isWarnEnabled()) { antLogger.setMessageOutputLevel(Project.MSG_WARN); } else if (getLog().isErrorEnabled()) { antLogger.setMessageOutputLevel(Project.MSG_ERR); } else { antLogger.setMessageOutputLevel(Project.MSG_VERBOSE); } antProject.addBuildListener(antLogger); antProject.setBaseDir(mavenProject.getBasedir()); Path p = new Path(antProject); p.setPath(StringUtils.join(mavenProject.getCompileClasspathElements().iterator(), File.pathSeparator)); /* maven.dependency.classpath it's deprecated as it's equal to maven.compile.classpath */ antProject.addReference("maven.dependency.classpath", p); antProject.addReference("maven.compile.classpath", p); p = new Path(antProject); p.setPath(StringUtils.join(mavenProject.getRuntimeClasspathElements().iterator(), File.pathSeparator)); antProject.addReference("maven.runtime.classpath", p); p = new Path(antProject); p.setPath(StringUtils.join(mavenProject.getTestClasspathElements().iterator(), File.pathSeparator)); antProject.addReference("maven.test.classpath", p); /* set maven.plugin.classpath with plugin dependencies */ antProject.addReference("maven.plugin.classpath", getPathFromArtifacts(pluginArtifacts, antProject)); antProject.addReference(DEFAULT_MAVEN_PROJECT_REFID, getMavenProject()); antProject.addReference(DEFAULT_MAVEN_PROJECT_HELPER_REFID, projectHelper); antProject.addReference("maven.local.repository", localRepository); initMavenTasks(antProject); // The ant project needs actual properties vs. using expression evaluator when calling an external build // file. copyProperties(mavenProject, antProject); if (getLog().isInfoEnabled()) { getLog().info("Executing tasks"); } antProject.executeTarget(antTargetName); if (getLog().isInfoEnabled()) { getLog().info("Executed tasks"); } copyProperties(antProject, mavenProject); } catch (DependencyResolutionRequiredException e) { throw new MojoExecutionException("DependencyResolutionRequiredException: " + e.getMessage(), e); } catch (BuildException e) { StringBuffer sb = new StringBuffer(); sb.append("An Ant BuildException has occured: " + e.getMessage()); String fragment = findFragment(e); if (fragment != null) { sb.append("\n").append(fragment); } if (!failOnError) { getLog().info(sb.toString(), e); return; // do not register roots. } else { throw new MojoExecutionException(sb.toString(), e); } } catch (Throwable e) { throw new MojoExecutionException("Error executing ant tasks: " + e.getMessage(), e); } }
From source file:org.jboss.demos.maven.classpath.deployer.ArtifactDependencyResolver.java
License:Open Source License
/** * Resolve the dependencies of a maven project. * //w w w . java2s . co m * @param mavenProject the file to the mvn project pom * @return the included artifacts * @throws Exception for any error */ public IncludedArtifacts resolveDependencies(File mavenProject) throws Exception { // Create and validate the configuration Configuration configuration = createConfiguration(); // Create the embedder MavenEmbedder embedder = new MavenEmbedder(configuration); embedder.setLogger(logger); // Read classpath pom MavenProject project = embedder.readProject(mavenProject); MavenExecutionRequest request = new DefaultMavenExecutionRequest(); request.setBaseDirectory(project.getBasedir()); MavenExecutionResult executionResult = embedder.readProjectWithDependencies(request); Set<Artifact> artifacts = executionResult.getArtifactResolutionResult().getArtifacts(); // Process the project dependencies IncludedArtifacts included = new IncludedArtifacts(); for (Artifact artifact : artifacts) { // Add the artifact included.addArtifact(artifact); } return included; }
From source file:org.jboss.maven.plugins.qstools.AbstractProjectWalker.java
License:Apache License
@SuppressWarnings("unchecked") public void walk(WalkType walkType, MavenProject project, MavenSession mavenSession, List<MavenProject> reactorProjects, Log log, Map<String, List<Violation>> results) throws QSToolsException { this.mavenSession = mavenSession; this.log = log; try {//from w w w.j a v a2 s . c o m List<String> ignoredQuickstarts = (List<String>) context.get(Constants.IGNORED_QUICKSTARTS_CONTEXT); if (configurationProvider.getQuickstartsRules(project.getGroupId()).isCheckerIgnored(this.getClass())) { setCheckerMessage("This checker is ignored for this groupId in config file."); } else { for (MavenProject mavenProject : reactorProjects) { if (!ignoredQuickstarts.contains(mavenProject.getBasedir().getName())) { Document doc = PositionalXMLReader.readXML(new FileInputStream(mavenProject.getFile())); switch (walkType) { case CHECK: checkProject(mavenProject, doc, results); break; case FIX: fixProject(mavenProject, doc); break; default: break; } } else { log.warn("Ignoring " + mavenProject.getBasedir().getName() + ". It is listed on .quickstarts_ignore file"); } } } } catch (Exception e) { // Any other exception is a problem. throw new QSToolsException(e); } }
From source file:org.jboss.maven.plugins.qstools.checkers.AbstractCheckstyleChecker.java
License:Apache License
@Override public Map<String, List<Violation>> check(MavenProject project, MavenSession mavenSession, List<MavenProject> reactorProjects, Log log) throws QSToolsException { Map<String, List<Violation>> results = new TreeMap<String, List<Violation>>(); if (configurationProvider.getQuickstartsRules(project.getGroupId()).isCheckerIgnored(this.getClass())) { checkerMessage = "This checker is ignored for this groupId in config file."; } else {// w w w.ja va 2s . c o m CheckstyleExecutorRequest executorRequest = new CheckstyleExecutorRequest(); Rules rules = configurationProvider.getQuickstartsRules(project.getGroupId()); try { executorRequest.setReactorProjects(reactorProjects).setSourceDirectory(project.getBasedir()) .setTestSourceDirectory(project.getBasedir()).setFailsOnError(false).setProject(project) .setConfigLocation(getCheckstyleConfig()).setLog(log).setEncoding("UTF-8") .setHeaderLocation(rules.getHeaderLocation()).setIncludes(getIncludes()) .setExcludes(rules.getExcludes() + ", " + rules.getCheckerSpecificExcludes(this)); CheckstyleResults checkstyleResults = checkstyleExecutor.executeCheckstyle(executorRequest); Map<String, List<AuditEvent>> files = checkstyleResults.getFiles(); for (String file : files.keySet()) { List<AuditEvent> events = files.get(file); // If file has events/violations if (events.size() > 0) { List<Violation> violations = new ArrayList<Violation>(); for (AuditEvent event : events) { // Add each checktyle AuditEvent as a new Violation violations.add(new Violation(this.getClass(), event.getLine(), event.getMessage())); violationsQtd++; } results.put(file, violations); } } } catch (Exception e) { throw new QSToolsException(e); } } if (getCheckerMessage() != null) { log.info("--> Checker Message: " + getCheckerMessage()); } return results; }
From source file:org.jboss.maven.plugins.qstools.checkers.AbstractProjectChecker.java
License:Apache License
@Override @SuppressWarnings("unchecked") public Map<String, List<Violation>> check(MavenProject project, MavenSession mavenSession, List<MavenProject> reactorProjects, Log log) throws QSCheckerException { this.mavenSession = mavenSession; this.log = log; Map<String, List<Violation>> results = new TreeMap<String, List<Violation>>(); try {//from w ww . j a v a 2s .com List<String> ignoredQuickstarts = (List<String>) context.get(Constants.IGNORED_QUICKSTARTS_CONTEXT); for (MavenProject mavenProject : reactorProjects) { if (!ignoredQuickstarts.contains(mavenProject.getBasedir().getName())) { Document doc = PositionalXMLReader.readXML(new FileInputStream(mavenProject.getFile())); if (configurationProvider.getQuickstartsRules(project.getGroupId()).isCheckerIgnored(this)) { String msg = "Skiping %s for %s:%s"; log.warn(String.format(msg, this.getClass().getSimpleName(), project.getGroupId(), project.getArtifactId())); } else { processProject(mavenProject, doc, results); } } else { log.debug("Ignoring " + mavenProject.getBasedir().getName() + ". It is listed on .quickstarts_ignore file"); } } if (violationsQtd > 0) { log.info("There are " + violationsQtd + " checkers errors"); } } catch (Exception e) { // Any other exception is a problem. throw new QSCheckerException(e); } return results; }
From source file:org.jboss.maven.plugins.qstools.checkers.JavaEncondingChecker.java
License:Apache License
@Override public Map<String, List<Violation>> check(MavenProject project, MavenSession mavenSession, List<MavenProject> reactorProjects, Log log) throws QSToolsException { Map<String, List<Violation>> results = new TreeMap<String, List<Violation>>(); try {/*from w w w . ja v a 2 s.c om*/ if (configurationProvider.getQuickstartsRules(project.getGroupId()).isCheckerIgnored(this.getClass())) { checkerMessage = "This checker is ignored for this groupId in config file."; } else { // get all files to process List<File> sourceFiles = FileUtils.getFiles(project.getBasedir(), "**/*.java", ""); for (File source : sourceFiles) { FileInputStream fis = null; try { // Read file content as byte array (no encoding) fis = new FileInputStream(source); byte[] buf = new byte[4096]; int nread; while ((nread = fis.read(buf)) > 0 && !encodingDetector.isDone()) { encodingDetector.handleData(buf, 0, nread); } encodingDetector.dataEnd(); // report if not utf-8 String encoding = encodingDetector.getDetectedCharset(); if (encoding != null && !encoding.equalsIgnoreCase("UTF-8")) { // Get relative path based on maven work dir String rootDirectory = (mavenSession.getExecutionRootDirectory() + File.separator) .replace("\\", "\\\\"); String fileAsString = source.getAbsolutePath().replace(rootDirectory, ""); if (results.get(fileAsString) == null) { results.put(fileAsString, new ArrayList<Violation>()); } results.get(fileAsString).add(new Violation(getClass(), 0, "This file contains a non UTF-8 characters. It was detected as " + encoding)); violationsQtd++; } } finally { encodingDetector.reset(); if (fis != null) { fis.close(); } } } 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.checkers.ModuleDefinedChecker.java
License:Apache License
@Override public void checkProject(MavenProject project, Document doc, Map<String, List<Violation>> results) throws Exception { File rootDir = project.getBasedir(); List<String> submodules = new ArrayList<String>(); for (File f : rootDir.listFiles()) { if (f.isDirectory() && isProjectSubdir(f)) { submodules.add(f.getName()); }//from w w w. ja va 2s. co m } submodules.removeAll( getConfigurationProvider().getQuickstartsRules(project.getGroupId()).getIgnoredModules()); for (String dir : submodules) { boolean contains = project.getModules().contains(dir); if (!contains) { //If doesn't contains, look in other profiles for (Profile profile : project.getModel().getProfiles()) { contains = profile.getModules().contains(dir); if (contains) { break; } } } if (!contains) { String msg = "The following dir [%s] is not listed as one of project submodules"; addViolation(project.getFile(), results, 0, String.format(msg, dir)); } } }
From source file:org.jboss.maven.plugins.qstools.checkers.ReadmeChecker.java
License:Apache License
@Override public void checkProject(MavenProject project, Document doc, Map<String, List<Violation>> results) throws Exception { folderName = project.getBasedir().getName() + ":"; regexPattern = readmeUtil.setupRegexPattern(project.getGroupId(), folderName); File readme = new File(project.getBasedir(), "README.md"); if (readme.exists()) { checkReadmeFile(project.getGroupId(), readme, results); }//from w w w . ja va 2s .co m }
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 {//from w w w . j a v a2 s .c o 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
public List<PomInformation> findAllIncorrectArtifactIdNames(List<MavenProject> reactorProjects, Rules rules) throws Exception { List<PomInformation> incorrectNames = new ArrayList<PomInformation>(); try {//w ww .ja v a 2 s. co m File rootDirOfQuickstarts = getRootDirOfQuickstarts(reactorProjects.get(0)); String artifactIdPrefix = rules.getArtifactIdPrefix(); for (MavenProject subProject : reactorProjects) { Document doc = PositionalXMLReader.readXML(new FileInputStream(subProject.getFile())); String expectedArtifactId = createArtifactId(artifactIdPrefix, rootDirOfQuickstarts, subProject.getBasedir()); Node actualArtifactId = ((Node) xPath.evaluate("/project/artifactId", doc, XPathConstants.NODE)); if (!expectedArtifactId.equals(actualArtifactId.getTextContent())) { int lineNumber = getLineNumberFromNode(actualArtifactId); incorrectNames.add(new PomInformation(subProject, lineNumber, expectedArtifactId, actualArtifactId.getTextContent())); } } return incorrectNames; } catch (Exception e) { throw new QSToolsException(e); } }