/** * Creates a list of POM models in an inheritance lineage. * Each resulting model is "raw", so contains no interpolation or inheritance. * In particular beware that groupId and/or version may be null if inherited from a parent; use {@link Model#getParent} to resolve. * Internally calls <code>executeModelBuilder</code> so if you need to call both just use the execute method. * @param pom a POM to inspect * @param embedder an embedder to use * @return a list of models, starting with the specified POM, going through any parents, finishing with the Maven superpom (with a null artifactId) * @throws ModelBuildingException if the POM or parents could not even be parsed; warnings are not reported */ public List<Model> createModelLineage(File pom) throws ModelBuildingException { ModelBuildingResult res = executeModelBuilder(pom); List<Model> toRet = new ArrayList<Model>(); for (String id : res.getModelIds()) { Model m = res.getRawModel(id); normalizePath(m); toRet.add(m); } // for (ModelProblem p : res.getProblems()) { // System.out.println("problem=" + p); // if (p.getException() != null) { // p.getException().printStackTrace(); // } // } return toRet; }
@Override public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException { ModelBuildingResult toRet = super.build(request); Model eff = toRet.getEffectiveModel(); InputSource source = new InputSource(); source.setLocation(""); InputLocation location = new InputLocation(-1, -1, source); eff.setLocation(NETBEANS_PROFILES, location); for (String id : toRet.getModelIds()) { Model mdl = toRet.getRawModel(id); for (Profile p : mdl.getProfiles()) { source.setLocation(source.getLocation() + "|" + p.getId()); } } return toRet; }
public void testInvalidRepositoryException() throws Exception { // #197831 File pom = TestFileUtils.writeFile(new File(getWorkDir(), "pom.xml"), "<project xmlns='http://maven.apache.org/POM/4.0.0'>" + "<modelVersion>4.0.0</modelVersion>" + "<groupId>grp</groupId>" + "<artifactId>art</artifactId>" + "<packaging>jar</packaging>" + "<version>1.0-SNAPSHOT</version>" + "<repositories><repository><url>http://nowhere.net/</url></repository></repositories>" + "</project>"); try { EmbedderFactory.createProjectLikeEmbedder().createModelLineage(pom); fail(); } catch (ModelBuildingException x) { // right } }
@Override public String getBundleName(Artifact artifact) { //return artifact.getGroupId() + " " + artifact.getArtifactId(); // don't have access to the name try { Model pom = Maven.getModel(artifact); String name = pom.getName(); System.out.println(pom); if(Strings.isNullOrEmpty(name)) return artifact.getArtifactId(); return name; } catch(ModelBuildingException | ComponentLookupException e) { System.err.println("Exception: " + e); return artifact.getArtifactId(); // don't have access to the name } }
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; }
/**f * Read the given POM so it can be used as the source of coordinates, etc. * during artifact construction. Note that if this object's * {@link #snapshots} property is true, and we're working with a development * build ({@link #buildNumber} ends with 'd'), the POM is modified to remove * the SNAPSHOT qualifier. * * @param pom * the POM file containing the artifact metadata * @return A Maven model to be used at * {@link com.isomorphic.maven.packaging.Module#Module(Model)} * Module construction * @throws ModelBuildingException * if the Model cannot be built from the given POM * @throws IOException * if the Model cannot be built from the given POM */ private Model getModelFromFile(File pom) throws ModelBuildingException, IOException { if (buildNumber.endsWith("d") && !snapshots) { LOGGER.info( "Rewriting file to remove SNAPSHOT qualifier from development POM '{}'", pom.getName()); String content = FileUtils.readFileToString(pom); content = content.replaceAll("-SNAPSHOT", ""); FileUtils.write(pom, content); } ModelBuildingRequest request = new DefaultModelBuildingRequest(); request.setPomFile(pom); ModelBuildingResult result = modelBuilder.build(request); return result.getEffectiveModel(); }
public Model getRawModel() throws ModelBuildingException { synchronized(MODEL_LOCK) { if(model == null) { MavenEmbedder projectEmbedder = EmbedderFactory.getProjectEmbedder(); ModelBuildingResult br = projectEmbedder.executeModelBuilder(getPOMFile()); model = br.getRawModel(); } return model; } }
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; }
@Override public void run() { //#164852 somehow a folder dataobject slipped in, test mimetype to avoid that. // the root cause of the problem is unknown though if (current != null && Constants.POM_MIME_TYPE.equals(current.getPrimaryFile().getMIMEType())) { //NOI18N File file = FileUtil.toFile(current.getPrimaryFile()); // can be null for stuff in jars? if (file != null) { try { List<Model> lin = EmbedderFactory.getProjectEmbedder().createModelLineage(file); final Children ch = Children.create(new PomChildren(lin), false); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { treeView.setRootVisible(false); explorerManager.setRootContext(new AbstractNode(ch)); } }); } catch (final ModelBuildingException ex) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { treeView.setRootVisible(true); explorerManager.setRootContext(POMModelPanel.createErrorNode(ex)); } }); } } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { treeView.setRootVisible(false); explorerManager.setRootContext(createEmptyNode()); } }); } } }
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; }
/** * * @param pom * @return result object with access to effective pom model and raw models for each parent. * @throws ModelBuildingException if the POM or parents could not even be parsed; warnings are not reported */ public ModelBuildingResult executeModelBuilder(File pom) throws ModelBuildingException { ModelBuilder mb = lookupComponent(ModelBuilder.class); assert mb!=null : "ModelBuilder component not found in maven"; ModelBuildingRequest req = new DefaultModelBuildingRequest(); req.setPomFile(pom); req.setProcessPlugins(false); req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); req.setLocationTracking(true); req.setModelResolver(new NBRepositoryModelResolver(this)); req.setSystemProperties(getSystemProperties()); req.setUserProperties(embedderConfiguration.getUserProperties()); return mb.build(req); }
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 static Model createModel(File pom) throws ModelBuildingException, ComponentLookupException { ModelBuilder builder = mavenContainer.lookup(ModelBuilder.class); ModelBuildingRequest req = new DefaultModelBuildingRequest(); req.setProcessPlugins(false); req.setModelResolver(new RepoModelResolver()); req.setPomFile(pom); return builder.build(req).getEffectiveModel(); }
public static Model getModel(Artifact artifact) throws ModelBuildingException, ComponentLookupException { RepositorySystem system = repositorySystem(); RepositorySystemSession session = repositorySystemSession(system); Metadata metadata = getMetadata(system, session, artifact); return createModel(metadata.getFile()); }
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(); }
private ProjectBuildingException transformError( ProjectBuildingException e ) { if ( e.getCause() instanceof ModelBuildingException ) { return new InvalidProjectModelException( e.getProjectId(), e.getMessage(), e.getPomFile() ); } return e; }
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; } }
private boolean build( List<ProjectBuildingResult> results, List<MavenProject> projects, Map<String, MavenProject> projectIndex, List<InterimResult> interimResults, ProjectBuildingRequest request, Map<File, Boolean> profilesXmls ) { boolean noErrors = true; for ( InterimResult interimResult : interimResults ) { try { ModelBuildingResult result = modelBuilder.build( interimResult.request, interimResult.result ); MavenProject project = interimResult.listener.getProject(); initProject( project, projectIndex, result, profilesXmls ); List<MavenProject> modules = new ArrayList<MavenProject>(); noErrors = build( results, modules, projectIndex, interimResult.modules, request, profilesXmls ) && noErrors; projects.addAll( modules ); projects.add( project ); project.setExecutionRoot( interimResult.root ); project.setCollectedProjects( modules ); results.add( new DefaultProjectBuildingResult( project, result.getProblems(), null ) ); } catch ( ModelBuildingException e ) { results.add( new DefaultProjectBuildingResult( e.getModelId(), interimResult.pomFile, e.getProblems() ) ); noErrors = false; } } return noErrors; }
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; } }
private Model loadPomModel(Path pomFile) { DefaultModelBuildingRequest request = new DefaultModelBuildingRequest(); request.setPomFile(pomFile.toFile()); try { ModelBuildingResult result = modelBuilder.build(request); return result.getRawModel(); } catch (ModelBuildingException | IllegalArgumentException e) { // IllegalArg can be thrown if the parent POM cannot be resolved. throw new RuntimeException(e); } }
private Model constructModel(File file, Model model) { ModelBuilder modelBuilder = MODEL_BUILDER_FACTORY.newInstance(); try { ModelBuildingRequest req = new DefaultModelBuildingRequest().setPomFile(file); ModelBuildingResult modelBuildingResult = modelBuilder.build(req); Model constructed = Preconditions.checkNotNull(modelBuildingResult.getRawModel()); return merge(model, constructed); } catch (ModelBuildingException e) { throw new RuntimeException(e); } }
public ModelBuildingResult buildModel(File pomFile) { ModelBuildingResult result = null; DefaultModelBuildingRequest request = new DefaultModelBuildingRequest(modelBuildingRequestTemplate); request.setPomFile(pomFile); request.setModelSource(new FileModelSource(pomFile)); try { result = modelBuilder.build(request); } catch (ModelBuildingException e) { result = null; } return result; }
private void validate(ValidatorContext ctx, File pomFile) { DefaultModelBuildingRequest request = new DefaultModelBuildingRequest(modelBuildingRequestTemplate); request.setPomFile(pomFile); request.setModelSource(new FileModelSource(pomFile)); request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0); try { modelBuilder.build(request); } catch (ModelBuildingException e) { ctx.addError(this, pomFile, e); } }
@Test public void shouldFindInvalidPackagingForParent() { Model fooParent = pom().artifactId("foo-parent").create(repoFooDir); pom().artifactId("foo-api").parent(fooParent).create(repoFooDir); validationExecutor.execute(ctx); assertExpectedException(ModelBuildingException.class, "Invalid packaging for parent POM"); }
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; }
private void checkContent(Project prj, InstanceContent ic, AccessQueryImpl access, ForeignClassBundlerImpl bundler, RecommendedTemplates templates) { NbMavenProject nbprj = prj.getLookup().lookup(NbMavenProject.class); String effPackaging = nbprj.getPackagingType(); boolean needToCheckFelixProjectTypes = true; if(!nbprj.isMavenProjectLoaded()) { // issue #262646 // due to unfortunate ProjectManager.findPorjetc calls in awt, // speed is essential during project init, so lets try to avoid // maven project loading if we can get the info faster from raw model. needToCheckFelixProjectTypes = false; Model model; try { model = nbprj.getRawModel(); } catch (ModelBuildingException ex) { // whatever happend, we can't use the model, // lets try to follow up with loading the maven project model = null; Logger.getLogger(OSGILookupProvider.class.getName()).log(Level.FINE, null, ex); } Build build = model != null ? model.getBuild() : null; List<Plugin> plugins = build != null ? build.getPlugins() : null; if(plugins != null) { for (Plugin plugin : plugins) { if(OSGiConstants.GROUPID_FELIX.equals(plugin.getGroupId()) && OSGiConstants.ARTIFACTID_BUNDLE_PLUGIN.equals(plugin.getArtifactId())) { needToCheckFelixProjectTypes = true; break; } } } } if(needToCheckFelixProjectTypes) { String[] types = PluginPropertyUtils.getPluginPropertyList(prj, OSGiConstants.GROUPID_FELIX, OSGiConstants.ARTIFACTID_BUNDLE_PLUGIN, "supportedProjectTypes", "supportedProjectType", /*"bundle" would not work for GlassFish parent POM*/null); if (types != null) { for (String type : types) { if (effPackaging.equals(type)) { effPackaging = NbMavenProject.TYPE_OSGI; } } } } if (NbMavenProject.TYPE_OSGI.equals(effPackaging)) { ic.add(access); ic.add(bundler); ic.add(templates); } else { ic.remove(access); ic.remove(bundler); ic.remove(templates); } }
@Override public String getSourceCodeEncoding() throws ModelBuildingException, IOException { return null; }
@Override public String getSourceCodeVersion() throws ModelBuildingException, IOException { return DEFAULT_SOURCE_CODE_VERSION; }
@Test public void shouldFindDamageNoGroupId() { pom().withDamage("<groupId>com.acme</groupId>", "").create(repoFooDir); validationExecutor.execute(ctx); assertExpectedException(ModelBuildingException.class, "'groupId' is missing"); }
@Test public void shouldFindInvalidModelVersion() { pom().withDamage("<modelVersion>4.0.0", "<modelVersion>999").create(repoFooDir); validationExecutor.execute(ctx); assertExpectedException(ModelBuildingException.class, "'modelVersion' must be one of [4.0.0]"); }
/** * @param args */ public static void main(String[] args) throws ModelBuildingException, ComponentLookupException { File pomFile = new File("/Users/ben/workspaces/gae-website/appsite-client/thirdparty/pom.xml"); Model model = Maven.createModel(pomFile); System.out.println(model.getModules()); }
/** * Returns the raw pom model for the project. * @return */ public Model getRawModel() throws ModelBuildingException { return project.getRawModel(); }
/** * Provides a Zero Install feed for a specific Maven artifact. * * @param artifactPath The path used to request the artifact from a Maven * server (artifact group and id combined). * @return The serialized feed data. * @throws IOException Download of one the Maven source files failed. * @throws SAXException Parsing of one the Maven source files failed. * @throws ModelBuildingException Maven source model is inconsistent. */ String getFeed(String artifactPath) throws IOException, SAXException, XPathExpressionException, ModelBuildingException;