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:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * /*from w  ww.  jav a 2s  . c  o m*/
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

From source file:org.paxml.util.PaxmlUtils.java

public static String readResourceToString(String resUri, String encoding) {
    Resource res = readResource(resUri);
    InputStream in = null;/*  w  ww. j ava  2  s . c  o m*/
    try {
        in = res.getInputStream();
        return readStreamToString(in, encoding);
    } catch (Exception e) {
        throw new PaxmlRuntimeException("Cannot read uri: " + resUri, e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.glaf.core.entity.mybatis.MyBatisSessionFactory.java

protected static void reloadSessionFactory() {
    long start = System.currentTimeMillis();
    Set<String> mappers = new HashSet<String>();
    Configuration configuration = new Configuration();
    String path = SystemProperties.getConfigRootPath() + "/conf/mapper";
    try {/*w  ww .  j av  a2 s .co  m*/
        Map<String, byte[]> dataMap = getLibMappers();
        for (int i = 0; i < dataMap.size(); i++) {
            Set<Entry<String, byte[]>> entrySet = dataMap.entrySet();
            for (Entry<String, byte[]> entry : entrySet) {
                String key = entry.getKey();
                if (key.indexOf("/") != -1) {
                    key = key.substring(key.lastIndexOf("/"), key.length());
                }
                byte[] bytes = entry.getValue();
                String filename = path + "/" + key;
                try {
                    FileUtils.save(filename, bytes);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        List<String> list = getClassPathMappers();
        for (int i = 0; i < list.size(); i++) {
            Resource mapperLocation = new FileSystemResource(list.get(i));
            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                        configuration, mapperLocation.toString(), configuration.getSqlFragments());
                xmlMapperBuilder.parse();
                mappers.add(mapperLocation.getFilename());
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", ex);
            } finally {
                ErrorContext.instance().reset();
            }
        }

        File dir = new File(path);
        if (dir.exists() && dir.isDirectory()) {
            File contents[] = dir.listFiles();
            if (contents != null) {
                for (int i = 0; i < contents.length; i++) {
                    if (contents[i].isFile() && contents[i].getName().endsWith("Mapper.xml")) {
                        if (mappers.contains(contents[i].getName())) {
                            continue;
                        }
                        Resource mapperLocation = new FileSystemResource(contents[i]);
                        try {
                            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
                                    mapperLocation.getInputStream(), configuration, mapperLocation.toString(),
                                    configuration.getSqlFragments());
                            xmlMapperBuilder.parse();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            throw new NestedIOException(
                                    "Failed to parse mapping resource: '" + mapperLocation + "'", ex);
                        } finally {
                            ErrorContext.instance().reset();
                        }
                    }
                }
            }
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    long time = System.currentTimeMillis() - start;
    System.out.println("SessionFactory" + (time));
}

From source file:org.openbaton.vnfm.utils.Utils.java

public static String getUserdataFromJar() {
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = {};//from w w  w . ja  v  a 2  s .  c om
    StringBuilder script = new StringBuilder();
    try {
        resources = resolver.getResources("/scripts/*.sh");
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    for (Resource resource : resources) {
        InputStream in = null;
        InputStreamReader is = null;
        BufferedReader br = null;
        try {
            in = resource.getInputStream();
            is = new InputStreamReader(in);
            br = new BufferedReader(is);
            String line = br.readLine();
            while (line != null) {
                script.append(line).append("\n");
                line = br.readLine();
            }
            script.append("\n");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                br.close();
                is.close();
                in.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
    return script.toString();
}

From source file:org.opennms.mock.snmp.MockSnmpAgent.java

public static MockSnmpAgent createAgentAndRun(Resource moFile, String bindAddress) throws InterruptedException {
    try {//ww w  .j  a  v  a2s.  c  o m
        if (moFile.getInputStream() == null) {
            throw new IllegalArgumentException(
                    "could not get InputStream mock object resource; does it exist?  Resource: " + moFile);
        }
    } catch (IOException e) {
        throw new RuntimeException("Got IOException while checking for existence of mock object file: " + e, e);
    }

    MockSnmpAgent agent = new MockSnmpAgent(new File("/dev/null"), new File("/dev/null"), moFile, bindAddress);
    Thread thread = new Thread(agent);
    thread.start();

    try {
        while (!agent.isRunning() && thread.isAlive()) {
            Thread.sleep(10);
        }
    } catch (InterruptedException e) {
        agent.shutDownAndWait();
        throw e;
    }

    if (!thread.isAlive()) {
        agent.m_running = false;
        agent.m_stopped = true;
        throw new IllegalStateException("agent failed to start--check logs");
    }

    return agent;
}

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

public static <T> T unmarshal(final Class<T> clazz, final Resource resource, final boolean validate) {
    try {//from   ww  w.j av a2s.  c  om
        return unmarshal(clazz, new InputSource(resource.getInputStream()), null, validate);
    } catch (final IOException e) {
        throw EXCEPTION_TRANSLATOR.translate("getting a configuration resource from spring", e);
    }
}

From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java

private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword)
        throws GeneralSecurityException, IOException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream inputStream = trustFile.getInputStream()) {
        trustStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
    }/*from  ww  w . j  av  a2  s.  co m*/

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return trustManagerFactory;
}

From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java

private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile, String storePassword)
        throws GeneralSecurityException, IOException {

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream inputStream = keystoreFile.getInputStream()) {
        keyStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
    }/* www  . j  av  a2  s . c  om*/

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,
            StringUtils.hasText(storePassword) ? storePassword.toCharArray() : new char[0]);

    return keyManagerFactory;
}

From source file:hm.binkley.util.XProperties.java

/**
 * Creates a new {@code XProperties} for the given <var>absolutePath</var>
 * found in the classpath./*from   ww w  .j  av a  2  s .  c o  m*/
 *
 * @param absolutePath the absolute path to search on the classpath, never
 * missing
 *
 * @throws IOException if <var>absolutePath</var> cannot be loaded
 */
@Nonnull
public static XProperties from(@Nonnull @NonNull final String absolutePath) throws IOException {
    final Resource resource = new PathMatchingResourcePatternResolver().getResource(absolutePath);
    try (final InputStream in = resource.getInputStream()) {
        final XProperties xprops = new XProperties();
        xprops.included.add(resource.getURI());
        xprops.load(in);
        return xprops;
    }
}

From source file:org.paxml.util.PaxmlUtils.java

/**
 * Load properties from a resource file and more text if given.
 * //from w  w  w  .j ava 2s. c  o  m
 * @param props
 *            the properties file to load into
 * @param res
 *            a resource to load from, null to ignore
 * @param moreText
 *            a text to load from, null to ignore
 * @return the input properties
 */
public static Properties loadProperties(Properties props, Resource res, String moreText) {

    InputStream[] ins = new InputStream[2];
    if (res != null) {
        try {
            ins[0] = res.getInputStream();
        } catch (IOException e) {
            throw new PaxmlRuntimeException("Cannot load properties from resource " + res, e);
        }
    }
    if (moreText != null) {
        try {
            ins[1] = new ByteArrayInputStream(moreText.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new PaxmlRuntimeException(e);
        }
    }
    return loadProperties(props, true, ins);

}