Search in sources :

Example 1 with MavenDependency

use of org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency in project camel by apache.

the class ArquillianPackager method springBootPackage.

public static Archive<?> springBootPackage(ITestConfig config) throws Exception {
    if (!new File(".").getCanonicalFile().getName().equals("camel-itest-spring-boot")) {
        throw new IllegalStateException("In order to run the integration tests, 'camel-itest-spring-boot' must be the working directory. Check your configuration.");
    }
    ExtensionLoader extensionLoader = new ServiceExtensionLoader(Collections.singleton(getExtensionClassloader()));
    extensionLoader.addOverride(ZipExporter.class, SpringBootZipExporterImpl.class);
    ConfigurationBuilder builder = new ConfigurationBuilder().extensionLoader(extensionLoader);
    Configuration conf = builder.build();
    Domain domain = ShrinkWrap.createDomain(conf);
    JavaArchive ark = domain.getArchiveFactory().create(JavaArchive.class, "test.jar");
    ark = ark.addAsManifestResource("BOOT-MANIFEST.MF", "MANIFEST.MF");
    ark = ark.addAsDirectories(LIB_FOLDER);
    if (!CLASSES_FOLDER.equals("")) {
        ark = ark.addAsDirectories(CLASSES_FOLDER);
    }
    if (config.getUseCustomLog()) {
        ark = ark.addAsResource("spring-logback.xml", CLASSES_FOLDER + "/spring-logback.xml");
    }
    for (Map.Entry<String, String> res : config.getResources().entrySet()) {
        ark = ark.addAsResource(res.getKey(), CLASSES_FOLDER + "/" + res.getValue());
    }
    String version = System.getProperty("version_org.apache.camel:camel-core");
    if (version == null) {
        config.getMavenVersion();
    }
    if (version == null) {
        // It is missing when launching from IDE
        List<MavenResolvedArtifact> resolved = Arrays.asList(resolver(config).loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withoutTransitivity().asResolvedArtifact());
        for (MavenResolvedArtifact dep : resolved) {
            if (dep.getCoordinate().getGroupId().equals("org.apache.camel")) {
                version = dep.getCoordinate().getVersion();
                break;
            }
        }
    }
    debug("Resolved version: " + version);
    if (version == null) {
        throw new IllegalStateException("Cannot determine the current version of the camel component");
    }
    List<MavenDependencyExclusion> commonExclusions = new LinkedList<>();
    commonExclusions.add(MavenDependencies.createExclusion("commons-logging", "commons-logging"));
    commonExclusions.add(MavenDependencies.createExclusion("org.slf4j", "slf4j-log4j12"));
    commonExclusions.add(MavenDependencies.createExclusion("log4j", "log4j"));
    commonExclusions.add(MavenDependencies.createExclusion("log4j", "log4j-slf4j-impl"));
    commonExclusions.add(MavenDependencies.createExclusion("org.apache.logging.log4j", "log4j"));
    commonExclusions.add(MavenDependencies.createExclusion("org.apache.logging.log4j", "log4j-core"));
    commonExclusions.add(MavenDependencies.createExclusion("org.apache.logging.log4j", "log4j-slf4j-impl"));
    commonExclusions.add(MavenDependencies.createExclusion("log4j", "apache-log4j-extras"));
    commonExclusions.add(MavenDependencies.createExclusion("org.slf4j", "slf4j-simple"));
    commonExclusions.add(MavenDependencies.createExclusion("org.slf4j", "slf4j-jdk14"));
    commonExclusions.add(MavenDependencies.createExclusion("ch.qos.logback", "logback-classic"));
    commonExclusions.add(MavenDependencies.createExclusion("ch.qos.logback", "logback-core"));
    for (String ex : config.getMavenExclusions()) {
        commonExclusions.add(MavenDependencies.createExclusion(ex));
    }
    // Module dependencies
    List<MavenDependency> additionalDependencies = new LinkedList<>();
    for (String canonicalForm : config.getAdditionalDependencies()) {
        MavenCoordinate coord = MavenCoordinates.createCoordinate(canonicalForm);
        MavenDependency dep = MavenDependencies.createDependency(coord, ScopeType.RUNTIME, false);
        additionalDependencies.add(dep);
    }
    //        String mainArtifactId = config.getModuleName() + "-starter";
    //        MavenCoordinate mainJar = MavenCoordinates.createCoordinate(config.getMavenGroup(), mainArtifactId, version, PackagingType.JAR, null);
    //        // Add exclusions only when not using the starters
    //        MavenDependency mainDep = MavenDependencies.createDependency(mainJar, ScopeType.COMPILE, false);
    //        moduleDependencies.add(mainDep);
    List<String> testProvidedDependenciesXml = new LinkedList<>();
    List<ScopeType> scopes = new LinkedList<>();
    if (config.getIncludeProvidedDependencies() || config.getIncludeTestDependencies() || config.getUnitTestEnabled()) {
        if (config.getIncludeTestDependencies() || config.getUnitTestEnabled()) {
            testProvidedDependenciesXml.addAll(DependencyResolver.getDependencies(config.getModuleBasePath() + "/pom.xml", ScopeType.TEST.toString()));
            scopes.add(ScopeType.TEST);
        }
        if (config.getIncludeProvidedDependencies()) {
            testProvidedDependenciesXml.addAll(DependencyResolver.getDependencies(config.getModuleBasePath() + "/pom.xml", ScopeType.PROVIDED.toString()));
            scopes.add(ScopeType.PROVIDED);
        }
    }
    List<String> cleanTestProvidedDependenciesXml = new LinkedList<>();
    for (String depXml : testProvidedDependenciesXml) {
        if (validTestDependency(config, depXml, commonExclusions)) {
            depXml = useBOMVersionIfPresent(config, depXml);
            depXml = enforceExclusions(config, depXml, commonExclusions);
            depXml = switchToStarterIfPresent(config, depXml);
            cleanTestProvidedDependenciesXml.add(depXml);
        }
    }
    //        List<MavenResolvedArtifact> testDependencies = new LinkedList<>();
    //        if (!cleanTestProvidedDependenciesXml.isEmpty()) {
    //
    //            File testProvidedResolverPom = createResolverPom(config, cleanTestProvidedDependenciesXml);
    //
    //            testDependencies.addAll(Arrays.asList(resolver(config)
    //                    .loadPomFromFile(testProvidedResolverPom)
    //                    .importDependencies(scopes.toArray(new ScopeType[0]))
    //                    .resolve()
    //                    .withTransitivity()
    //                    .asResolvedArtifact()));
    //        }
    File moduleSpringBootPom = createUserPom(config, cleanTestProvidedDependenciesXml);
    List<ScopeType> resolvedScopes = new LinkedList<>();
    resolvedScopes.add(ScopeType.COMPILE);
    resolvedScopes.add(ScopeType.RUNTIME);
    resolvedScopes.addAll(scopes);
    List<MavenResolvedArtifact> runtimeDependencies = new LinkedList<>();
    runtimeDependencies.addAll(Arrays.asList(resolver(config).loadPomFromFile(moduleSpringBootPom).importDependencies(resolvedScopes.toArray(new ScopeType[0])).addDependencies(additionalDependencies).resolve().withTransitivity().asResolvedArtifact()));
    //merge(config, runtimeDependencies, testDependencies);
    List<MavenResolvedArtifact> dependencyArtifacts = runtimeDependencies;
    lookForVersionMismatch(config, dependencyArtifacts);
    List<File> dependencies = new LinkedList<>();
    for (MavenResolvedArtifact a : dependencyArtifacts) {
        dependencies.add(a.asFile());
    }
    // The spring boot-loader dependency will be added to the main jar, so it should be excluded from the embedded ones
    excludeDependencyRegex(dependencies, "^spring-boot-loader-[0-9].*");
    // Add all dependencies as spring-boot nested jars
    ark = addDependencies(ark, dependencies);
    // Add common packages to main jar
    ark = ark.addPackages(true, "org.jboss.shrinkwrap");
    // Add current classes to both location to be used by different classloaders
    ark = ark.addPackages(true, "org.apache.camel.itest.springboot");
    ark = addSpringbootPackage(ark, "org.apache.camel.itest.springboot");
    // CAMEL-10060 is resolved since 2.18 but some unit tests use custom (non spring-boot enabled) camel contexts
    ark = ark.addPackages(true, "org.apache.camel.converter.myconverter");
    ark = ark.addPackages(true, "org.springframework.boot.loader");
    ClassPath.Builder external = ClassPath.builder().add(ark);
    // overcome limitations of some JDKs
    external.addSystemProperty("javax.xml.accessExternalDTD", "all");
    external.addSystemProperty("javax.xml.accessExternalSchema", "all");
    if (config.getUnitTestEnabled()) {
        external.addSystemProperty("container.user.dir", new File(config.getModuleBasePath()).getCanonicalPath());
        external.addSystemProperty("container.test.resources.dir", new File(config.getModuleBasePath()).getCanonicalPath() + "/target/test-classes");
    }
    // Adding configuration properties
    for (Map.Entry<Object, Object> e : System.getProperties().entrySet()) {
        if (e.getKey() instanceof String && e.getValue() instanceof String) {
            String key = (String) e.getKey();
            if (key.startsWith(ITestConfigBuilder.CONFIG_PREFIX)) {
                external.addSystemProperty(key, (String) e.getValue());
            }
        }
    }
    for (Map.Entry<String, String> e : config.getSystemProperties().entrySet()) {
        external.addSystemProperty(e.getKey(), e.getValue());
    }
    return external.build();
}
Also used : ConfigurationBuilder(org.jboss.shrinkwrap.api.ConfigurationBuilder) ClassPath(org.jboss.arquillian.container.se.api.ClassPath) Configuration(org.jboss.shrinkwrap.api.Configuration) JavaArchive(org.jboss.shrinkwrap.api.spec.JavaArchive) ServiceExtensionLoader(org.jboss.shrinkwrap.impl.base.ServiceExtensionLoader) MavenDependencyExclusion(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencyExclusion) MavenDependency(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency) ScopeType(org.jboss.shrinkwrap.resolver.api.maven.ScopeType) MavenResolvedArtifact(org.jboss.shrinkwrap.resolver.api.maven.MavenResolvedArtifact) LinkedList(java.util.LinkedList) MavenCoordinate(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate) Domain(org.jboss.shrinkwrap.api.Domain) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) ServiceExtensionLoader(org.jboss.shrinkwrap.impl.base.ServiceExtensionLoader) ExtensionLoader(org.jboss.shrinkwrap.api.ExtensionLoader)

Example 2 with MavenDependency

use of org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency in project syndesis by syndesisio.

the class RepackageExtensionMojo method getAdditionalFilters.

@Override
protected Collection<ArtifactsFilter> getAdditionalFilters() {
    Collection<MavenDependency> dependencies = new HashSet<>();
    if (StringUtils.isNotBlank(blackListedBoms)) {
        addCustomBoms(dependencies);
    } else {
        addDefaultBOMs(dependencies);
    }
    if (StringUtils.isNotBlank(blackListedGAVs)) {
        addCustomGAVs(dependencies);
    } else {
        addDefaultGAVs(dependencies);
    }
    if (getLog().isDebugEnabled()) {
        getLog().debug("Filtering out dependencies from the following BOMs: " + bomsUsed);
        getLog().debug("Dependencies to be filtered out:");
        dependencies.stream().sorted(Comparator.comparing(MavenCoordinate::toCanonicalForm)).forEach(mavenDependency -> getLog().debug(mavenDependency.toCanonicalForm()));
    }
    List<ArtifactsFilter> filters = new ArrayList<>(dependencies.size());
    for (MavenCoordinate dep : dependencies) {
        filters.add(newExcludeFilter(dep));
    }
    return filters;
}
Also used : MavenCoordinate(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate) ArrayList(java.util.ArrayList) ArtifactsFilter(org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter) MavenDependency(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency) HashSet(java.util.HashSet)

Example 3 with MavenDependency

use of org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency in project component-runtime by Talend.

the class Dependencies method resolve.

public static URL[] resolve(final MavenDependency dep) {
    return CACHE.computeIfAbsent(dep, d -> {
        final ConfigurableMavenResolverSystem resolver = Maven.configureResolver().withClassPathResolution(true).workOffline(Boolean.getBoolean("talend.component.junit.maven.offline"));
        REPOSITORIES.forEach(resolver::withRemoteRepo);
        resolver.addDependency(dep);
        return Stream.of(resolver.resolve().using(STRATEGY).asFile()).distinct().map(f -> {
            try {
                return f.toURI().toURL();
            } catch (final MalformedURLException e) {
                throw new IllegalStateException(e);
            }
        }).toArray(URL[]::new);
    });
}
Also used : AcceptScopesStrategy(org.jboss.shrinkwrap.resolver.api.maven.strategy.AcceptScopesStrategy) URL(java.net.URL) MavenResolutionStrategy(org.jboss.shrinkwrap.resolver.api.maven.strategy.MavenResolutionStrategy) MavenChecksumPolicy(org.jboss.shrinkwrap.resolver.api.maven.repository.MavenChecksumPolicy) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Maven(org.jboss.shrinkwrap.resolver.api.maven.Maven) MavenRemoteRepository(org.jboss.shrinkwrap.resolver.api.maven.repository.MavenRemoteRepository) PomEquippedResolveStageBaseImpl(org.jboss.shrinkwrap.resolver.impl.maven.PomEquippedResolveStageBaseImpl) MavenDependency(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency) MavenWorkingSession(org.jboss.shrinkwrap.resolver.api.maven.MavenWorkingSession) ScopeType(org.jboss.shrinkwrap.resolver.api.maven.ScopeType) MavenRemoteRepositories(org.jboss.shrinkwrap.resolver.api.maven.repository.MavenRemoteRepositories) MalformedURLException(java.net.MalformedURLException) PomEquippedResolveStage(org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Field(java.lang.reflect.Field) File(java.io.File) RemoteRepository(org.eclipse.aether.repository.RemoteRepository) List(java.util.List) Stream(java.util.stream.Stream) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem) MavenUpdatePolicy(org.jboss.shrinkwrap.resolver.api.maven.repository.MavenUpdatePolicy) PRIVATE(lombok.AccessLevel.PRIVATE) NoArgsConstructor(lombok.NoArgsConstructor) MalformedURLException(java.net.MalformedURLException) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem)

Example 4 with MavenDependency

use of org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency in project bookkeeper by apache.

the class MavenClassLoader method createClassLoader.

private static MavenClassLoader createClassLoader(ConfigurableMavenResolverSystem resolver, String mainArtifact) throws Exception {
    Optional<String> slf4jVersion = Arrays.stream(resolver.resolve(mainArtifact).withTransitivity().asResolvedArtifact()).filter((a) -> a.getCoordinate().getGroupId().equals("org.slf4j") && a.getCoordinate().getArtifactId().equals("slf4j-log4j12")).map((a) -> a.getCoordinate().getVersion()).findFirst();
    List<MavenDependency> deps = Lists.newArrayList(MavenDependencies.createDependency(mainArtifact, ScopeType.COMPILE, false, MavenDependencies.createExclusion("org.slf4j:slf4j-log4j12"), MavenDependencies.createExclusion("log4j:log4j")));
    if (slf4jVersion.isPresent()) {
        deps.add(MavenDependencies.createDependency("org.slf4j:slf4j-simple:" + slf4jVersion.get(), ScopeType.COMPILE, false));
    }
    File[] files = resolver.addDependencies(deps.toArray(new MavenDependency[0])).resolve().withTransitivity().asFile();
    URLClassLoader cl = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {

        @Override
        public URLClassLoader run() {
            return new URLClassLoader(Arrays.stream(files).map((f) -> {
                try {
                    return f.toURI().toURL();
                } catch (Throwable t) {
                    throw new RuntimeException(t);
                }
            }).toArray(URL[]::new), ClassLoader.getSystemClassLoader());
        }
    });
    return new MavenClassLoader(cl);
}
Also used : ScopeType(org.jboss.shrinkwrap.resolver.api.maven.ScopeType) Arrays(java.util.Arrays) Proxy(java.lang.reflect.Proxy) Logger(org.slf4j.Logger) URL(java.net.URL) MethodHandles(java.lang.invoke.MethodHandles) LoggerFactory(org.slf4j.LoggerFactory) Closure(groovy.lang.Closure) PrivilegedAction(java.security.PrivilegedAction) Constructor(java.lang.reflect.Constructor) File(java.io.File) ArrayList(java.util.ArrayList) MavenDependencies(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencies) Maven(org.jboss.shrinkwrap.resolver.api.maven.Maven) URLClassLoader(java.net.URLClassLoader) List(java.util.List) Lists(com.google.common.collect.Lists) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem) Optional(java.util.Optional) InvocationHandler(java.lang.reflect.InvocationHandler) MavenDependency(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency) AccessController(java.security.AccessController) Method(java.lang.reflect.Method) URLClassLoader(java.net.URLClassLoader) File(java.io.File) MavenDependency(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency)

Example 5 with MavenDependency

use of org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency in project syndesis by syndesisio.

the class RepackageExtensionMojo method obtainBomDependencies.

protected Set<MavenDependency> obtainBomDependencies(String urlLocation) throws IOException, MojoExecutionException {
    Artifact artifact = downloadAndInstallArtifact(urlLocation).getArtifact();
    File tempPom = new File(outputDirectory, ".syndesis-extension-plugin-temp-pom");
    try (BufferedWriter out = Files.newBufferedWriter(tempPom.toPath(), StandardCharsets.UTF_8)) {
        Dependency bom = new Dependency();
        bom.setGroupId(artifact.getGroupId());
        bom.setArtifactId(artifact.getArtifactId());
        bom.setVersion(artifact.getVersion());
        bom.setType(artifact.getExtension());
        bom.setScope("import");
        Model bomModel = new Model();
        bomModel.setDependencyManagement(new DependencyManagement());
        bomModel.getDependencyManagement().addDependency(bom);
        bomModel.setRepositories(project.getRepositories());
        MavenProject bomProject = new MavenProject();
        bomProject.setModel(bomModel);
        bomProject.setModelVersion(project.getModelVersion());
        bomProject.setGroupId(project.getGroupId());
        bomProject.setArtifactId(project.getArtifactId() + "-temp-bom");
        bomProject.setVersion(project.getVersion());
        ModelWriter modelWriter = new DefaultModelWriter();
        modelWriter.write(out, Collections.emptyMap(), bomProject.getModel());
        MavenResolverSystem resolver = Maven.resolver();
        resolver.loadPomFromFile(tempPom).importCompileAndRuntimeDependencies();
        MavenWorkingSession session = ((MavenWorkingSessionContainer) resolver).getMavenWorkingSession();
        return session.getDependencyManagement();
    } finally {
        if (!tempPom.delete()) {
            getLog().warn("Cannot delete file " + tempPom);
        }
    }
}
Also used : DefaultModelWriter(org.apache.maven.model.io.DefaultModelWriter) MavenWorkingSession(org.jboss.shrinkwrap.resolver.api.maven.MavenWorkingSession) MavenWorkingSessionContainer(org.jboss.shrinkwrap.resolver.impl.maven.MavenWorkingSessionContainer) MavenProject(org.apache.maven.project.MavenProject) Model(org.apache.maven.model.Model) MavenDependency(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency) Dependency(org.apache.maven.model.Dependency) File(java.io.File) Artifact(org.eclipse.aether.artifact.Artifact) DefaultArtifact(org.eclipse.aether.artifact.DefaultArtifact) DependencyManagement(org.apache.maven.model.DependencyManagement) DefaultModelWriter(org.apache.maven.model.io.DefaultModelWriter) ModelWriter(org.apache.maven.model.io.ModelWriter) MavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.MavenResolverSystem) BufferedWriter(java.io.BufferedWriter)

Aggregations

MavenDependency (org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency)5 File (java.io.File)4 ArrayList (java.util.ArrayList)3 ScopeType (org.jboss.shrinkwrap.resolver.api.maven.ScopeType)3 URL (java.net.URL)2 List (java.util.List)2 ConfigurableMavenResolverSystem (org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem)2 Maven (org.jboss.shrinkwrap.resolver.api.maven.Maven)2 MavenWorkingSession (org.jboss.shrinkwrap.resolver.api.maven.MavenWorkingSession)2 MavenCoordinate (org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate)2 Lists (com.google.common.collect.Lists)1 Closure (groovy.lang.Closure)1 BufferedWriter (java.io.BufferedWriter)1 MethodHandles (java.lang.invoke.MethodHandles)1 Constructor (java.lang.reflect.Constructor)1 Field (java.lang.reflect.Field)1 InvocationHandler (java.lang.reflect.InvocationHandler)1 Method (java.lang.reflect.Method)1 Proxy (java.lang.reflect.Proxy)1 MalformedURLException (java.net.MalformedURLException)1