List of usage examples for org.apache.maven.execution MavenExecutionResult hasExceptions
boolean hasExceptions();
From source file:com.carrotgarden.m2e.config.LaunchDelegate.java
License:BSD License
private void launchMaven(final File pomFile, final List<String> commandList, final IProgressMonitor monitor) throws CoreException { final IMaven maven = MavenPlugin.getMaven(); final Model mavenModel = maven.readModel(pomFile); final MavenProject mavenProject = new MavenProject(mavenModel); final Properties mavenProps = mavenProject.getProperties(); for (final Map.Entry<?, ?> entry : mavenProps.entrySet()) { final String key = entry.getKey().toString(); final String value = entry.getValue().toString(); // ConfigPlugin.logInfo("key= " + key + " value=" + value); }/*from www. j a v a 2 s.co m*/ // final List<String> goalList = new LinkedList<String>(); final List<String> profileActiveList = new LinkedList<String>(); final List<String> profileInactiveList = new LinkedList<String>(); for (final String command : commandList) { if (command.startsWith("-")) { /** command line options */ if (command.startsWith("--activate-profiles")) { ConfigPlugin.log(IStatus.ERROR, "TODO : " + command); } else { ConfigPlugin.log(IStatus.ERROR, "not supported : " + command); } } else { /** maven execution goals */ goalList.add(command); } } // final MavenExecutionRequest request = maven.createExecutionRequest(monitor); request.setPom(pomFile); request.setGoals(goalList); // TODO // request.setActiveProfiles(profileActiveList); // request.setInactiveProfiles(profileInactiveList); // final String id = mavenProject.getId(); ConfigPlugin.log(IStatus.INFO, "maven execute : " + mavenProject.getId() + " " + MojoUtil.join(commandList, ",")); // final Job job = new Job(id) { // { // setSystem(true); // setPriority(BUILD); // } // @Override // protected IStatus run(final IProgressMonitor monitor) { // return null; // } // }; final MavenExecutionResult result = maven.execute(request, monitor); if (result.hasExceptions()) { throw new CoreException(new Status(IStatus.ERROR, ConfigPlugin.ID, "maven execution failed", result.getExceptions().get(0))); } }
From source file:com.cloudbees.eclipse.m2e.CBMavenUtils.java
License:Open Source License
public static IFile runMaven(IProject project, IProgressMonitor monitor, String[] goals) throws CloudBeesException { boolean pomExists = project.exists(new Path("/pom.xml")); if (!pomExists) { return null; }/*from w ww . ja va2 s . c o m*/ IMaven maven = MavenPlugin.getMaven(); String version = MavenPlugin.getMavenRuntimeManager().getDefaultRuntime().getVersion(); MavenExecutionRequest request; IMavenProjectFacade mpr = MavenPlugin.getMavenProjectRegistry().getProject(project); try { if (mpr == null) { // maven not configured for the project. But as pom.xml existed, let's configure. NatureUtil.addNatures(project, new String[] { CloudBeesNature.NATURE_ID, JavaCore.NATURE_ID, "org.eclipse.m2e.core.maven2Nature" }, monitor); project.refreshLocal(IProject.DEPTH_INFINITE, monitor); mpr = MavenPlugin.getMavenProjectRegistry().getProject(project); } request = maven.createExecutionRequest(monitor); } catch (CoreException e) { throw new CloudBeesException("Failed to prepare maven war preparation request", e); } //IMavenProjectFacade facade = projectManager.create(pomFile, true, new SubProgressMonitor(monitor, 1)); //ResolverConfiguration config = mpr.getResolverConfiguration(); request.setPom(project.getFile(new Path("/pom.xml")).getRawLocation().toFile()); //request.setBaseDirectory(project.getRawLocation().toFile()); request.getSystemProperties().put("maven.test.skip", "true"); //MavenExecutionRequest request = projectManager.createExecutionRequest(pomFile, config, new SubProgressMonitor(monitor, 1)); //request.getUserProperties().setProperty("m2e.version", MavenPlugin.getVersion()); //goals.add("package"); //goals.add("eclipse:eclipse"); request.setGoals(Arrays.asList(goals)); //MavenPlugin.getConsole().showConsole(); MavenExecutionResult result = maven.execute(request, monitor); if (result.hasExceptions()) { // Throw CoreException //System.out.println("Got exceptions while running!"); Iterator<Throwable> it = result.getExceptions().iterator(); Throwable e = null; while (it.hasNext()) { Throwable throwable = (Throwable) it.next(); throwable.printStackTrace(); e = throwable; } throw new CloudBeesException("Maven build failed!", e); } BuildSummary summary = result.getBuildSummary(result.getProject()); MavenProject proj = summary.getProject(); Artifact artifact = proj.getArtifact(); File f = artifact.getFile(); //System.out.println("Artifact: " + f); //System.out.println("Artifact name: " + f.getName()); if (f == null) { return null; } if (BeesSDK.hasSupportedExtension(f.getName())) { String apath = f.getAbsolutePath().substring(project.getLocation().toFile().getAbsolutePath().length()); //System.out.println("APATH: " + apath); return project.getFile(apath); } return null; }
From source file:com.github.swt_release_fetcher.Artifact.java
License:Apache License
public void runMavenDeploy(File pomFile, File jarFile, File sourcesFile) { Properties properties = new Properties(); properties.put("pomFile", pomFile.getAbsolutePath()); properties.put("file", jarFile.getAbsolutePath()); properties.put("sources", sourcesFile.getAbsolutePath()); properties.put("repositoryId", "googlecode"); properties.put("url", REPOSITORY_URL); MavenExecutionRequest request = new DefaultMavenExecutionRequest(); request.setPom(pomFile);// w w w. j av a2 s . co m request.setGoals(Arrays.asList(new String[] { "deploy:deploy-file" })); request.setSystemProperties(properties); Maven maven = EmbeddedMaven.get(); MavenExecutionResult result = maven.execute(request); if (result.hasExceptions()) { System.out.println("Maven deploy failed!"); System.out.println(result.getExceptions()); throw new RuntimeException("Maven deploy failed!", result.getExceptions().get(0)); } else { System.out.println("Maven deploy succeeded!"); } }
From source file:com.google.code.play2.plugin.MavenPlay2Builder.java
License:Apache License
@Override /* Play2Builder */ public boolean build() throws Play2BuildFailure, Play2BuildError/*Play2BuildException*/ { Set<String> changedFilePaths = null; Map<String, Long> prevChangedFiles = new HashMap<String, Long>(); synchronized (changedFilesLock) { if (!changedFiles.isEmpty()) { changedFilePaths = changedFiles.keySet(); prevChangedFiles = changedFiles; changedFiles = new HashMap<String, Long>(); }//ww w . j ava 2 s. c om //TEST - more code inside synchronized block } if (!forceReloadNextTime && changedFilePaths == null /*&& afterFirstSuccessfulBuild*/ ) { return false; } List<MavenProject> projectsToBuild = projects; // - !afterFirstSuccessfulBuild => first build or no previous successful builds, build all modules // - currentSourceMaps.isEmpty() => first build, build all modules // - projects.size() == 1 => one-module project, just build it // - else => not the first build in multimodule-project, calculate modules subset to build if (afterFirstSuccessfulBuild /*!currentSourceMaps.isEmpty()*//*currentSourceMap != null*/ && projects.size() > 1) { projectsToBuild = calculateProjectsToBuild(changedFilePaths); } MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest()); request.setStartTime(new Date()); request.setExecutionListener(new ExecutionEventLogger()); request.setGoals(goals); MavenExecutionResult result = new DefaultMavenExecutionResult(); MavenSession newSession = new MavenSession(container, session.getRepositorySession(), request, result); newSession.setProjects(projectsToBuild); newSession.setCurrentProject(session.getCurrentProject()); newSession.setParallel(session.isParallel()); newSession.setProjectDependencyGraph(session.getProjectDependencyGraph()); lifecycleExecutor.execute(newSession); forceReloadNextTime = result.hasExceptions(); if (!result.hasExceptions() && !additionalGoals.isEmpty()) { request = DefaultMavenExecutionRequest.copy(session.getRequest()); request.setStartTime(new Date()); request.setExecutionListener(new ExecutionEventLogger()); request.setGoals(additionalGoals); result = new DefaultMavenExecutionResult(); newSession = new MavenSession(container, session.getRepositorySession(), request, result); List<MavenProject> onlyMe = Arrays.asList(new MavenProject[] { session.getCurrentProject() }); newSession.setProjects(onlyMe); newSession.setCurrentProject(session.getCurrentProject()); newSession.setParallel(session.isParallel()); newSession.setProjectDependencyGraph(session.getProjectDependencyGraph()); lifecycleExecutor.execute(newSession); forceReloadNextTime = result.hasExceptions(); } if (result.hasExceptions()) { synchronized (changedFilesLock) { changedFiles.putAll(prevChangedFiles); // restore previously changed paths, required for next rebuild } Throwable firstException = result.getExceptions().get(0); if (firstException.getCause() instanceof MojoFailureException) { MojoFailureException mfe = (MojoFailureException) firstException.getCause(); Throwable mfeCause = mfe.getCause(); if (mfeCause != null) { try { Play2BuildException pbe = null; String causeName = mfeCause.getClass().getName(); // sbt-compiler exception if (CompilerException.class.getName().equals(causeName)) { pbe = getSBTCompilerBuildException(mfeCause); } else if (AssetCompilationException.class.getName().equals(causeName) || RoutesCompilationException.class.getName().equals(causeName) || TemplateCompilationException.class.getName().equals(causeName)) { pbe = getPlayBuildException(mfeCause); } if (pbe != null) { throw new Play2BuildFailure(pbe, sourceEncoding); } throw new Play2BuildError("Build failed without reporting any problem!"/*?, ce*/ ); } catch (Play2BuildFailure e) { throw e; } catch (Play2BuildError e) { throw e; } catch (Exception e) { throw new Play2BuildError(".... , check Maven console"); } } } throw new Play2BuildError("The compilation task failed, check Maven console"/*?, firstException*/ ); } // no exceptions if (!afterFirstSuccessfulBuild) // this was first successful build { afterFirstSuccessfulBuild = true; if (playWatchService != null) { // Monitor all existing, not generated (inside output directory) source and resource roots List<File> monitoredDirectories = new ArrayList<File>(); for (MavenProject p : projects) { String targetDirectory = p.getBuild().getDirectory(); for (String sourceRoot : p.getCompileSourceRoots()) { if (!sourceRoot.startsWith(targetDirectory) && new File(sourceRoot).isDirectory()) { monitoredDirectories.add(new File(sourceRoot)); } } for (Resource resource : p.getResources()) { String resourceRoot = resource.getDirectory(); if (!resourceRoot.startsWith(targetDirectory) && new File(resourceRoot).isDirectory()) { monitoredDirectories.add(new File(resourceRoot)); } } } //TODO - remove roots nested inside another roots (is it possible?) try { watcher = playWatchService.watch(monitoredDirectories, this); } catch (FileWatchException e) { logger.warn("File watcher initialization failed. Running without hot-reload functionality.", e); } } } Map<MavenProject, Map<String, File>> sourceMaps = new HashMap<MavenProject, Map<String, File>>( currentSourceMaps); for (MavenProject p : projectsToBuild) { Map<String, File> sourceMap = new HashMap<String, File>(); File classesDirectory = new File(p.getBuild().getOutputDirectory()); String classesDirectoryPath = classesDirectory.getAbsolutePath() + File.separator; File analysisCacheFile = defaultAnalysisCacheFile(p); Analysis analysis = sbtAnalysisProcessor.readFromFile(analysisCacheFile); for (File sourceFile : analysis.getSourceFiles()) { Set<File> sourceFileProducts = analysis.getProducts(sourceFile); for (File product : sourceFileProducts) { String absolutePath = product.getAbsolutePath(); if (absolutePath.contains("$")) { continue; // skip inner and object classes } String relativePath = absolutePath.substring(classesDirectoryPath.length()); // String name = product.getName(); String name = relativePath.substring(0, relativePath.length() - ".class".length()); /*if (name.indexOf( '$' ) > 0) { name = name.substring( 0, name.indexOf( '$' ) ); }*/ name = name.replace(File.separator, "."); //System.out.println(sourceFile.getPath() + " -> " + name); sourceMap.put(name, sourceFile); } /*String[] definitionNames = analysis.getDefinitionNames( sourceFile ); Set<String> uniqueDefinitionNames = new HashSet<String>(definitionNames.length); for (String definitionName: definitionNames) { if ( !uniqueDefinitionNames.contains( definitionName ) ) { result.put( definitionName, sourceFile ); // System.out.println( "definitionName:'" + definitionName + "', source:'" // + sourceFile.getAbsolutePath() + "'" ); uniqueDefinitionNames.add( definitionName ); } }*/ } sourceMaps.put(p, sourceMap); } this.currentSourceMaps = sourceMaps; boolean reloadRequired = false; for (MavenProject p : projectsToBuild) { long lastModifiedTime = 0L; Set<String> outputFilePaths = new HashSet<String>(); File outputDirectory = new File(p.getBuild().getOutputDirectory()); if (outputDirectory.exists() && outputDirectory.isDirectory()) { DirectoryScanner classPathScanner = new DirectoryScanner(); classPathScanner.setBasedir(outputDirectory); classPathScanner.setExcludes(new String[] { assetsPrefix + "**" }); classPathScanner.scan(); String[] files = classPathScanner.getIncludedFiles(); for (String fileName : files) { File f = new File(outputDirectory, fileName); outputFilePaths.add(f.getAbsolutePath()); long lmf = f.lastModified(); if (lmf > lastModifiedTime) { lastModifiedTime = lmf; } } } if (!reloadRequired && (lastModifiedTime > currentClasspathTimestamps.get(p).longValue() || !outputFilePaths.equals(currentClasspathFilePaths.get(p)))) { reloadRequired = true; } currentClasspathTimestamps.put(p, Long.valueOf(lastModifiedTime)); currentClasspathFilePaths.put(p, outputFilePaths); } return reloadRequired; }
From source file:com.google.gdt.eclipse.maven.e35.configurators.GoogleProjectConfigurator.java
License:Open Source License
@Override protected void doConfigure(final MavenProject mavenProject, IProject project, ProjectConfigurationRequest request, final IProgressMonitor monitor) throws CoreException { final IMaven maven = MavenPlugin.getDefault().getMaven(); boolean configureGaeNatureSuccess = configureNature(project, mavenProject, GaeNature.NATURE_ID, true, new NatureCallbackAdapter() { @Override//from ww w . jav a 2 s . c o m public void beforeAddingNature() { try { DefaultMavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest(); executionRequest.setBaseDirectory(mavenProject.getBasedir()); executionRequest.setLocalRepository(maven.getLocalRepository()); executionRequest.setRemoteRepositories(mavenProject.getRemoteArtifactRepositories()); executionRequest .setPluginArtifactRepositories(mavenProject.getPluginArtifactRepositories()); executionRequest.setPom(mavenProject.getFile()); executionRequest.setGoals(GAE_UNPACK_GOAL); MavenExecutionResult result = maven.execute(executionRequest, monitor); if (result.hasExceptions()) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error configuring project", result.getExceptions().get(0))); } } catch (CoreException e) { Activator.getDefault().getLog().log( new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error configuring project", e)); } } }, monitor); boolean configureGWTNatureSuccess = configureNature(project, mavenProject, GWTNature.NATURE_ID, true, new NatureCallbackAdapter() { @Override public void beforeAddingNature() { // Get the GWT version from the project pom String gwtVersion = null; List<Dependency> dependencies = mavenProject.getDependencies(); for (Dependency dependency : dependencies) { if (GWTMavenRuntime.MAVEN_GWT_GROUP_ID.equals(dependency.getGroupId()) && (GWTMavenRuntime.MAVEN_GWT_USER_ARTIFACT_ID .equals(dependency.getArtifactId()) || GWTMavenRuntime.MAVEN_GWT_SERVLET_ARTIFACT_ID .equals(dependency.getArtifactId()))) { gwtVersion = dependency.getVersion(); break; } } // Check that the pom.xml has GWT dependencies if (!StringUtilities.isEmpty(gwtVersion)) { try { /* * Download and install the gwt-dev.jar into the local * repository. */ maven.resolve(GWTMavenRuntime.MAVEN_GWT_GROUP_ID, GWTMavenRuntime.MAVEN_GWT_DEV_JAR_ARTIFACT_ID, gwtVersion, "jar", null, mavenProject.getRemoteArtifactRepositories(), monitor); } catch (CoreException e) { Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error configuring project", e)); } } } }, monitor); if (configureGWTNatureSuccess || configureGaeNatureSuccess) { try { // Add GWT Web Application configuration parameters WebAppProjectProperties.setWarSrcDir(project, new Path("src/main/webapp")); WebAppProjectProperties.setWarSrcDirIsOutput(project, false); String artifactId = mavenProject.getArtifactId(); String version = mavenProject.getVersion(); IPath location = (project.getRawLocation() != null ? project.getRawLocation() : project.getLocation()); if (location != null && artifactId != null && version != null) { WebAppProjectProperties.setLastUsedWarOutLocation(project, location.append("target").append(artifactId + "-" + version)); } } catch (BackingStoreException be) { Activator.getDefault().getLog() .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error configuring project", be)); } } }
From source file:de.lgohlke.sonar.maven.Maven3SonarEmbedder.java
License:Open Source License
public void run() throws MavenEmbedderException { try {//from w ww.j a v a 2 s. c o m MavenExecutionResult result = embedder.execute(mavenRequest); if (result.hasExceptions()) { final Throwable firstException = result.getExceptions().get(0); throw new MavenEmbedderException(firstException); } } catch (ComponentLookupException e) { throw new MavenEmbedderException(e); } }
From source file:org.commonjava.emb.boot.embed.EMBEmbedder.java
License:Apache License
public int formatErrorOutput(final EMBExecutionRequest request, final MavenExecutionResult result) { if (result.hasExceptions()) { final ExceptionHandler handler = new DefaultExceptionHandler(); final Map<String, String> references = new LinkedHashMap<String, String>(); MavenProject project = null;/*ww w .j av a2 s.c o m*/ for (final Throwable exception : result.getExceptions()) { final ExceptionSummary summary = handler.handleException(exception); logSummary(summary, references, "", shouldShowErrors); if (project == null && exception instanceof LifecycleExecutionException) { project = ((LifecycleExecutionException) exception).getProject(); } } logger.error(""); if (!shouldShowErrors) { logger.error("To see the full stack trace of the errors, re-run Maven with the -e switch."); } if (!logger.isDebugEnabled()) { logger.error("Re-run Maven using the -X switch to enable full debug logging."); } if (!references.isEmpty()) { logger.error(""); logger.error("For more information about the errors and possible solutions" + ", please read the following articles:"); for (final Map.Entry<String, String> entry : references.entrySet()) { logger.error(entry.getValue() + " " + entry.getKey()); } } if (project != null && !project.equals(result.getTopologicallySortedProjects().get(0))) { logger.error(""); logger.error("After correcting the problems, you can resume the build with the command"); logger.error(" mvn <goals> -rf :" + project.getArtifactId()); } if (MavenExecutionRequest.REACTOR_FAIL_NEVER.equals(request.getReactorFailureBehavior())) { logger.info("Build failures were ignored."); return 0; } else { return 1; } } else { return 0; } }
From source file:org.commonjava.sjbi.maven3.builder.M3BuildResult.java
License:Open Source License
M3BuildResult(final MavenExecutionResult mavenResult) { if (mavenResult.hasExceptions()) { setErrors(mavenResult.getExceptions()); }/* w w w . j av a2s . c o m*/ final List<ArtifactSetRef> ars = new ArrayList<ArtifactSetRef>(); for (final MavenProject project : mavenResult.getTopologicallySortedProjects()) { final ProjectRef pr = new ProjectRef(project.getGroupId(), project.getArtifactId(), project.getVersion()); pr.setPomFile(project.getFile()); final ArtifactSetRef ar = new ArtifactSetRef(pr); final Artifact mainArtifact = project.getArtifact(); ar.addArtifactRef(mainArtifact.getType(), mainArtifact.getClassifier(), mainArtifact.getFile()); for (final Artifact a : project.getAttachedArtifacts()) { ar.addArtifactRef(a.getType(), a.getClassifier(), a.getFile()); } ars.add(ar); } setArtifactSets(ars); }
From source file:org.eclipse.m2e.core.internal.builder.MavenBuilderImpl.java
License:Open Source License
private void processMavenSessionErrors(MavenSession session, MojoExecutionKey mojoExecutionKey, Map<Throwable, MojoExecutionKey> buildErrors) { MavenExecutionResult result = session.getResult(); if (result.hasExceptions()) { for (Throwable e : result.getExceptions()) { buildErrors.put(e, mojoExecutionKey); }/*w w w . java2 s. co m*/ result.getExceptions().clear(); } }
From source file:org.eclipse.m2e.core.internal.builder.MavenBuilderImpl.java
License:Open Source License
private void processBuildResults(IProject project, MavenProject mavenProject, MavenExecutionResult result, AbstractEclipseBuildContext buildContext, Map<Throwable, MojoExecutionKey> buildErrors) { IMavenMarkerManager markerManager = MavenPluginActivator.getDefault().getMavenMarkerManager(); // Remove obsolete markers for problems reported by build participants for (Entry<String, List<File>> entry : buildContext.getRemoveMessages().entrySet()) { String buildParticipantId = entry.getKey(); for (File file : entry.getValue()) { deleteBuildParticipantMarkers(project, markerManager, file, buildParticipantId); }//from w w w. j a v a 2 s . c om } // Create new markers for problems reported by build participants for (Entry<String, List<Message>> messageEntry : buildContext.getMessages().entrySet()) { String buildParticipantId = messageEntry.getKey(); for (Message buildMessage : messageEntry.getValue()) { addBuildParticipantMarker(project, markerManager, buildMessage, buildParticipantId); if (buildMessage.cause != null && buildErrors.containsKey(buildMessage.cause)) { buildErrors.remove(buildMessage.cause); } } } // Create markers for the build errors linked to mojo/plugin executions for (Throwable error : buildErrors.keySet()) { MojoExecutionKey mojoExecutionKey = buildErrors.get(error); SourceLocation markerLocation; if (mojoExecutionKey != null) { markerLocation = SourceLocationHelper.findLocation(mavenProject, mojoExecutionKey); } else { markerLocation = new SourceLocation(1, 0, 0); } BuildProblemInfo problem = new BuildProblemInfo(error, mojoExecutionKey, markerLocation); markerManager.addErrorMarker(project.getFile(IMavenConstants.POM_FILE_NAME), IMavenConstants.MARKER_BUILD_ID, problem); } if (result.hasExceptions()) { markerManager.addMarkers(project.getFile(IMavenConstants.POM_FILE_NAME), IMavenConstants.MARKER_BUILD_ID, result); } }