public static boolean checkByCLIMavenValidationLevel(ModelProblem problem) { // XXX HACK - this should be properly solved by upgrading the embeded maven String version = MavenSettings.getCommandLineMavenVersion(); try { if ( version != null && !"".equals(version.trim()) && new DefaultArtifactVersion(version).compareTo(new DefaultArtifactVersion("3.2.1")) > 0) { if ( (problem.getMessage().startsWith("'dependencies.dependency.exclusions.exclusion.groupId' for ") || problem.getMessage().startsWith("'dependencies.dependency.exclusions.exclusion.artifactId' for ")) && problem.getMessage().contains(" with value '*' does not match a valid id pattern")) { return false; } } } catch (Throwable e) { // ignore and be optimistic about the hint LOG.log(Level.INFO, version, e); } return true; }
private static String createMessage( List<ProjectBuildingResult> results ) { StringWriter buffer = new StringWriter( 1024 ); PrintWriter writer = new PrintWriter( buffer ); writer.println( "Some problems were encountered while processing the POMs:" ); for ( ProjectBuildingResult result : results ) { for ( ModelProblem problem : result.getProblems() ) { writer.print( "[" ); writer.print( problem.getSeverity() ); writer.print( "] " ); writer.print( problem.getMessage() ); writer.print( " @ " ); writer.println( ModelProblemUtils.formatLocation( problem, result.getProjectId() ) ); } } writer.close(); return buffer.toString(); }
private ModelProblem hasMissingParentPom( ProjectBuildingException e ) { if ( e.getCause() instanceof ModelBuildingException ) { ModelBuildingException mbe = (ModelBuildingException) e.getCause(); for ( ModelProblem problem : mbe.getProblems() ) { if ( problem.getException() instanceof UnresolvableModelException ) { return problem; } } } return null; }
private ExceptionSummary handle( ProjectBuildingResult result ) { List<ExceptionSummary> children = new ArrayList<ExceptionSummary>(); for ( ModelProblem problem : result.getProblems() ) { ExceptionSummary child = handle( problem, result.getProjectId() ); if ( child != null ) { children.add( child ); } } if ( children.isEmpty() ) { return null; } String message = "\nThe project " + result.getProjectId() + " (" + result.getPomFile() + ") has " + children.size() + " error" + ( children.size() == 1 ? "" : "s" ); return new ExceptionSummary( null, message, null, children ); }
private ExceptionSummary handle( ModelProblem problem, String projectId ) { if ( ModelProblem.Severity.ERROR.compareTo( problem.getSeverity() ) >= 0 ) { String message = problem.getMessage(); String location = ModelProblemUtils.formatLocation( problem, projectId ); if ( StringUtils.isNotEmpty( location ) ) { message += " @ " + location; } return handle( message, problem.getException() ); } else { return null; } }
static List<ModelProblem> runMavenValidationImpl(final File pom) { //TODO profiles based on current configuration?? MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder(); MavenExecutionRequest meReq = embedder.createMavenExecutionRequest(); ProjectBuildingRequest req = meReq.getProjectBuildingRequest(); req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1); // currently enables just <reporting> warning req.setLocalRepository(embedder.getLocalRepository()); List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder); req.setRemoteRepositories(remoteRepos); req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq)); List<ModelProblem> problems; try { problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems(); } catch (ProjectBuildingException x) { problems = new ArrayList<ModelProblem>(); List<ProjectBuildingResult> results = x.getResults(); if (results != null) { //one code point throwing ProjectBuildingException contains results, for (ProjectBuildingResult result : results) { problems.addAll(result.getProblems()); } } else { // another code point throwing ProjectBuildingException doesn't contain results.. Throwable cause = x.getCause(); if (cause instanceof ModelBuildingException) { problems.addAll(((ModelBuildingException) cause).getProblems()); } } } return problems; }
static Node createErrorNode(ModelBuildingException x) { AbstractNode an = new AbstractNode(Children.LEAF); StringBuilder b = new StringBuilder(); for (ModelProblem p : x.getProblems()) { if (b.length() > 0) { b.append("; "); } b.append(p.getMessage()); } an.setDisplayName(b.toString()); return an; }
private static void runMavenValidation(final POMModel model, final List<ErrorDescription> err) { File pom = model.getModelSource().getLookup().lookup(File.class); if (pom == null) { return; } List<ModelProblem> problems = runMavenValidationImpl(pom); for (ModelProblem problem : problems) { if (!problem.getSource().equals(pom.getAbsolutePath())) { LOG.log(Level.FINE, "found problem not in {0}: {1}", new Object[] {pom, problem.getSource()}); continue; } int line = problem.getLineNumber(); if (line <= 0) { // probably from a parent POM /* probably more irritating than helpful: line = 1; // fallback Parent parent = model.getProject().getPomParent(); if (parent != null) { Line l = NbEditorUtilities.getLine(model.getBaseDocument(), parent.findPosition(), false); if (l != null) { line = l.getLineNumber() + 1; } } */ continue; } if (problem.getException() instanceof UnresolvableModelException) { // If a <parent> reference cannot be followed because e.g. no projects are opened (so no repos registered), just ignore it. continue; } try { err.add(ErrorDescriptionFactory.createErrorDescription(problem.getSeverity() == ModelProblem.Severity.WARNING ? Severity.WARNING : Severity.ERROR, problem.getMessage(), model.getBaseDocument(), line)); } catch (IndexOutOfBoundsException x) { LOG.log(Level.WARNING, "improper line number: {0}", problem); } } }
static List<ModelProblem> runMavenValidationImpl(final File pom) { MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder(); MavenExecutionRequest meReq = embedder.createMavenExecutionRequest(); ProjectBuildingRequest req = meReq.getProjectBuildingRequest(); req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0); // 3.1 currently enables just <reporting> warning, see issue 223562 for details on why it's bad to show. req.setLocalRepository(embedder.getLocalRepository()); List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder); req.setRemoteRepositories(remoteRepos); req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq)); List<ModelProblem> problems; try { problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems(); } catch (ProjectBuildingException x) { problems = new ArrayList<ModelProblem>(); List<ProjectBuildingResult> results = x.getResults(); if (results != null) { //one code point throwing ProjectBuildingException contains results, for (ProjectBuildingResult result : results) { problems.addAll(result.getProblems()); } } else { // another code point throwing ProjectBuildingException doesn't contain results.. Throwable cause = x.getCause(); if (cause instanceof ModelBuildingException) { problems.addAll(((ModelBuildingException) cause).getProblems()); } } } List<ModelProblem> toRet = new LinkedList<ModelProblem>(); for (ModelProblem problem : problems) { if(ModelUtils.checkByCLIMavenValidationLevel(problem)) { toRet.add(problem); } } return toRet; }
public Model loadPomFromFile(File pomFile, String... profiles) { RepositorySystem system = mavenContainer.getRepositorySystem(); Settings settings = mavenContainer.getSettings(); DefaultRepositorySystemSession session = mavenContainer.setupRepoSession(system, settings); final DefaultModelBuildingRequest request = new DefaultModelBuildingRequest() .setSystemProperties(System.getProperties()) .setPomFile(pomFile) .setActiveProfileIds(settings.getActiveProfiles()); ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); ModelBuildingResult result; try { request.setModelResolver(new MavenModelResolver(system, session, MavenRepositories.getRemoteRepositories(mavenContainer, settings))); result = builder.build(request); } // wrap exception message catch (ModelBuildingException e) { String pomPath = request.getPomFile().getAbsolutePath(); StringBuilder sb = new StringBuilder("Found ").append(e.getProblems().size()) .append(" problems while building POM model from ").append(pomPath).append("\n"); int counter = 1; for (ModelProblem problem : e.getProblems()) { sb.append(counter++).append("/ ").append(problem).append("\n"); } throw new RuntimeException(sb.toString()); } return result.getEffectiveModel(); }
public void add( ModelProblemCollectorRequest req ) { if ( !ModelProblem.Severity.WARNING.equals( req.getSeverity() ) ) { result.addMessage( req.getMessage() ); } }
public List getActiveProfiles() throws ProfileActivationException { DefaultProfileActivationContext context = new DefaultProfileActivationContext(); context.setActiveProfileIds( activatedIds ); context.setInactiveProfileIds( deactivatedIds ); context.setSystemProperties( System.getProperties() ); context.setUserProperties( requestProperties ); final List<ProfileActivationException> errors = new ArrayList<ProfileActivationException>(); List<Profile> profiles = profileSelector.getActiveProfiles( profilesById.values(), context, new ModelProblemCollector() { public void add( ModelProblemCollectorRequest req ) { if ( !ModelProblem.Severity.WARNING.equals( req.getSeverity() ) ) { errors.add( new ProfileActivationException( req.getMessage(), req.getException() ) ); } } } ); if ( !errors.isEmpty() ) { throw errors.get( 0 ); } return profiles; }
protected MavenProject getProjectWithDependencies( File pom ) throws Exception { ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); configuration.setLocalRepository( getLocalRepository() ); configuration.setRemoteRepositories( Arrays.asList( new ArtifactRepository[] {} ) ); configuration.setProcessPlugins( false ); configuration.setResolveDependencies( true ); initRepoSession( configuration ); try { return projectBuilder.build( pom, configuration ).getProject(); } catch ( Exception e ) { Throwable cause = e.getCause(); if ( cause instanceof ModelBuildingException ) { String message = "In: " + pom + "\n\n"; for ( ModelProblem problem : ( (ModelBuildingException) cause ).getProblems() ) { message += problem + "\n"; } System.out.println( message ); fail( message ); } throw e; } }
/** * Creates a new result with the specified contents. * * @param project The project that was built, may be {@code null}. * @param problems The problems that were encouterned, may be {@code null}. * @param dependencyResolutionResult The result of the resolution for the project dependencies, may be {@code null}. */ public DefaultProjectBuildingResult( MavenProject project, List<ModelProblem> problems, DependencyResolutionResult dependencyResolutionResult ) { this.projectId = ( project != null ) ? project.getGroupId() + ':' + project.getArtifactId() + ':' + project.getVersion() : ""; this.pomFile = ( project != null ) ? project.getFile() : null; this.project = project; this.problems = problems; this.dependencyResolutionResult = dependencyResolutionResult; }
public List<ModelProblem> getProblems() { if ( problems == null ) { problems = new ArrayList<ModelProblem>(); } return problems; }
private void collectProjects( List<MavenProject> projects, List<File> files, MavenExecutionRequest request ) throws ProjectBuildingException { ProjectBuildingRequest projectBuildingRequest = request.getProjectBuildingRequest(); List<ProjectBuildingResult> results = projectBuilder.build( files, request.isRecursive(), projectBuildingRequest ); boolean problems = false; for ( ProjectBuildingResult result : results ) { projects.add( result.getProject() ); if ( !result.getProblems().isEmpty() && logger.isWarnEnabled() ) { logger.warn( "" ); logger.warn( "Some problems were encountered while building the effective model for " + result.getProject().getId() ); for ( ModelProblem problem : result.getProblems() ) { String location = ModelProblemUtils.formatLocation( problem, result.getProjectId() ); logger.warn( problem.getMessage() + ( StringUtils.isNotEmpty( location ) ? " @ " + location : "" ) ); } problems = true; } } if ( problems ) { logger.warn( "" ); logger.warn( "It is highly recommended to fix these problems" + " because they threaten the stability of your build." ); logger.warn( "" ); logger.warn( "For this reason, future Maven versions might no" + " longer support building such malformed projects." ); logger.warn( "" ); } }
protected MavenProject getProjectWithDependencies( File pom ) throws Exception { ProjectBuildingRequest configuration = newBuildingRequest(); configuration.setRemoteRepositories( Arrays.asList( new ArtifactRepository[] {} ) ); configuration.setProcessPlugins( false ); configuration.setResolveDependencies( true ); try { return projectBuilder.build( pom, configuration ).getProject(); } catch ( Exception e ) { Throwable cause = e.getCause(); if ( cause instanceof ModelBuildingException ) { String message = "In: " + pom + "\n\n"; for ( ModelProblem problem : ( (ModelBuildingException) cause ).getProblems() ) { message += problem + "\n"; } System.out.println( message ); } throw e; } }
public Model loadPomFromFile(File pomFile, String... profiles) { RepositorySystem system = mavenContainer.getRepositorySystem(); Settings settings = mavenContainer.getSettings(); DefaultRepositorySystemSession session = mavenContainer.setupRepoSession(system, settings); final DefaultModelBuildingRequest request = new DefaultModelBuildingRequest() .setSystemProperties(System.getProperties()) .setPomFile(pomFile) .setActiveProfileIds(settings.getActiveProfiles()); ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); ModelBuildingResult result; try { request.setModelResolver(new MavenModelResolver(system, session, mavenContainer .getEnabledRepositoriesFromProfile(settings))); result = builder.build(request); } // wrap exception message catch (ModelBuildingException e) { String pomPath = request.getPomFile().getAbsolutePath(); StringBuilder sb = new StringBuilder("Found ").append(e.getProblems().size()) .append(" problems while building POM model from ").append(pomPath).append("\n"); int counter = 1; for (ModelProblem problem : e.getProblems()) { sb.append(counter++).append("/ ").append(problem).append("\n"); } throw new RuntimeException(sb.toString()); } return result.getEffectiveModel(); }
@NbBundle.Messages({ "TXT_Artifact_Resolution_problem=Artifact Resolution problem", "TXT_Artifact_Not_Found=Artifact Not Found", "TXT_Cannot_Load_Project=Unable to properly load project", "TXT_Cannot_read_model=Error reading project model", "TXT_NoMsg=Exception thrown while loading maven project at {0}. See messages.log for more information." }) private Collection<ProjectProblem> reportExceptions(MavenExecutionResult res) { List<ProjectProblem> toRet = new ArrayList<ProjectProblem>(); for (Throwable e : res.getExceptions()) { LOG.log(Level.FINE, "Error on loading project " + project.getProjectDirectory(), e); if (e instanceof ArtifactResolutionException) { // XXX when does this occur? toRet.add(ProjectProblem.createError(TXT_Artifact_Resolution_problem(), getDescriptionText(e))); problemReporter.addMissingArtifact(((ArtifactResolutionException) e).getArtifact()); } else if (e instanceof ArtifactNotFoundException) { // XXX when does this occur? toRet.add(ProjectProblem.createError(TXT_Artifact_Not_Found(), getDescriptionText(e))); problemReporter.addMissingArtifact(((ArtifactNotFoundException) e).getArtifact()); } else if (e instanceof ProjectBuildingException) { toRet.add(ProjectProblem.createError(TXT_Cannot_Load_Project(), getDescriptionText(e), new SanityBuildAction(project))); if (e.getCause() instanceof ModelBuildingException) { ModelBuildingException mbe = (ModelBuildingException) e.getCause(); for (ModelProblem mp : mbe.getProblems()) { LOG.log(Level.FINE, mp.toString(), mp.getException()); if (mp.getException() instanceof UnresolvableModelException) { // Probably obsoleted by ProblemReporterImpl.checkParent, but just in case: UnresolvableModelException ume = (UnresolvableModelException) mp.getException(); problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createProjectArtifact(ume.getGroupId(), ume.getArtifactId(), ume.getVersion())); } else if (mp.getException() instanceof PluginResolutionException) { Plugin plugin = ((PluginResolutionException) mp.getException()).getPlugin(); // XXX this is not actually accurate; should rather pick out the ArtifactResolutionException & ArtifactNotFoundException inside problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createArtifact(plugin.getGroupId(), plugin.getArtifactId(), plugin.getVersion(), "jar")); } else if (mp.getException() instanceof PluginManagerException) { PluginManagerException ex = (PluginManagerException) mp.getException(); problemReporter.addMissingArtifact(EmbedderFactory.getProjectEmbedder().createArtifact(ex.getPluginGroupId(), ex.getPluginArtifactId(), ex.getPluginVersion(), "jar")); } } } } else { String msg = e.getMessage(); if(msg != null) { LOG.log(Level.INFO, "Exception thrown while loading maven project at " + project.getProjectDirectory(), e); //NOI18N toRet.add(ProjectProblem.createError(TXT_Cannot_read_model(), msg)); } else { String path = project.getProjectDirectory().getPath(); toRet.add(ProjectProblem.createError(TXT_Cannot_read_model(), TXT_NoMsg(path))); LOG.log(Level.WARNING, "Exception thrown while loading maven project at " + path, e); //NOI18N } } } return toRet; }
/** * Creates a new result with the specified contents. * * @param projectId The identifier of the project, may be {@code null}. * @param pomFile The POM file from which the project was built, may be {@code null}. * @param problems The problems that were encouterned, may be {@code null}. */ public DefaultProjectBuildingResult( String projectId, File pomFile, List<ModelProblem> problems ) { this.projectId = ( projectId != null ) ? projectId : ""; this.pomFile = pomFile; this.problems = problems; }
/** * Gets the problems that were encountered during the project building. * * @return The problems that were encountered during the project building, can be empty but never {@code null}. */ List<ModelProblem> getProblems();