Example usage for org.apache.maven.model.building ModelBuildingRequest VALIDATION_LEVEL_MINIMAL

List of usage examples for org.apache.maven.model.building ModelBuildingRequest VALIDATION_LEVEL_MINIMAL

Introduction

In this page you can find the example usage for org.apache.maven.model.building ModelBuildingRequest VALIDATION_LEVEL_MINIMAL.

Prototype

int VALIDATION_LEVEL_MINIMAL

To view the source code for org.apache.maven.model.building ModelBuildingRequest VALIDATION_LEVEL_MINIMAL.

Click Source Link

Document

Denotes minimal validation of POMs.

Usage

From source file:net.oneandone.maven.embedded.Maven.java

License:Apache License

public MavenProject loadPom(FileNode file, boolean resolve, Properties userProperties, List<String> profiles,
        List<Dependency> dependencies) throws RepositoryException, ProjectBuildingException {
    ProjectBuildingRequest request;/*  w  ww  .  j a  v a  2 s  .c om*/
    ProjectBuildingResult result;
    List<Exception> problems;

    request = new DefaultProjectBuildingRequest();
    request.setRepositorySession(repositorySession);
    request.setRemoteRepositories(remoteLegacy);
    request.setProcessPlugins(false);
    request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    request.setSystemProperties(System.getProperties());
    if (userProperties != null) {
        request.setUserProperties(userProperties);
    }
    // If you don't turn this into RepositoryMerging.REQUEST_DOMINANT the dependencies will be resolved against Maven Central
    // and not against the configured repositories. The default of the DefaultProjectBuildingRequest is
    // RepositoryMerging.POM_DOMINANT.
    request.setRepositoryMerging(ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT);
    request.setResolveDependencies(resolve);
    if (profiles != null) {
        request.setActiveProfileIds(profiles);
    }
    result = builder.build(file.toPath().toFile(), request);

    // TODO: i've seen these collection errors for a dependency with ranges. Why does Aether NOT throw an exception in this case?
    if (result.getDependencyResolutionResult() != null) {
        problems = result.getDependencyResolutionResult().getCollectionErrors();
        if (problems != null && !problems.isEmpty()) {
            throw new RepositoryException("collection errors: " + problems.toString(), problems.get(0));
        }
    }

    if (dependencies != null) {
        if (!resolve) {
            throw new IllegalArgumentException();
        }
        dependencies.addAll(result.getDependencyResolutionResult().getDependencies());
    }
    return result.getProject();
}

From source file:net.oneandone.maven.plugins.prerelease.util.Maven.java

License:Apache License

public MavenProject loadPom(FileNode file) throws ProjectBuildingException {
    ProjectBuildingRequest request;//from w w  w  .j  av  a2 s. c  o  m
    ProjectBuildingResult result;

    // session initializes the repository session in the build request
    request = new DefaultProjectBuildingRequest(parentSession.getProjectBuildingRequest());
    request.setRemoteRepositories(remoteRepositories);
    request.setProcessPlugins(false);
    request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    request.setSystemProperties(System.getProperties());
    //If you don't turn this into RepositoryMerging.REQUEST_DOMINANT the dependencies will be resolved against Maven Central
    //and not against the configured repositories. The default of the DefaultProjectBuildingRequest is
    // RepositoryMerging.POM_DOMINANT.
    request.setRepositoryMerging(ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT);
    request.setResolveDependencies(false);
    result = builder.build(file.toPath().toFile(), request);
    return result.getProject();
}

From source file:org.apache.archiva.metadata.repository.storage.maven2.Maven2RepositoryStorage.java

License:Apache License

@Override
public ProjectVersionMetadata readProjectVersionMetadata(ReadMetadataRequest readMetadataRequest)
        throws RepositoryStorageMetadataNotFoundException, RepositoryStorageMetadataInvalidException,
        RepositoryStorageRuntimeException {
    try {//from  w  w w .jav a2  s. c  om
        ManagedRepository managedRepository = managedRepositoryAdmin
                .getManagedRepository(readMetadataRequest.getRepositoryId());
        String artifactVersion = readMetadataRequest.getProjectVersion();
        // olamy: in case of browsing via the ui we can mix repos (parent of a SNAPSHOT can come from release repo)
        if (!readMetadataRequest.isBrowsingRequest()) {
            if (VersionUtil.isSnapshot(artifactVersion)) {
                // skygo trying to improve speed by honoring managed configuration MRM-1658
                if (managedRepository.isReleases() && !managedRepository.isSnapshots()) {
                    throw new RepositoryStorageRuntimeException("lookforsnaponreleaseonly",
                            "managed repo is configured for release only");
                }
            } else {
                if (!managedRepository.isReleases() && managedRepository.isSnapshots()) {
                    throw new RepositoryStorageRuntimeException("lookforsreleaseonsneponly",
                            "managed repo is configured for snapshot only");
                }
            }
        }
        File basedir = new File(managedRepository.getLocation());
        if (VersionUtil.isSnapshot(artifactVersion)) {
            File metadataFile = pathTranslator.toFile(basedir, readMetadataRequest.getNamespace(),
                    readMetadataRequest.getProjectId(), artifactVersion, METADATA_FILENAME);
            try {
                ArchivaRepositoryMetadata metadata = MavenMetadataReader.read(metadataFile);

                // re-adjust to timestamp if present, otherwise retain the original -SNAPSHOT filename
                SnapshotVersion snapshotVersion = metadata.getSnapshotVersion();
                if (snapshotVersion != null) {
                    artifactVersion = artifactVersion.substring(0, artifactVersion.length() - 8); // remove SNAPSHOT from end
                    artifactVersion = artifactVersion + snapshotVersion.getTimestamp() + "-"
                            + snapshotVersion.getBuildNumber();
                }
            } catch (XMLException e) {
                // unable to parse metadata - LOGGER it, and continue with the version as the original SNAPSHOT version
                LOGGER.warn("Invalid metadata: {} - {}", metadataFile, e.getMessage());
            }
        }

        // TODO: won't work well with some other layouts, might need to convert artifact parts to ID by path translator
        String id = readMetadataRequest.getProjectId() + "-" + artifactVersion + ".pom";
        File file = pathTranslator.toFile(basedir, readMetadataRequest.getNamespace(),
                readMetadataRequest.getProjectId(), readMetadataRequest.getProjectVersion(), id);

        if (!file.exists()) {
            // metadata could not be resolved
            throw new RepositoryStorageMetadataNotFoundException(
                    "The artifact's POM file '" + file.getAbsolutePath() + "' was missing");
        }

        // TODO: this is a workaround until we can properly resolve using proxies as well - this doesn't cache
        //       anything locally!
        List<RemoteRepository> remoteRepositories = new ArrayList<>();
        Map<String, NetworkProxy> networkProxies = new HashMap<>();

        Map<String, List<ProxyConnector>> proxyConnectorsMap = proxyConnectorAdmin.getProxyConnectorAsMap();
        List<ProxyConnector> proxyConnectors = proxyConnectorsMap.get(readMetadataRequest.getRepositoryId());
        if (proxyConnectors != null) {
            for (ProxyConnector proxyConnector : proxyConnectors) {
                RemoteRepository remoteRepoConfig = remoteRepositoryAdmin
                        .getRemoteRepository(proxyConnector.getTargetRepoId());

                if (remoteRepoConfig != null) {
                    remoteRepositories.add(remoteRepoConfig);

                    NetworkProxy networkProxyConfig = networkProxyAdmin
                            .getNetworkProxy(proxyConnector.getProxyId());

                    if (networkProxyConfig != null) {
                        // key/value: remote repo ID/proxy info
                        networkProxies.put(proxyConnector.getTargetRepoId(), networkProxyConfig);
                    }
                }
            }
        }

        // That's a browsing request so we can a mix of SNAPSHOT and release artifacts (especially with snapshots which
        // can have released parent pom
        if (readMetadataRequest.isBrowsingRequest()) {
            remoteRepositories.addAll(remoteRepositoryAdmin.getRemoteRepositories());
        }

        ModelBuildingRequest req = new DefaultModelBuildingRequest().setProcessPlugins(false).setPomFile(file)
                .setTwoPhaseBuilding(false).setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);

        //MRM-1607. olamy this will resolve jdk profiles on the current running archiva jvm
        req.setSystemProperties(System.getProperties());

        // MRM-1411
        req.setModelResolver(new RepositoryModelResolver(managedRepository, pathTranslator, wagonFactory,
                remoteRepositories, networkProxies, managedRepository));

        Model model;
        try {
            model = builder.build(req).getEffectiveModel();
        } catch (ModelBuildingException e) {
            String msg = "The artifact's POM file '" + file + "' was invalid: " + e.getMessage();

            List<ModelProblem> modelProblems = e.getProblems();
            for (ModelProblem problem : modelProblems) {
                // MRM-1411, related to MRM-1335
                // this means that the problem was that the parent wasn't resolved!
                // olamy really hackhish but fail with java profile so use error message
                // || ( StringUtils.startsWith( problem.getMessage(), "Failed to determine Java version for profile" ) )
                // but setTwoPhaseBuilding(true) fix that
                if ((problem.getException() instanceof FileNotFoundException && e.getModelId() != null
                        && !e.getModelId().equals(problem.getModelId()))) {
                    LOGGER.warn("The artifact's parent POM file '{}' cannot be resolved. "
                            + "Using defaults for project version metadata..", file);

                    ProjectVersionMetadata metadata = new ProjectVersionMetadata();
                    metadata.setId(readMetadataRequest.getProjectVersion());

                    MavenProjectFacet facet = new MavenProjectFacet();
                    facet.setGroupId(readMetadataRequest.getNamespace());
                    facet.setArtifactId(readMetadataRequest.getProjectId());
                    facet.setPackaging("jar");
                    metadata.addFacet(facet);

                    String errMsg = "Error in resolving artifact's parent POM file. "
                            + (problem.getException() == null ? problem.getMessage()
                                    : problem.getException().getMessage());
                    RepositoryProblemFacet repoProblemFacet = new RepositoryProblemFacet();
                    repoProblemFacet.setRepositoryId(readMetadataRequest.getRepositoryId());
                    repoProblemFacet.setId(readMetadataRequest.getRepositoryId());
                    repoProblemFacet.setMessage(errMsg);
                    repoProblemFacet.setProblem(errMsg);
                    repoProblemFacet.setProject(readMetadataRequest.getProjectId());
                    repoProblemFacet.setVersion(readMetadataRequest.getProjectVersion());
                    repoProblemFacet.setNamespace(readMetadataRequest.getNamespace());

                    metadata.addFacet(repoProblemFacet);

                    return metadata;
                }
            }

            throw new RepositoryStorageMetadataInvalidException("invalid-pom", msg, e);
        }

        // Check if the POM is in the correct location
        boolean correctGroupId = readMetadataRequest.getNamespace().equals(model.getGroupId());
        boolean correctArtifactId = readMetadataRequest.getProjectId().equals(model.getArtifactId());
        boolean correctVersion = readMetadataRequest.getProjectVersion().equals(model.getVersion());
        if (!correctGroupId || !correctArtifactId || !correctVersion) {
            StringBuilder message = new StringBuilder("Incorrect POM coordinates in '" + file + "':");
            if (!correctGroupId) {
                message.append("\nIncorrect group ID: ").append(model.getGroupId());
            }
            if (!correctArtifactId) {
                message.append("\nIncorrect artifact ID: ").append(model.getArtifactId());
            }
            if (!correctVersion) {
                message.append("\nIncorrect version: ").append(model.getVersion());
            }

            throw new RepositoryStorageMetadataInvalidException("mislocated-pom", message.toString());
        }

        ProjectVersionMetadata metadata = new ProjectVersionMetadata();
        metadata.setCiManagement(convertCiManagement(model.getCiManagement()));
        metadata.setDescription(model.getDescription());
        metadata.setId(readMetadataRequest.getProjectVersion());
        metadata.setIssueManagement(convertIssueManagement(model.getIssueManagement()));
        metadata.setLicenses(convertLicenses(model.getLicenses()));
        metadata.setMailingLists(convertMailingLists(model.getMailingLists()));
        metadata.setDependencies(convertDependencies(model.getDependencies()));
        metadata.setName(model.getName());
        metadata.setOrganization(convertOrganization(model.getOrganization()));
        metadata.setScm(convertScm(model.getScm()));
        metadata.setUrl(model.getUrl());
        metadata.setProperties(model.getProperties());

        MavenProjectFacet facet = new MavenProjectFacet();
        facet.setGroupId(model.getGroupId() != null ? model.getGroupId() : model.getParent().getGroupId());
        facet.setArtifactId(model.getArtifactId());
        facet.setPackaging(model.getPackaging());
        if (model.getParent() != null) {
            MavenProjectParent parent = new MavenProjectParent();
            parent.setGroupId(model.getParent().getGroupId());
            parent.setArtifactId(model.getParent().getArtifactId());
            parent.setVersion(model.getParent().getVersion());
            facet.setParent(parent);
        }
        metadata.addFacet(facet);

        return metadata;
    } catch (RepositoryAdminException e) {
        throw new RepositoryStorageRuntimeException("repo-admin", e.getMessage(), e);
    }
}

From source file:org.commonjava.emb.boot.services.DefaultEMBServiceManager.java

License:Apache License

public DefaultProjectBuildingRequest createProjectBuildingRequest() throws EMBEmbeddingException {
    final DefaultProjectBuildingRequest req = new DefaultProjectBuildingRequest();
    req.setLocalRepository(defaultLocalRepository());
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    req.setProcessPlugins(false);//from w w  w .j  a v  a2 s. c o  m
    req.setResolveDependencies(false);

    req.setRepositorySession(createAetherRepositorySystemSession());

    return req;
}

From source file:org.commonjava.poc.ral.AppLauncher.java

License:Open Source License

public AppLauncher(final Options options) throws AppLauncherException {
    setupLogging(Level.INFO);//from  w w  w.j a  va2s .  c  o m

    this.options = options;

    try {
        load();
    } catch (MAEException e) {
        throw new AppLauncherException("Failed to initialize MAE subsystem: %s", e, e.getMessage());
    }

    SimpleProjectToolsSession session = new SimpleProjectToolsSession();
    session.setPomValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    session.setDependencySelector(
            new FlexibleScopeDependencySelector(org.apache.maven.artifact.Artifact.SCOPE_TEST,
                    org.apache.maven.artifact.Artifact.SCOPE_PROVIDED).setTransitive(true));

    MavenProject project = loadProject(options.coordinate, session);

    DependencyGraph depGraph = resolveDependencies(project, session);

    List<URL> urls = new ArrayList<URL>();
    try {
        ArtifactResult result = repositorySystem.resolveArtifact(session.getRepositorySystemSession(),
                new ArtifactRequest(RepositoryUtils.toArtifact(project.getArtifact()),
                        session.getRemoteRepositoriesForResolution(), null));

        mainJar = result.getArtifact().getFile().toURI().normalize().toURL();
        urls.add(mainJar);
    } catch (ArtifactResolutionException e) {
        throw new AppLauncherException("Failed to resolve main project artifact: %s. Reason: %s", e,
                project.getId(), e.getMessage());
    } catch (MalformedURLException e) {
        throw new AppLauncherException("Cannot format classpath URL from: %s. Reason: %s", e, project.getId(),
                e.getMessage());
    }

    for (DepGraphNode node : depGraph) {
        try {
            ArtifactResult result = node.getLatestResult();
            if (result == null) {
                if (node.getKey()
                        .equals(key(project.getGroupId(), project.getArtifactId(), project.getVersion()))) {
                    continue;
                } else {
                    throw new AppLauncherException("Failed to resolve: %s", node.getKey());
                }
            }

            Artifact artifact = result.getArtifact();
            File file = artifact.getFile();
            URL url = file.toURI().normalize().toURL();
            urls.add(url);
        } catch (MalformedURLException e) {
            throw new AppLauncherException("Cannot format classpath URL from: %s. Reason: %s", e, node.getKey(),
                    e.getMessage());
        }
    }

    classLoader = new URLClassLoader(urls.toArray(new URL[] {}), ClassLoader.getSystemClassLoader());
}

From source file:org.commonjava.poc.ral.AppLauncher.java

License:Open Source License

private DependencyGraph resolveDependencies(final MavenProject project, final SimpleProjectToolsSession session)
        throws AppLauncherException {
    if (LOGGER.isDebugEnabled()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Setting up repository session to resolve dependencies...");
        }//www.j a  v a 2  s  .c  o  m
    }
    final DefaultProjectBuildingRequest pbr;
    try {
        sessionInitializer.initializeSessionComponents(session);

        pbr = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
        pbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
        session.setProjectBuildingRequest(pbr);
    } catch (final MAEException e) {
        throw new AppLauncherException("Failed to initialize workspace for capture analysis: %s", e,
                e.getMessage());
    }

    final DefaultRepositorySystemSession rss = (DefaultRepositorySystemSession) pbr.getRepositorySession();

    if (LOGGER.isDebugEnabled()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Resolving dependency graph...");
        }
    }

    Collection<MavenProject> projects = Collections.singleton(project);

    final DependencyGraph depGraph = graphResolver.accumulateGraph(projects, rss, session);
    graphResolver.resolveGraph(depGraph, projects, rss, session);

    return depGraph;
}

From source file:org.debian.dependency.builders.EmbeddedAntBuilder.java

License:Apache License

private File findProjectFile(final Artifact artifact, final Source source) throws ArtifactBuildException {
    try {//  ww w .jav  a2 s.  com
        for (File pom : FileUtils.getFiles(source.getLocation(), "**/*.xml,**/*.pom", null)) {
            try {
                ModelBuildingRequest request = new DefaultModelBuildingRequest()
                        .setModelSource(new FileModelSource(pom))
                        .setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);

                Model model = modelBuilder.build(request).getEffectiveModel();
                if (model.getGroupId().equals(artifact.getGroupId())
                        && model.getArtifactId().equals(artifact.getArtifactId())
                        && model.getVersion().equals(artifact.getVersion())) {
                    return pom;
                }
            } catch (ModelBuildingException e) {
                getLogger().debug("Ignoring unreadable pom file:" + pom, e);
            }
        }
    } catch (IOException e) {
        throw new ArtifactBuildException(e);
    }
    throw new ArtifactBuildException(
            "Unable to find reactor containing " + artifact + " under " + source.getLocation());
}

From source file:org.debian.dependency.builders.ForkedMavenBuilder.java

License:Apache License

private Model findProjectModel(final String groupId, final String artifactId, final String version,
        final File basedir) throws ArtifactBuildException {
    try {/*from w w  w .  ja va2  s  .c o  m*/
        for (File pom : findBuildFiles(basedir)) {
            try {
                ModelBuildingRequest request = new DefaultModelBuildingRequest().setPomFile(pom)
                        .setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);

                Model model = modelBuilder.build(request).getEffectiveModel();
                if (model.getGroupId().equals(groupId) && model.getArtifactId().equals(artifactId)
                        && model.getVersion().equals(version)) {
                    return model;
                }
            } catch (ModelBuildingException e) {
                getLogger().debug("Ignoring unreadable pom file:" + pom, e);
            }
        }
    } catch (IOException e) {
        throw new ArtifactBuildException(e);
    }
    throw new ArtifactBuildException("Unable to find reactor containing " + groupId + ":" + artifactId + ":"
            + version + " under " + basedir);
}

From source file:org.debian.dependency.DefaultDependencyCollection.java

License:Apache License

private MavenProject buildProject(final String groupId, final String artifactId, final String version,
        final MavenSession session) throws DependencyResolutionException {
    Artifact artifact = repositorySystem.createProjectArtifact(groupId, artifactId, version);

    ProjectBuildingRequest request = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
    request.setActiveProfileIds(null);/* www  .  j a v a  2s . co  m*/
    request.setInactiveProfileIds(null);
    request.setProfiles(null);
    request.setResolveDependencies(false); // we may filter them out
    request.setUserProperties(null);
    request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);

    try {
        ProjectBuildingResult result = projectBuilder.build(artifact, request);
        return result.getProject();
    } catch (ProjectBuildingException e) {
        throw new DependencyResolutionException(e);
    }
}

From source file:org.dthume.maven.xpom.impl.DefaultArtifactResolver.java

License:Apache License

private Source resolveEffectivePOMInternal(final String coords) {
    final File pom = resolveArtifactInternal(coords).getArtifact().getFile();
    final ModelBuildingRequest request = new DefaultModelBuildingRequest()
            .setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL)
            .setModelResolver(getModelResolver()).setPomFile(pom);

    final ModelBuildingResult result = buildModel(request);

    try {//from   www.j  av  a 2 s  . c  om
        return XPOMUtil.modelToSource(result.getEffectiveModel());
    } catch (final IOException e) {
        throw ARE("Failed to serialize model", e);
    }
}