Example usage for org.springframework.core.io Resource getInputStream

List of usage examples for org.springframework.core.io Resource getInputStream

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream for the content of an underlying resource.

Usage

From source file:com.themodernway.server.core.io.IO.java

public static final long checksum(final Resource resource) throws IOException {
    try (CheckSumInputStream check = new CheckSumInputStream(resource.getInputStream())) {
        IO.copy(check, new NoOpOutputStream());

        return check.getChecksum().getValue();
    }/* w w  w . j a  v a2 s. co  m*/
}

From source file:com.themodernway.server.core.io.IO.java

public static final String getStringAtMost(final Resource resource, final long leng, final long slop)
        throws IOException {
    try (InputStream stream = resource.getInputStream()) {
        return IO.getStringAtMost(stream, leng, slop);
    }//ww  w .  j a va  2 s  . c o m
}

From source file:com.themodernway.server.core.io.IO.java

public static final long checksum(final Resource resource, final Checksum ck) throws IOException {
    try (CheckSumInputStream check = new CheckSumInputStream(resource.getInputStream(), ck)) {
        IO.copy(check, new NoOpOutputStream());

        return check.getChecksum().getValue();
    }/*from   www .j a  v  a  2  s  .co m*/
}

From source file:com.themodernway.server.core.io.IO.java

public static final long copy(final Resource resource, final Writer output, long length) throws IOException {
    if ((length = Math.max(0L, length)) > 0L) {
        try (InputStream stream = resource.getInputStream()) {
            return IO.copy(stream, output, length);
        }/*from   www.  j  a v a2s.  c  o m*/
    }
    return length;
}

From source file:com.themodernway.server.core.io.IO.java

public static final long copy(final Resource resource, final OutputStream output, long length)
        throws IOException {
    if ((length = Math.max(0L, length)) > 0L) {
        try (InputStream stream = resource.getInputStream()) {
            return IO.copy(stream, output, length);
        }//from  w  ww .j a v  a  2  s .c o  m
    }
    return length;
}

From source file:fi.solita.phantomrunner.util.FileUtils.java

/**
 * Extracts the given resource to user's temporary directory (by creating a unique directory underneath
 * it). Will delete that file and created directories on system exit if deleteOnExit is true.
 * //  w  ww .jav a2s  .  com
 * @param resource Resource to be extracted
 * @param subPath Slash (character '/') separated path of the sub-directories which should be created
 * @param deleteOnExit If the resource and created sub-directories should be deleted
 * 
 * @return File handle to the created file in the temporary directory
 */
public static File extractResourceToTempDirectory(Resource resource, String subPath, boolean deleteOnExit)
        throws IOException {
    final File tempDir = Files.createTempDir();
    if (deleteOnExit)
        tempDir.deleteOnExit();

    File lastDir = tempDir;
    for (String subDir : subPath.split("/")) {
        // if the subPath starts or ends with '/' we'll get empty strings too
        if (StringUtils.hasLength(subDir)) {
            lastDir = new File(lastDir, subDir);
            lastDir.mkdir();
            if (deleteOnExit)
                lastDir.deleteOnExit();
        }
    }

    final File resFile = new File(lastDir, resource.getFilename());
    resFile.createNewFile();
    if (deleteOnExit)
        resFile.deleteOnExit();

    IOUtil.copy(resource.getInputStream(), new FileWriter(resFile), "UTF-8");

    return resFile;
}

From source file:org.jamwiki.utils.ResourceUtil.java

/**
 * Given a file name for a file that is located somewhere in the application
 * classpath, return a File object representing the file.
 *
 * @param filename The name of the file (relative to the classpath) that is
 *  to be retrieved./*from  ww  w.j a va 2s .co m*/
 * @return A file object representing the requested filename.  Note that the
 *  file name is not guaranteed to match the filename passed to this method
 *  since (for example) the file might be found in a JAR file and thus will
 *  need to be copied to a temporary location for reading.
 * @throws IOException Thrown if the classloader can not be found or if
 *  the file can not be found in the classpath.
 */
public static File getClassLoaderFile(String filename) throws IOException {
    // note that this method is used when initializing logging, so it must
    // not attempt to log anything.
    Resource resource = new ClassPathResource(filename);
    try {
        return resource.getFile();
    } catch (IOException e) {
        // does not resolve to a file, possibly a JAR URL
    }
    InputStream is = null;
    FileOutputStream os = null;
    try {
        // url exists but file cannot be read, so perhaps it's not a "file:" url (an example
        // would be a "jar:" url).  as a workaround, copy the file to a temp file and return
        // the temp file.
        String tempFilename = RandomStringUtils.randomAlphanumeric(20);
        File file = File.createTempFile(tempFilename, null);
        is = resource.getInputStream();
        os = new FileOutputStream(file);
        IOUtils.copy(is, os);
        return file;
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:com.netxforge.oss2.core.xml.CastorUtils.java

/**
 * Unmarshal a Castor XML configuration file.  Uses Java 5 generics for
 * return type and throws DataAccessExceptions.
 *
 * @param clazz the class representing the marshalled XML configuration file
 * @param resource the marshalled XML configuration file to unmarshal
 * @return Unmarshalled object representing XML file
 * @throws DataAccessException if the resource could not be opened or the
 *      underlying Castor/* w  ww  .ja v a2 s. c om*/
 *      Unmarshaller.unmarshal() call throws a MarshalException or
 *      ValidationException.  The underlying exception will be translated
 *      using MarshallingExceptionTranslator and will include information about
 *      the resource from its {@link Resource#toString() toString()} method.
 */
public static <T> T unmarshalWithTranslatedExceptions(Class<T> clazz, Resource resource,
        boolean preserveWhitespace) {
    // TODO It might be useful to add code to test for readability on real files; the code below is from DefaultManualProvisioningDao - dj@opennms.org 
    //        if (!importFile.canRead()) {
    //            throw new PermissionDeniedDataAccessException("Unable to read file "+importFile, null);
    //        }

    InputStream in;
    try {
        in = resource.getInputStream();
    } catch (IOException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR
                .translate("opening XML configuration file for resource '" + resource + "'", e);
    }

    try {
        InputSource source = new InputSource(in);
        try {
            source.setSystemId(resource.getURL().toString());
        } catch (Throwable t) {
            /*
             * resource.getURL() might throw an IOException
             * (or maybe a DataAccessException, since it's a
             * RuntimeException), indicating that the resource can't be
             * represented as a URL.  We don't really care so much--we'll
             * only lose the ability for Castor to include the resource URL
             * in error messages and for it to directly resolve relative
             * URLs (which we don't currently use), so we just ignore it.
             */
        }
        return unmarshal(clazz, source, preserveWhitespace);
    } catch (MarshalException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR.translate("unmarshalling XML file for resource '" + resource + "'",
                e);
    } catch (ValidationException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR.translate("unmarshalling XML file for resource '" + resource + "'",
                e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:de.ingrid.iplug.ckan.utils.ScriptEngine.java

/**
 * Execute the given scripts with the given parameters
 * @param scripts The script files/*from   w  w  w .ja v  a 2  s  .co  m*/
 * @param parameters The parameters
 * @param compile Boolean indicating whether to compile the script or not
 * @return Map with the absolute paths of the scripts as keys and the execution results as values
 * If an execution returns null, the result will not be added
 * @throws Exception
 */
public static Map<String, Object> execute(Resource[] scripts, Map<String, Object> parameters, boolean compile)
        throws Exception {

    Map<Integer, Bindings> bindings = new Hashtable<Integer, Bindings>();
    Map<String, Object> results = new Hashtable<String, Object>();

    for (Resource script : scripts) {
        // get the engine for the script
        javax.script.ScriptEngine engine = getEngine(script);

        // initialize/get the bindings
        if (!bindings.containsKey(engine.hashCode())) {
            Bindings newBindings = engine.createBindings();
            newBindings.putAll(parameters);
            bindings.put(engine.hashCode(), newBindings);
        }
        Bindings curBindings = bindings.get(engine.hashCode());

        // execute the script
        CompiledScript compiledScript = null;
        Object result = null;
        if (compile && (compiledScript = getCompiledScript(script)) != null) {
            result = compiledScript.eval(curBindings);
        } else {
            result = engine.eval(new InputStreamReader(script.getInputStream()), curBindings);
        }
        if (result != null) {
            results.put(script.getFilename(), result);
        }
    }
    return results;
}

From source file:org.jahia.modules.external.test.db.WriteableMappedDatabaseProvider.java

private static void extract(JahiaTemplatesPackage p, org.springframework.core.io.Resource r, File f)
        throws Exception {
    if ((r instanceof BundleResource && r.contentLength() == 0)
            || (!(r instanceof BundleResource) && r.getFile().isDirectory())) {
        f.mkdirs();/*from  ww w .  j a  v  a 2  s  .co m*/
        String path = r.getURI().getPath();
        for (org.springframework.core.io.Resource resource : p
                .getResources(path.substring(path.indexOf("/toursdb")))) {
            extract(p, resource, new File(f, resource.getFilename()));
        }
    } else {
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(f);
            IOUtils.copy(r.getInputStream(), output);
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
}