Java Code Examples for org.jboss.shrinkwrap.api.Node#getAsset()

The following examples show how to use org.jboss.shrinkwrap.api.Node#getAsset() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConfigApplicationArchiveProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Archive<?> applicationArchive, TestClass testClass) {
    if (applicationArchive instanceof WebArchive) {
        WebArchive war = applicationArchive.as(WebArchive.class);
        Node libNode = war.get(PATH_LIBRARY);
        if (libNode != null) {
            for (Node child : libNode.getChildren()) {
                Asset childAsset = child.getAsset();
                if (childAsset instanceof ArchiveAsset) {
                    ArchiveAsset archiveAsset = (ArchiveAsset) childAsset;
                    if (archiveAsset.getArchive() instanceof JavaArchive) {
                        JavaArchive libArchive = (JavaArchive) archiveAsset.getArchive();
                        libArchive.deleteClass(testClass.getName());
                    }
                }
            }
        }
    }
}
 
Example 2
Source File: JBossWebContainer.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
default JBossWebAsset findJbossWebAsset() {
    final Node jbossWeb = this.get(JBOSS_WEB_PATH);
    Asset asset;
    if (jbossWeb == null) {
        asset = new JBossWebAsset();
        this.add(asset, JBOSS_WEB_PATH);
    } else {
        asset = jbossWeb.getAsset();
        if (!(asset instanceof JBossWebAsset)) {
            asset = new JBossWebAsset(asset.openStream());
            this.add(asset, JBOSS_WEB_PATH);
        }
    }

    return (JBossWebAsset) asset;
}
 
Example 3
Source File: ShrinkWrapResource.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public InputStream getResourceAsStreamByLocation(String location) {
    if (location == null) {
        return null;
    }
    
    Node node = getNode(archive, location);
    if (node == null) {
        return null;
    }
    
    Asset asset = node.getAsset();
    if (asset == null) {
        // Node was a directory
        return new ShrinkWrapDirectoryInputStream(getContentFromNode(node));
    }
    
    // Node was an asset
    return asset.openStream();
}
 
Example 4
Source File: Main.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
    swarm = new Swarm(args);
    swarm.start();
    Archive<?> deployment = swarm.createDefaultDeployment();
    if (deployment == null) {
        throw new Error("Couldn't create default deployment");
    }

    Node persistenceXml = deployment.get("WEB-INF/classes/META-INF/persistence.xml");

    if (persistenceXml == null) {
        throw new Error("persistence.xml is not found");
    }

    if (persistenceXml.getAsset() == null) {
        throw new Error("persistence.xml is not found");
    }

    swarm.deploy(deployment);
}
 
Example 5
Source File: KeycloakMicroprofileJwtArchivePreparer.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private InputStream getKeycloakJsonFromClasspath(String resourceName) {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream keycloakJson = cl.getResourceAsStream(resourceName);
    if (keycloakJson == null) {

        Node jsonNode = archive.get(resourceName);
        if (jsonNode == null) {
            jsonNode = getKeycloakJsonNodeFromWebInf(resourceName, true);
        }
        if (jsonNode == null) {
            jsonNode = getKeycloakJsonNodeFromWebInf(resourceName, false);
        }
        if (jsonNode != null && jsonNode.getAsset() != null) {
            keycloakJson = jsonNode.getAsset().openStream();
        }
    }
    return keycloakJson;
}
 
Example 6
Source File: JBossDeploymentStructureContainer.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
default JBossDeploymentStructureAsset getDescriptorAsset() {
    String path = PRIMARY_JBOSS_DEPLOYMENT_DESCRIPTOR_PATH;
    Node jbossDS = this.get(PRIMARY_JBOSS_DEPLOYMENT_DESCRIPTOR_PATH);
    if (jbossDS == null) {
        jbossDS = this.get(SECONDARY_JBOSS_DEPLOYMENT_DESCRIPTOR_PATH);
        if (jbossDS != null) {
            path = SECONDARY_JBOSS_DEPLOYMENT_DESCRIPTOR_PATH;
        }
    }
    Asset asset;

    if (jbossDS == null) {
        asset = new JBossDeploymentStructureAsset();
    } else {
        asset = jbossDS.getAsset();
        if (!(asset instanceof JBossDeploymentStructureAsset)) {
            asset = new JBossDeploymentStructureAsset(asset.openStream());
        }
    }

    this.add(asset, path);

    return (JBossDeploymentStructureAsset) asset;
}
 
Example 7
Source File: TopologyArchiveImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new instance using the underlying specified archive, which is required
 *
 * @param archive
 */
public TopologyArchiveImpl(ArchiveBase<?> archive) throws IOException {
    super(archive);

    Node regConf = as(JARArchive.class).get(REGISTRATION_CONF);
    if (regConf != null && regConf.getAsset() != null) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(regConf.getAsset().openStream()))) {
            reader.lines().forEach(this::parseConfigLine);
        }
    }
}
 
Example 8
Source File: DefaultApplicationDeploymentProcessorTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplicationPathAnnotation_SpecifiedInProjectDefaults() throws Exception {
    JAXRSArchive archive = ShrinkWrap.create(JAXRSArchive.class, "app.war");
    DefaultApplicationDeploymentProcessor processor = new DefaultApplicationDeploymentProcessor(archive);
    processor.applicationPath.set("/api-test"); // Simulate the behavior of loading the project defaults.
    processor.process();

    Node generated = archive.get(PATH);
    Asset asset = generated.getAsset();

    assertThat(generated).isNotNull();
    assertThat(asset).isNotNull();
}
 
Example 9
Source File: JAXRSArchiveImpl.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
protected void addGeneratedApplication() {

        Map<ArchivePath, Node> content = getArchive().getContent();

        boolean applicationFound = false;

        for (Map.Entry<ArchivePath, Node> entry : content.entrySet()) {
            Node node = entry.getValue();
            Asset asset = node.getAsset();
            if (hasApplicationPathAnnotation(node.getPath(), asset)) {
                applicationFound = true;
                break;
            }
        }

        if (!applicationFound) {
            String name = "org.wildfly.swarm.generated.WildFlySwarmDefaultJAXRSApplication";
            String path = "WEB-INF/classes/" + name.replace('.', '/') + ".class";

            byte[] generatedApp = new byte[0];
            try {
                generatedApp = ApplicationFactory2.create(name, "/");
                add(new ByteArrayAsset(generatedApp), path);
                addHandlers(new ApplicationHandler(this, path));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
Example 10
Source File: ContextPathArchivePreparerTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testExternalMount() throws Exception {
    WARArchive archive = DefaultWarDeploymentFactory.archiveFromCurrentApp();

    assertThat(archive.getContextRoot()).isNull();

    URL url = getClass().getClassLoader().getResource("mounts.yml");
    ConfigViewFactory factory = new ConfigViewFactory(new Properties());
    factory.load("test", url);
    factory.withProfile("test");
    ConfigViewImpl view = factory.get(true);

    List<String> mounts = view.resolve("thorntail.context.mounts").as(List.class).getValue();

    ContextPathArchivePreparer preparer = new ContextPathArchivePreparer(archive);
    preparer.mounts = mounts;

    preparer.process();

    Node externalMount = archive.get(WARArchive.EXTERNAL_MOUNT_PATH);
    assertThat(externalMount).isNotNull();
    assertThat(externalMount.getAsset()).isInstanceOf(UndertowExternalMountsAsset.class);
    UndertowExternalMountsAsset externalMountAsset = (UndertowExternalMountsAsset) externalMount.getAsset();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(externalMountAsset.openStream()));) {
        assertThat(reader.readLine()).endsWith("external1");
        assertThat(reader.readLine()).endsWith("external2");
    }

}
 
Example 11
Source File: SWClassLoader.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
protected URLConnection openConnection(final URL u) throws IOException {
    final String arName = key(u);

    final Archive<?> archive = archives.get(arName);
    final String path = path(archive.getName(), WebArchive.class.isInstance(archive) ? "/WEB-INF/classes/" : "", u);
    Node node = archive.get(path);
    if (node == null) {
        node = archive.get(path(archive.getName(), "", u)); // web resources
        if (node == null) {
            throw new IOException(u.toExternalForm() + " not found");
        }
    }

    final Asset asset = node.getAsset();
    if (UrlAsset.class.isInstance(asset)) {
        return URL.class.cast(Reflections.get(asset, "url")).openConnection();
    } else if (FileAsset.class.isInstance(asset)) {
        return File.class.cast(Reflections.get(asset, "file")).toURI().toURL().openConnection();
    } else if (ClassLoaderAsset.class.isInstance(asset)) {
        return ClassLoader.class.cast(Reflections.get(asset, "classLoader")).getResource(String.class.cast(Reflections.get(asset, "resourceName"))).openConnection();
    }

    return new URLConnection(u) {
        @Override
        public void connect() throws IOException {
            // no-op
        }

        @Override
        public InputStream getInputStream() throws IOException {
            final InputStream input = asset.openStream();
            final Collection<Closeable> c = closeables.get(arName);
            c.add(input);
            return input;
        }
    };
}
 
Example 12
Source File: UndertowDeployerHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addAnnotatedServlets(DeploymentInfo di, Archive<?> archive) {
    Map<ArchivePath, Node> classNodes = archive.getContent((ArchivePath path) -> {

        String stringPath = path.get();
        return (stringPath.startsWith("/WEB-INF/classes") && stringPath.endsWith("class"));

    });

    for (Map.Entry<ArchivePath, Node> entry : classNodes.entrySet()) {
        Node n = entry.getValue();
        if (n.getAsset() instanceof ClassAsset) {
            ClassAsset classAsset = (ClassAsset) n.getAsset();
            Class<?> clazz = classAsset.getSource();

            WebServlet annotation = clazz.getAnnotation(WebServlet.class);
            if (annotation != null) {
                ServletInfo undertowServlet = new ServletInfo(clazz.getSimpleName(), (Class<? extends Servlet>) clazz);

                String[] mappings = annotation.value();
                if (mappings != null) {
                    for (String urlPattern : mappings) {
                        undertowServlet.addMapping(urlPattern);
                    }
                }

                di.addServlet(undertowServlet);
            }
        }
    }

}
 
Example 13
Source File: SwaggerArchiveImpl.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
private void loadOrCreateConfigurationAsset() {
    Node node = getArchive().get(SWAGGER_CONFIGURATION_PATH);
    if (node != null) {
        Asset asset = node.getAsset();
        if (asset instanceof SwaggerConfigurationAsset) {
            this.configurationAsset = (SwaggerConfigurationAsset) asset;
        } else {
            this.configurationAsset = new SwaggerConfigurationAsset(asset.openStream());
        }
    } else {
        this.configurationAsset = new SwaggerConfigurationAsset();
        getArchive().add(this.configurationAsset, SWAGGER_CONFIGURATION_PATH);
    }
}
 
Example 14
Source File: ShrinkWrapResource.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Asset getAsset(Archive<?> archiveToGetFrom, String location) {
    Node node = getNode(archiveToGetFrom, location);
    if (node == null) {
        return null;
    }

    Asset asset = node.getAsset();
    if (asset == null) {
        return null;
    }
    
    return asset;
}
 
Example 15
Source File: ShrinkWrapResource.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public URL getResource(String url) {
    String location = getLocationFromUrl(url);
    if (location == null) {
        return null;
    }
    
    Node node = getNode(archive, location);
    if (node == null) {
        return null;
    }
    
    URLStreamHandler streamHandler = archiveStreamHandler;
    Asset asset = node.getAsset();
    if (asset == null) {
        // Node was a directory
        streamHandler = new NodeURLStreamHandler(getContentFromNode(node));
    }
    
    try {
        return new URL(null, 
            "shrinkwrap://" + archive.getName() + (location.startsWith("/")? "" : archive.getName().endsWith("/")? "" : "/") + location, 
            streamHandler);
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 16
Source File: OpenEJBArchiveProcessor.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static void addPersistenceXml(final Archive<?> archive, final String prefix, final AppModule appModule) {
    Node persistenceXml = archive.get(prefix.concat(PERSISTENCE_XML));
    if (persistenceXml == null && WEB_INF.equals(prefix)) {
        persistenceXml = archive.get(WEB_INF_CLASSES.concat(META_INF).concat(PERSISTENCE_XML));
    }
    if (persistenceXml != null) {
        final Asset asset = persistenceXml.getAsset();
        if (UrlAsset.class.isInstance(asset)) {
            appModule.getAltDDs().put(PERSISTENCE_XML, Arrays.asList(get(URL.class, "url", asset)));
        } else if (FileAsset.class.isInstance(asset)) {
            try {
                appModule.getAltDDs().put(PERSISTENCE_XML, Arrays.asList(get(File.class, "file", asset).toURI().toURL()));
            } catch (final MalformedURLException e) {
                appModule.getAltDDs().put(PERSISTENCE_XML, Arrays.asList(new AssetSource(persistenceXml.getAsset(), null)));
            }
        } else if (ClassLoaderAsset.class.isInstance(asset)) {
            final URL url = get(ClassLoader.class, "classLoader", asset).getResource(get(String.class, "resourceName", asset));
            if (url != null) {
                appModule.getAltDDs().put(PERSISTENCE_XML, Arrays.asList(url));
            } else {
                appModule.getAltDDs().put(PERSISTENCE_XML, Arrays.asList(new AssetSource(persistenceXml.getAsset(), null)));
            }
        } else {
            appModule.getAltDDs().put(PERSISTENCE_XML, Arrays.asList(new AssetSource(persistenceXml.getAsset(), null)));
        }
    }
}
 
Example 17
Source File: ManagedSEDeployableContainer.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
private void materializeDirectory(Archive<?> archive) throws DeploymentException {
    if (archive.getContent().isEmpty()) {
        // Do not materialize an empty directory
        return;
    }
    File entryDirectory = new File(TARGET.concat(File.separator).concat(archive.getName()));
    try {
        if (entryDirectory.exists()) {
            // Always delete previous content
            FileDeploymentUtils.deleteContent(entryDirectory.toPath());
        } else {
            if (!entryDirectory.mkdirs()) {
                throw new DeploymentException("Could not create class path directory: " + entryDirectory);
            }
        }
        for (Node child : archive.get(ClassPath.ROOT_ARCHIVE_PATH).getChildren()) {
            Asset asset = child.getAsset();
            if (asset instanceof ClassAsset) {
                FileDeploymentUtils.materializeClass(entryDirectory, (ClassAsset) asset);
            } else if (asset == null) {
                FileDeploymentUtils.materializeSubdirectories(entryDirectory, child);
            }
        }
    } catch (IOException e) {
        throw new DeploymentException("Could not materialize class path directory: " + archive.getName(), e);
    }
    materializedFiles.add(entryDirectory);
}
 
Example 18
Source File: StaticContentContainer.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
default T staticContent(String base) {
    as(WARArchive.class).addModule("org.wildfly.swarm.undertow", "runtime");

    try {
        // Add all the static content from the current app to the archive
        Archive allResources = DefaultWarDeploymentFactory.archiveFromCurrentApp();
        // Here we define static as basically anything that's not a
        // Java class file or under WEB-INF or META-INF
        mergeIgnoringDuplicates(allResources, base, Filters.exclude(".*\\.class$"));
    } catch (Exception ex) {
        log.log(Level.WARNING, "Error setting up static resources", ex);
    }

    Node node = get("WEB-INF/undertow-external-mounts.conf");
    UndertowExternalMountsAsset asset;
    if (node == null) {
        asset = new UndertowExternalMountsAsset();
        add(asset, "WEB-INF/undertow-external-mounts.conf");
    } else {
        asset = (UndertowExternalMountsAsset) node.getAsset();
    }

    // Add external mounts for static content so changes are picked up
    // immediately during development
    Path webResources = Paths.get(System.getProperty("user.dir"), "src", "main", "webapp");
    if (base != null) {
        webResources = webResources.resolve(base);
    }
    if (Files.exists(webResources)) {
        asset.externalMount(webResources.toString());
    }
    webResources = Paths.get(System.getProperty("user.dir"), "src", "main", "resources");
    if (base != null) {
        webResources = webResources.resolve(base);
    }
    if (Files.exists(webResources)) {
        asset.externalMount(webResources.toString());
    }

    return (T) this;
}
 
Example 19
Source File: SecuredTest.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Test
public void testExistingWebXml() {
    WARArchive archive = ShrinkWrap.create( WARArchive.class );

    ClassLoaderAsset asset = new ClassLoaderAsset("test-web.xml");
    archive.addAsWebInfResource( asset, "web.xml" );

    archive.as(Secured.class)
            .protect( "/cheddar" );

    Node webXml = archive.get("WEB-INF/web.xml");

    Asset newAsset = webXml.getAsset();

    InputStream in = newAsset.openStream();
    BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );

    List<String> lines = reader.lines().map(String::trim).collect(Collectors.toList());

    assertThat( lines ).contains( "<servlet-name>comingsoon</servlet-name>" );
    assertThat( lines ).contains( "<url-pattern>/cheddar</url-pattern>" );
}
 
Example 20
Source File: ManagedSEDeployableContainer.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
public ProtocolMetaData deploy(final Archive<?> archive) throws DeploymentException {
    LOGGER.info("Deploying " + archive.getName());

    // First of all clear the list of previously materialized deployments - otherwise the class path would grow indefinitely
    materializedFiles.clear();

    // Create a new classpath
    classpathDependencies.clear();

    if (ClassPath.isRepresentedBy(archive)) {
        for (Node child : archive.get(ClassPath.ROOT_ARCHIVE_PATH).getChildren()) {
            Asset asset = child.getAsset();
            if (asset instanceof ArchiveAsset) {
                Archive<?> assetArchive = ((ArchiveAsset) asset).getArchive();
                if (ClassPathDirectory.isRepresentedBy(assetArchive)) {
                    materializeDirectory(assetArchive);
                } else {
                    materializeArchive(assetArchive);
                }
            }
        }
    } else {
        materializeArchive(archive);
    }

    Properties systemProperties = getSystemProperties(archive);
    readJarFilesFromDirectory();
    addTestResourcesDirectory(systemProperties);

    List<String> processCommand = buildProcessCommand(systemProperties);
    logExecutedCommand(processCommand);
    // Launch the process
    final ProcessBuilder processBuilder = new ProcessBuilder(processCommand);

    String path = systemProperties.getProperty("container.user.dir");
    if (path != null) {
        processBuilder.directory(new File(path));
    }

    processBuilder.environment().put("JAVA_HOME", new File(System.getProperty(SYSPROP_KEY_JAVA_HOME)).getAbsolutePath());

    processBuilder.redirectErrorStream(true);
    processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
    processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

    try {
        process = processBuilder.start();
    } catch (final IOException e) {
        throw new DeploymentException("Could not start process", e);
    }

    int finalWaitTime = debugModeEnabled ? (3 * waitTime) : waitTime;

    // Wait for socket connection
    if (!isServerStarted(host, port, finalWaitTime)) {
        throw new DeploymentException("Child JVM process failed to start within " + finalWaitTime + " seconds.");
    }
    if (!isJMXTestRunnerMBeanRegistered(host, port, finalWaitTime)) {
        throw new DeploymentException("JMXTestRunnerMBean not registered within " + finalWaitTime + " seconds.");
    }

    ProtocolMetaData protocolMetaData = new ProtocolMetaData();
    protocolMetaData.addContext(new JMXContext(host, port));
    return protocolMetaData;
}