Java Code Examples for org.jboss.shrinkwrap.api.asset.Asset#openStream()

The following examples show how to use org.jboss.shrinkwrap.api.asset.Asset#openStream() . 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: 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 2
Source File: DependencyManager.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isRemovable(Node node) {
    Asset asset = node.getAsset();
    if (asset == null) {
        return false;
    }

    if (removableCheckSums == null) {
        initCheckSums();
    }

    try (final InputStream inputStream = asset.openStream()) {
        String checksum = ChecksumUtil.calculateChecksum(inputStream);

        return this.removableCheckSums.contains(checksum);
    } catch (NoSuchAlgorithmException | IOException e) {
        e.printStackTrace();
    }

    return false;
}
 
Example 3
Source File: SwaggerArchiveImpl.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private void loadOrCreateConfigurationAsset() throws IOException {

        Node node = getArchive().get(SWAGGER_CONFIGURATION_PATH);

        if (node == null && getArchive().getName().endsWith(".war")) {
            node = getArchive().get("WEB-INF/classes/" + 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());
                getArchive().add(this.configurationAsset, node.getPath());
            }
        } else {
            this.configurationAsset = new SwaggerConfigurationAsset();
            if (getArchive().getName().endsWith(".war")) {
                getArchive().add(this.configurationAsset, "WEB-INF/classes/" + SWAGGER_CONFIGURATION_PATH);
            } else {
                getArchive().add(this.configurationAsset, SWAGGER_CONFIGURATION_PATH);
            }
        }
    }
 
Example 4
Source File: JBossWebContainer.java    From thorntail with Apache License 2.0 6 votes vote down vote up
/**
 * Locate and load, or create a {@code jboss-web.xml} asset for this archive.
 *
 * @return The existing or new {@code jboss-web.xml} asset.
 */
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 5
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 6
Source File: JAXRSArchiveImpl.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private static boolean isJAXRS(ArchivePath path, Asset asset) {
    if (asset == null) {
        return false;
    }

    if (asset instanceof ArchiveAsset) {
        return isJAXRS(((ArchiveAsset) asset).getArchive());
    }

    if (!path.get().endsWith(".class")) {
        return false;
    }
    try (InputStream in = asset.openStream()) {
        ClassReader reader = new ClassReader(in);
        JAXRSAnnotationSeekingClassVisitor visitor = new JAXRSAnnotationSeekingClassVisitor();
        reader.accept(visitor, 0);
        return visitor.isFound();
    } catch (IOException ignored) {
    }
    return false;
}
 
Example 7
Source File: DefaultApplicationDeploymentProcessor.java    From thorntail with Apache License 2.0 6 votes vote down vote up
static boolean hasApplicationPathAnnotation(ArchivePath path, Asset asset) {
    if (asset == null) {
        return false;
    }

    if (asset instanceof ArchiveAsset) {
        return hasApplicationPathAnnotation(((ArchiveAsset) asset).getArchive());
    }

    if (!path.get().endsWith(".class")) {
        return false;
    }

    try (InputStream in = asset.openStream()) {
        ClassReader reader = new ClassReader(in);
        ApplicationPathAnnotationSeekingClassVisitor visitor = new ApplicationPathAnnotationSeekingClassVisitor();
        reader.accept(visitor, 0);
        return visitor.isFound();
    } catch (IOException ignored) {
    }

    return false;
}
 
Example 8
Source File: DefaultApplicationDeploymentProcessor.java    From thorntail with Apache License 2.0 6 votes vote down vote up
static boolean hasApplicationServletMapping(Asset asset) {
    if (asset == null) {
        return false;
    }
    WebXmlAsset webXmlAsset;
    if (asset instanceof WebXmlAsset) {
        webXmlAsset = (WebXmlAsset) asset;
    } else {
        try {
            webXmlAsset = new WebXmlAsset(asset.openStream());
        } catch (Exception e) {
            JAXRSMessages.MESSAGES.unableToParseWebXml(e);
            return false;
        }
    }
    return !webXmlAsset.getServletMapping(Application.class.getName()).isEmpty();
}
 
Example 9
Source File: JBossDeploymentStructureContainer.java    From thorntail with Apache License 2.0 6 votes vote down vote up
/** Retrieve the underlying {@code jboss-deployment-structure.xml} descriptor asset.
 *
 * <p>This method will effectively round-trip an existing {@code .xml} file into
 * the appropriate descriptor object tree.</p>
 *
 * @return The existing descriptor asset, if present, else a newly-created one.
 */
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 10
Source File: NotificationFilter.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected static byte[] toBytes(Asset asset) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = asset.openStream();
        try {
            Utils.copyStream(is, baos);
        } finally {
            Utils.safeClose(is);
        }
        return baos.toByteArray();
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 11
Source File: ServiceFileCombinationImpl.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static List<String> read(Asset asset, String path) {
    List<String> lines;
    try (InputStream input = asset.openStream()){
        lines = IOUtils.readLines(input, "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException("Cannot read " + path, e);
    }
    return lines;
}
 
Example 12
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 13
Source File: SwaggerArchiveTest.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwaggerConfiguration() {
    JARArchive archive = ShrinkWrap.create(JARArchive.class, "myapp.jar");

    archive.as(SwaggerArchive.class)
            .setResourcePackages("com.tester.resource", "com.tester.other.resource")
            .setTitle("My Application API")
            .setLicenseUrl("http://myapplication.com/license.txt")
            .setLicense("Use at will")
            .setContextRoot("/tacos")
            .setDescription("This is a description of my API")
            .setHost("api.myapplication.com")
            .setContact("[email protected]")
            .setPrettyPrint(true)
            .setSchemes("http", "https")
            .setTermsOfServiceUrl("http://myapplication.com/tos.txt")
            .setVersion("1.0");


    Asset asset = archive.get(SwaggerArchive.SWAGGER_CONFIGURATION_PATH).getAsset();
    assertThat(asset).isNotNull();
    assertThat(asset).isInstanceOf(SwaggerConfigurationAsset.class);

    SwaggerConfig config = new SwaggerConfig(asset.openStream());
    assertThat(config.get(SwaggerConfig.Key.VERSION)).isEqualTo("1.0");
    assertThat(config.get(SwaggerConfig.Key.TERMS_OF_SERVICE_URL)).isEqualTo("http://myapplication.com/tos.txt");
    assertThat(config.get(SwaggerConfig.Key.PACKAGES)).isEqualTo("com.tester.resource,com.tester.other.resource");
}
 
Example 14
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 15
Source File: TestBase.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
protected static Asset rewriteAsset(Asset original) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (InputStream stream = original.openStream()) {
            int b;
            while ((b = stream.read()) != -1) {
                baos.write(b);
            }
        }
        String content = baos.toString();
        return new StringAsset(StringPropertyReplacer.replaceProperties(content));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 16
Source File: ServiceActivatorArchiveImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
protected void prepareAsset() {
    Node node = getArchive().get(path());
    if (node != null) {
        Asset maybeCorrect = node.getAsset();
        if (maybeCorrect instanceof ServiceActivatorAsset) {
            setAsset((ServiceActivatorAsset) maybeCorrect);
        } else {
            ServiceActivatorAsset read = new ServiceActivatorAsset(maybeCorrect.openStream());
            setAsset(read);
        }
    } else {
        setAsset(new ServiceActivatorAsset());
    }
}
 
Example 17
Source File: SwaggerArchiveTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwaggerConfiguration() throws IOException {
    JARArchive archive = ShrinkWrap.create(JARArchive.class, "myapp.jar");

    archive.as(SwaggerArchive.class)
            .setResourcePackages("com.tester.resource", "com.tester.other.resource")
            .setTitle("My Application API")
            .setLicenseUrl("http://myapplication.com/license.txt")
            .setLicense("Use at will")
            .setContextRoot("/tacos")
            .setDescription("This is a description of my API")
            .setHost("api.myapplication.com")
            .setContact("[email protected]")
            .setPrettyPrint(true)
            .setSchemes("http", "https")
            .setTermsOfServiceUrl("http://myapplication.com/tos.txt")
            .setVersion("1.0");


    Asset asset = archive.get(SwaggerArchive.SWAGGER_CONFIGURATION_PATH).getAsset();
    assertThat(asset).isNotNull();
    assertThat(asset).isInstanceOf(SwaggerConfigurationAsset.class);

    SwaggerConfig config = new SwaggerConfig(asset.openStream());
    assertThat(config.get(SwaggerConfig.Key.VERSION)).isEqualTo("1.0");
    assertThat(config.get(SwaggerConfig.Key.TERMS_OF_SERVICE_URL)).isEqualTo("http://myapplication.com/tos.txt");
    assertThat(Arrays.toString((String[]) config.get(SwaggerConfig.Key.PACKAGES))).isEqualTo("[com.tester.resource, com.tester.other.resource]");
    assertThat(config.get(SwaggerConfig.Key.ROOT)).isEqualTo("/tacos");
}
 
Example 18
Source File: ArchiveURLStreamHandler.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected StreamConnection openConnection(URL requestedUrl) throws IOException {
    return new StreamConnection(requestedUrl) {

        @Override
        public InputStream getInputStream() throws IOException {
            Node node = getNode();
            if (node == null) {
                throw new IllegalStateException("Can't resolve URL " + requestedUrl.toExternalForm());
            }

            Asset asset = node.getAsset();
            if (asset == null) {
                return null;
            }
            
            return asset.openStream();
        }
        
        private Node getNode() {
            return archive.get(
                ArchivePaths.create(
                    requestedUrl
                        .getPath()
                        .replace(archive.getName(), "")));
        }
    };
    
    
}
 
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: StaticContentContainer.java    From thorntail with Apache License 2.0 4 votes vote down vote up
/** Enable static content to be served from a given base in the classpath.
 *
 * @param base The path prefix to use for static content.
 * @return
 */
@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
        // I believe it does not make sense to call archiveFromCurrentApp() again if this archive was created by DefaultWarDeploymentFactory
        Archive allResources = contains(DefaultWarDeploymentFactory.MARKER_PATH) ? this : 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(EXTERNAL_MOUNT_PATH);
    UndertowExternalMountsAsset asset;
    if (node == null) {
        asset = new UndertowExternalMountsAsset();
        add(asset, EXTERNAL_MOUNT_PATH);
    } else {
        Asset tempAsset = node.getAsset();
        if (!(tempAsset instanceof UndertowExternalMountsAsset)) {
            asset = new UndertowExternalMountsAsset(tempAsset.openStream());
            add(asset, EXTERNAL_MOUNT_PATH);
        } 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;
}