Search in sources :

Example 1 with DeclaredDependencies

use of org.wildfly.swarm.tools.DeclaredDependencies in project wildfly-swarm by wildfly-swarm.

the class GradleDependencyAdapter method parseDependencies.

public DeclaredDependencies parseDependencies(Configuration configuration) {
    System.out.println(rootPath);
    GradleConnector connector = GradleConnector.newConnector().forProjectDirectory(rootPath.toFile());
    ProjectConnection connection = connector.connect();
    GradleProject project = connection.getModel(GradleProject.class);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    connection.newBuild().withArguments("dependencies", "--configuration", configuration.literal).setStandardOutput(bout).run();
    connection.close();
    // parse
    DeclaredDependencies declaredDependencies = new DeclaredDependencies();
    String deps = new String(bout.toByteArray());
    Scanner scanner = new Scanner(deps);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        // top level deps
        if (line.startsWith(PREFIX1) || line.startsWith(PREFIX2)) {
            if (stack.size() > 0) {
                stack.pop();
            }
            // parse
            line = parseLine(line);
            String coord = parseCoordinate(line);
            ArtifactSpec parent = DeclaredDependencies.createSpec(coord);
            declaredDependencies.add(parent);
            stack.push(parent);
        } else if (line.contains(PREFIX)) {
            // transient
            line = parseLine(line);
            if (line.startsWith(PROJECT)) {
                // Always skip 'project' dependencies.
                continue;
            }
            String coord = parseCoordinate(line);
            declaredDependencies.add(stack.peek(), DeclaredDependencies.createSpec(coord));
        }
    }
    scanner.close();
    return declaredDependencies;
}
Also used : Scanner(java.util.Scanner) ArtifactSpec(org.wildfly.swarm.tools.ArtifactSpec) DeclaredDependencies(org.wildfly.swarm.tools.DeclaredDependencies) ProjectConnection(org.gradle.tooling.ProjectConnection) GradleProject(org.gradle.tooling.model.GradleProject) ByteArrayOutputStream(java.io.ByteArrayOutputStream) GradleConnector(org.gradle.tooling.GradleConnector)

Example 2 with DeclaredDependencies

use of org.wildfly.swarm.tools.DeclaredDependencies in project wildfly-swarm by wildfly-swarm.

the class UberjarSimpleContainer method start.

@Override
public void start(Archive<?> archive) throws Exception {
    archive.add(EmptyAsset.INSTANCE, "META-INF/arquillian-testable");
    ContextRoot contextRoot = null;
    if (archive.getName().endsWith(".war")) {
        contextRoot = new ContextRoot("/");
        Node jbossWebNode = archive.as(WebArchive.class).get("WEB-INF/jboss-web.xml");
        if (jbossWebNode != null) {
            if (jbossWebNode.getAsset() != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(jbossWebNode.getAsset().openStream()))) {
                    String content = String.join("\n", reader.lines().collect(Collectors.toList()));
                    Pattern pattern = Pattern.compile("<context-root>(.+)</context-root>");
                    Matcher matcher = pattern.matcher(content);
                    if (matcher.find()) {
                        contextRoot = new ContextRoot(matcher.group(1));
                    }
                }
            }
        }
        this.deploymentContext.getObjectStore().add(ContextRoot.class, contextRoot);
    }
    MainSpecifier mainSpecifier = containerContext.getObjectStore().get(MainSpecifier.class);
    boolean annotatedCreateSwarm = false;
    Method swarmMethod = getAnnotatedMethodWithAnnotation(this.testClass, CreateSwarm.class);
    List<Class<?>> types = determineTypes(this.testClass);
    // preflight check it
    if (swarmMethod != null) {
        if (Modifier.isStatic(swarmMethod.getModifiers())) {
            // good to go
            annotatedCreateSwarm = true;
            types.add(CreateSwarm.class);
            types.add(AnnotationBasedMain.class);
            archive.as(JARArchive.class).addModule("org.wildfly.swarm.container");
            archive.as(JARArchive.class).addModule("org.wildfly.swarm.configuration");
        } else {
            throw new IllegalArgumentException(String.format("Method annotated with %s is %s but it is not static", CreateSwarm.class.getSimpleName(), swarmMethod));
        }
    }
    if (types.size() > 0) {
        try {
            ((ClassContainer<?>) archive).addClasses(types.toArray(new Class[types.size()]));
        } catch (UnsupportedOperationException e) {
            // TODO Remove the try/catch when SHRINKWRAP-510 is resolved and we update to latest SW
            archive.as(JARArchive.class).addClasses(types.toArray(new Class[types.size()]));
        }
    }
    final ShrinkwrapArtifactResolvingHelper resolvingHelper = ShrinkwrapArtifactResolvingHelper.defaultInstance();
    BuildTool tool = new BuildTool(resolvingHelper).fractionDetectionMode(BuildTool.FractionDetectionMode.when_missing).bundleDependencies(false);
    String additionalModules = System.getProperty(SwarmInternalProperties.BUILD_MODULES);
    // See https://issues.jboss.org/browse/SWARM-571
    if (null == additionalModules) {
        // see if we can find it
        File modulesDir = new File("target/classes/modules");
        additionalModules = modulesDir.exists() ? modulesDir.getAbsolutePath() : null;
    }
    if (additionalModules != null) {
        tool.additionalModules(Stream.of(additionalModules.split(":")).map(File::new).filter(File::exists).map(File::getAbsolutePath).collect(Collectors.toList()));
    }
    final SwarmExecutor executor = new SwarmExecutor().withDefaultSystemProperties();
    if (annotatedCreateSwarm) {
        executor.withProperty(AnnotationBasedMain.ANNOTATED_CLASS_NAME, this.testClass.getName());
    }
    if (contextRoot != null) {
        executor.withProperty(SwarmProperties.CONTEXT_PATH, contextRoot.context());
    }
    executor.withProperty("swarm.inhibit.auto-stop", "true");
    String additionalRepos = System.getProperty(SwarmInternalProperties.BUILD_REPOS);
    if (additionalRepos != null) {
        additionalRepos = additionalRepos + ",";
    } else {
        additionalRepos = "";
    }
    additionalRepos = additionalRepos + "https://repository.jboss.org/nexus/content/groups/public/";
    executor.withProperty("remote.maven.repo", additionalRepos);
    // project dependencies
    FileSystemLayout fsLayout = FileSystemLayout.create();
    DeclaredDependencies declaredDependencies = DependencyDeclarationFactory.newInstance(fsLayout).create(fsLayout, resolvingHelper);
    tool.declaredDependencies(declaredDependencies);
    // see DependenciesContainer#addAllDependencies()
    if (archive instanceof DependenciesContainer) {
        DependenciesContainer<?> depContainer = (DependenciesContainer<?>) archive;
        if (depContainer.hasMarker(DependenciesContainer.ALL_DEPENDENCIES_MARKER)) {
            munge(depContainer, declaredDependencies);
        }
    } else if (archive instanceof WebArchive) {
        // Handle the default deployment of type WAR
        WebArchive webArchive = (WebArchive) archive;
        if (MarkerContainer.hasMarker(webArchive, DependenciesContainer.ALL_DEPENDENCIES_MARKER)) {
            munge(webArchive, declaredDependencies);
        }
    }
    tool.projectArchive(archive);
    final String debug = System.getProperty(SwarmProperties.DEBUG_PORT);
    if (debug != null) {
        try {
            executor.withDebug(Integer.parseInt(debug));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(String.format("Failed to parse %s of \"%s\"", SwarmProperties.DEBUG_PORT, debug), e);
        }
    }
    if (mainSpecifier != null) {
        tool.mainClass(mainSpecifier.getClassName());
        String[] args = mainSpecifier.getArgs();
        for (String arg : args) {
            executor.withArgument(arg);
        }
    } else if (annotatedCreateSwarm) {
        tool.mainClass(AnnotationBasedMain.class.getName());
    } else {
        Optional<String> mainClassName = Optional.empty();
        Node node = archive.get("META-INF/arquillian-main-class");
        if (node != null && node.getAsset() != null) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(node.getAsset().openStream()))) {
                mainClassName = reader.lines().findFirst();
            }
        }
        tool.mainClass(mainClassName.orElse(Swarm.class.getName()));
    }
    if (this.testClass != null) {
        tool.testClass(this.testClass.getName());
    }
    Archive<?> wrapped = null;
    try {
        wrapped = tool.build();
    } catch (Throwable t) {
        t.printStackTrace();
        throw t;
    }
    if (BootstrapProperties.flagIsSet(SwarmInternalProperties.EXPORT_UBERJAR)) {
        final File out = new File(wrapped.getName());
        System.err.println("Exporting swarm jar to " + out.getAbsolutePath());
        wrapped.as(ZipExporter.class).exportTo(out, true);
    }
    /* for (Map.Entry<ArchivePath, Node> each : wrapped.getContent().entrySet()) {
                System.err.println("-> " + each.getKey());
            }*/
    File executable = File.createTempFile(TempFileManager.WFSWARM_TMP_PREFIX + "arquillian", "-swarm.jar");
    wrapped.as(ZipExporter.class).exportTo(executable, true);
    executable.deleteOnExit();
    String mavenRepoLocal = System.getProperty("maven.repo.local");
    if (mavenRepoLocal != null) {
        executor.withProperty("maven.repo.local", mavenRepoLocal);
    }
    executor.withProperty("java.net.preferIPv4Stack", "true");
    File processFile = File.createTempFile(TempFileManager.WFSWARM_TMP_PREFIX + "mainprocessfile", null);
    executor.withProcessFile(processFile);
    executor.withJVMArguments(getJavaVmArgumentsList());
    executor.withExecutableJar(executable.toPath());
    workingDirectory = TempFileManager.INSTANCE.newTempDirectory("arquillian", null);
    executor.withWorkingDirectory(workingDirectory.toPath());
    this.process = executor.execute();
    this.process.getOutputStream().close();
    this.process.awaitReadiness(2, TimeUnit.MINUTES);
    if (!this.process.isAlive()) {
        throw new DeploymentException("Process failed to start");
    }
    if (this.process.getError() != null) {
        throw new DeploymentException("Error starting process", this.process.getError());
    }
}
Also used : Matcher(java.util.regex.Matcher) ClassContainer(org.jboss.shrinkwrap.api.container.ClassContainer) ZipExporter(org.jboss.shrinkwrap.api.exporter.ZipExporter) Node(org.jboss.shrinkwrap.api.Node) FileSystemLayout(org.wildfly.swarm.internal.FileSystemLayout) Swarm(org.wildfly.swarm.Swarm) CreateSwarm(org.wildfly.swarm.arquillian.CreateSwarm) ShrinkwrapArtifactResolvingHelper(org.wildfly.swarm.arquillian.resolver.ShrinkwrapArtifactResolvingHelper) ContextRoot(org.wildfly.swarm.arquillian.adapter.resources.ContextRoot) JARArchive(org.wildfly.swarm.spi.api.JARArchive) Pattern(java.util.regex.Pattern) InputStreamReader(java.io.InputStreamReader) Optional(java.util.Optional) SwarmExecutor(org.wildfly.swarm.tools.exec.SwarmExecutor) DependenciesContainer(org.wildfly.swarm.spi.api.DependenciesContainer) DeclaredDependencies(org.wildfly.swarm.tools.DeclaredDependencies) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) Method(java.lang.reflect.Method) BuildTool(org.wildfly.swarm.tools.BuildTool) BufferedReader(java.io.BufferedReader) DeploymentException(org.jboss.arquillian.container.spi.client.container.DeploymentException) File(java.io.File)

Example 3 with DeclaredDependencies

use of org.wildfly.swarm.tools.DeclaredDependencies in project wildfly-swarm by wildfly-swarm.

the class MavenDependencyDeclarationFactory method create.

@Override
public DeclaredDependencies create(FileSystemLayout ignored, ShrinkwrapArtifactResolvingHelper resolvingHelper) {
    final DeclaredDependencies declaredDependencies = new DeclaredDependencies();
    final PomEquippedResolveStage pom = MavenProfileLoader.loadPom(resolvingHelper.getResolver());
    // NonTransitiveStrategy
    final MavenResolvedArtifact[] explicitDeps = resolvingHelper.withResolver(r -> pom.importRuntimeAndTestDependencies().resolve().withoutTransitivity().asResolvedArtifact());
    // TransitiveStrategy
    for (MavenResolvedArtifact directDep : explicitDeps) {
        ArtifactSpec parent = new ArtifactSpec(directDep.getScope().toString(), directDep.getCoordinate().getGroupId(), directDep.getCoordinate().getArtifactId(), directDep.getCoordinate().getVersion(), directDep.getCoordinate().getPackaging().toString(), directDep.getCoordinate().getClassifier(), directDep.asFile());
        MavenResolvedArtifact[] bucket = resolvingHelper.withResolver(r -> {
            r.addDependency(resolvingHelper.createMavenDependency(parent));
            return pom.resolve().withTransitivity().asResolvedArtifact();
        });
        for (MavenResolvedArtifact dep : bucket) {
            ArtifactSpec child = new ArtifactSpec(dep.getScope().toString(), dep.getCoordinate().getGroupId(), dep.getCoordinate().getArtifactId(), dep.getCoordinate().getVersion(), dep.getCoordinate().getPackaging().toString(), dep.getCoordinate().getClassifier(), dep.asFile());
            declaredDependencies.add(parent, child);
        }
    }
    return declaredDependencies;
}
Also used : MavenResolvedArtifact(org.jboss.shrinkwrap.resolver.api.maven.MavenResolvedArtifact) ArtifactSpec(org.wildfly.swarm.tools.ArtifactSpec) DeclaredDependencies(org.wildfly.swarm.tools.DeclaredDependencies) PomEquippedResolveStage(org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage)

Example 4 with DeclaredDependencies

use of org.wildfly.swarm.tools.DeclaredDependencies in project wildfly-swarm by wildfly-swarm.

the class PackageMojo method executeSpecific.

@SuppressWarnings("deprecation")
@Override
public void executeSpecific() throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
        getLog().info("Skipping packaging");
        return;
    }
    if (this.project.getPackaging().equals("pom")) {
        getLog().info("Not processing project with pom packaging");
        return;
    }
    initProperties(false);
    final Artifact primaryArtifact = this.project.getArtifact();
    final String finalName = this.project.getBuild().getFinalName();
    final String type = primaryArtifact.getType();
    final File primaryArtifactFile = divineFile();
    if (primaryArtifactFile == null) {
        throw new MojoExecutionException("Cannot package without a primary artifact; please `mvn package` prior to invoking wildfly-swarm:package from the command-line");
    }
    final DeclaredDependencies declaredDependencies = new DeclaredDependencies();
    final BuildTool tool = new BuildTool(mavenArtifactResolvingHelper()).projectArtifact(primaryArtifact.getGroupId(), primaryArtifact.getArtifactId(), primaryArtifact.getBaseVersion(), type, primaryArtifactFile, finalName.endsWith("." + type) ? finalName : String.format("%s.%s", finalName, type)).properties(this.properties).mainClass(this.mainClass).bundleDependencies(this.bundleDependencies).executable(executable).executableScript(executableScript).fractionDetectionMode(fractionDetectMode).hollow(hollow).logger(new SimpleLogger() {

        @Override
        public void debug(String msg) {
            getLog().debug(msg);
        }

        @Override
        public void info(String msg) {
            getLog().info(msg);
        }

        @Override
        public void error(String msg) {
            getLog().error(msg);
        }

        @Override
        public void error(String msg, Throwable t) {
            getLog().error(msg, t);
        }
    });
    this.additionalFractions.stream().map(f -> FractionDescriptor.fromGav(FractionList.get(), f)).map(ArtifactSpec::fromFractionDescriptor).forEach(tool::fraction);
    Map<ArtifactSpec, Set<ArtifactSpec>> buckets = createBuckets(this.project.getArtifacts(), this.project.getDependencies());
    for (ArtifactSpec directDep : buckets.keySet()) {
        if (!(directDep.scope.equals("compile") || directDep.scope.equals("runtime"))) {
            // ignore anything but compile and runtime
            continue;
        }
        Set<ArtifactSpec> transientDeps = buckets.get(directDep);
        if (transientDeps.isEmpty()) {
            declaredDependencies.add(directDep);
        } else {
            for (ArtifactSpec transientDep : transientDeps) {
                declaredDependencies.add(directDep, transientDep);
            }
        }
    }
    tool.declaredDependencies(declaredDependencies);
    this.project.getResources().forEach(r -> tool.resourceDirectory(r.getDirectory()));
    Path uberjarResourcesDir = null;
    if (this.uberjarResources == null) {
        uberjarResourcesDir = Paths.get(this.project.getBasedir().toString()).resolve("src").resolve("main").resolve("uberjar");
    } else {
        uberjarResourcesDir = Paths.get(this.uberjarResources);
    }
    tool.uberjarResourcesDirectory(uberjarResourcesDir);
    this.additionalModules.stream().map(m -> new File(this.project.getBuild().getOutputDirectory(), m)).filter(File::exists).map(File::getAbsolutePath).forEach(tool::additionalModule);
    try {
        File jar = tool.build(finalName + (this.hollow ? "-hollow" : ""), Paths.get(this.projectBuildDir));
        ArtifactHandler handler = new DefaultArtifactHandler("jar");
        Artifact swarmJarArtifact = new DefaultArtifact(primaryArtifact.getGroupId(), primaryArtifact.getArtifactId(), primaryArtifact.getBaseVersion(), primaryArtifact.getScope(), "jar", (this.hollow ? "hollow" : "") + "swarm", handler);
        swarmJarArtifact.setFile(jar);
        this.project.addAttachedArtifact(swarmJarArtifact);
        if (this.project.getPackaging().equals("war")) {
            tool.repackageWar(primaryArtifactFile);
        }
    } catch (Exception e) {
        throw new MojoFailureException("Unable to create -swarm.jar", e);
    }
}
Also used : Path(java.nio.file.Path) DefaultArtifact(org.apache.maven.artifact.DefaultArtifact) DefaultArtifactHandler(org.apache.maven.artifact.handler.DefaultArtifactHandler) SimpleLogger(org.wildfly.swarm.spi.meta.SimpleLogger) ArtifactHandler(org.apache.maven.artifact.handler.ArtifactHandler) Files(java.nio.file.Files) DeclaredDependencies(org.wildfly.swarm.tools.DeclaredDependencies) Set(java.util.Set) FractionDescriptor(org.wildfly.swarm.fractions.FractionDescriptor) BuildTool(org.wildfly.swarm.tools.BuildTool) Parameter(org.apache.maven.plugins.annotations.Parameter) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) File(java.io.File) FractionList(org.wildfly.swarm.fractions.FractionList) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Mojo(org.apache.maven.plugins.annotations.Mojo) Paths(java.nio.file.Paths) Map(java.util.Map) Artifact(org.apache.maven.artifact.Artifact) LifecyclePhase(org.apache.maven.plugins.annotations.LifecyclePhase) ResolutionScope(org.apache.maven.plugins.annotations.ResolutionScope) Path(java.nio.file.Path) ArtifactSpec(org.wildfly.swarm.tools.ArtifactSpec) Set(java.util.Set) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) DeclaredDependencies(org.wildfly.swarm.tools.DeclaredDependencies) MojoFailureException(org.apache.maven.plugin.MojoFailureException) DefaultArtifact(org.apache.maven.artifact.DefaultArtifact) Artifact(org.apache.maven.artifact.Artifact) SimpleLogger(org.wildfly.swarm.spi.meta.SimpleLogger) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) DefaultArtifactHandler(org.apache.maven.artifact.handler.DefaultArtifactHandler) ArtifactHandler(org.apache.maven.artifact.handler.ArtifactHandler) ArtifactSpec(org.wildfly.swarm.tools.ArtifactSpec) DefaultArtifactHandler(org.apache.maven.artifact.handler.DefaultArtifactHandler) BuildTool(org.wildfly.swarm.tools.BuildTool) File(java.io.File) DefaultArtifact(org.apache.maven.artifact.DefaultArtifact)

Example 5 with DeclaredDependencies

use of org.wildfly.swarm.tools.DeclaredDependencies in project wildfly-swarm by wildfly-swarm.

the class StartMojo method dependencies.

@SuppressWarnings("unchecked")
List<Path> dependencies(final Path archiveContent, final boolean scanDependencies) throws MojoFailureException {
    final List<Path> elements = new ArrayList<>();
    final Set<Artifact> artifacts = this.project.getArtifacts();
    boolean hasSwarmDeps = false;
    final DeclaredDependencies declaredDependencies = new DeclaredDependencies();
    for (Artifact each : artifacts) {
        String parentDep = each.getDependencyTrail().get(1);
        declaredDependencies.add(DeclaredDependencies.createSpec(parentDep), DeclaredDependencies.createSpec(each.toString()));
        if (each.getGroupId().equals(DependencyManager.WILDFLY_SWARM_GROUP_ID) && each.getArtifactId().equals(DependencyManager.WILDFLY_SWARM_BOOTSTRAP_ARTIFACT_ID)) {
            hasSwarmDeps = true;
        }
        if (each.getGroupId().equals("org.jboss.logmanager") && each.getArtifactId().equals("jboss-logmanager")) {
            continue;
        }
        if (each.getScope().equals("provided")) {
            continue;
        }
        elements.add(each.getFile().toPath());
    }
    if (declaredDependencies.getDirectDeps().size() > 0) {
        try {
            // multi-start doesn't have a projectBuildDir
            File tmp = this.projectBuildDir != null ? Files.createTempFile(Paths.get(this.projectBuildDir), TempFileManager.WFSWARM_TMP_PREFIX + "swarm-", "-cp.txt").toFile() : Files.createTempFile(TempFileManager.WFSWARM_TMP_PREFIX + "swarm-", "-cp.txt").toFile();
            tmp.deleteOnExit();
            getPluginContext().put("swarm-cp-file", tmp);
            declaredDependencies.writeTo(tmp);
            getLog().debug("dependency info stored at: " + tmp.getAbsolutePath());
            this.properties.setProperty("swarm.cp.info", tmp.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    elements.add(Paths.get(this.project.getBuild().getOutputDirectory()));
    if (fractionDetectMode != BuildTool.FractionDetectionMode.never) {
        if (fractionDetectMode == BuildTool.FractionDetectionMode.force || !hasSwarmDeps) {
            List<Path> fractionDeps = findNeededFractions(artifacts, archiveContent, scanDependencies);
            for (Path p : fractionDeps) {
                if (!elements.contains(p)) {
                    elements.add(p);
                }
            }
        }
    } else if (!hasSwarmDeps) {
        getLog().warn("No WildFly Swarm dependencies found and fraction detection disabled");
    }
    return elements;
}
Also used : Path(java.nio.file.Path) DeclaredDependencies(org.wildfly.swarm.tools.DeclaredDependencies) ArrayList(java.util.ArrayList) IOException(java.io.IOException) File(java.io.File) Artifact(org.apache.maven.artifact.Artifact)

Aggregations

DeclaredDependencies (org.wildfly.swarm.tools.DeclaredDependencies)8 File (java.io.File)5 ArtifactSpec (org.wildfly.swarm.tools.ArtifactSpec)4 BuildTool (org.wildfly.swarm.tools.BuildTool)4 Path (java.nio.file.Path)3 ArrayList (java.util.ArrayList)2 Properties (java.util.Properties)2 Artifact (org.apache.maven.artifact.Artifact)2 SimpleLogger (org.wildfly.swarm.spi.meta.SimpleLogger)2 BufferedReader (java.io.BufferedReader)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 Method (java.lang.reflect.Method)1 Files (java.nio.file.Files)1 Paths (java.nio.file.Paths)1 Map (java.util.Map)1 Optional (java.util.Optional)1