Java Code Examples for org.springframework.core.io.Resource#getInputStream()
The following examples show how to use
org.springframework.core.io.Resource#getInputStream() .
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: DefaultS3StoreImpl.java From spring-content with Apache License 2.0 | 6 votes |
@Transactional @Override public InputStream getContent(S entity) { if (entity == null) return null; Resource resource = this.getResource(entity); try { if (resource != null && resource.exists()) { return resource.getInputStream(); } } catch (IOException e) { logger.error(format("Unexpected error getting content for entity %s", entity), e); throw new StoreAccessException(format("Getting content for entity %s", entity), e); } return null; }
Example 2
Source File: PropertiesLoaderUtils.java From spring-analysis-note with MIT License | 6 votes |
/** * Fill the given properties from the given resource (in ISO-8859-1 encoding). * @param props the Properties instance to fill * @param resource the resource to load from * @throws IOException if loading failed */ public static void fillProperties(Properties props, Resource resource) throws IOException { InputStream is = resource.getInputStream(); try { String filename = resource.getFilename(); if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) { props.loadFromXML(is); } else { props.load(is); } } finally { is.close(); } }
Example 3
Source File: ResourceLoaderClassLoadHelper.java From spring-analysis-note with MIT License | 6 votes |
@Override @Nullable public InputStream getResourceAsStream(String name) { Assert.state(this.resourceLoader != null, "ResourceLoaderClassLoadHelper not initialized"); Resource resource = this.resourceLoader.getResource(name); if (resource.exists()) { try { return resource.getInputStream(); } catch (IOException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not load " + resource); } return null; } } else { return getClassLoader().getResourceAsStream(name); } }
Example 4
Source File: DockerServiceFactory.java From haven-platform with Apache License 2.0 | 6 votes |
private void initSsl(String addr, NettyRequestFactory factory) throws Exception { SSLContext sslc = SSLContext.getInstance("TLS"); if(!checkSsl) { log.debug("disable any SSL check on {} address", addr); sslc.init(null, new TrustManager[]{new SSLUtil.NullX509TrustManager()}, null); } else if(StringUtils.hasText(keystore)) { log.debug("use SSL trusted store {} on {} address", keystore, addr); final String alg = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory def = TrustManagerFactory.getInstance(alg); def.init((KeyStore)null);// initialize default list of trust managers Resource resource = resourceLoader.getResource(keystore); if(!resource.exists()) { log.warn("Specified JKS {} is not exists.", keystore); return; } KeyStore ks = KeyStore.getInstance("JKS"); try(InputStream is = resource.getInputStream()) { ks.load(is, storepass == null? new char[0] : storepass.toCharArray()); } TrustManagerFactory local = TrustManagerFactory.getInstance(alg); local.init(ks); TrustManager tm = SSLUtil.combineX509TrustManagers(local.getTrustManagers(), def.getTrustManagers()); sslc.init(null, new TrustManager[]{tm}, null); } factory.setSslContext(new JdkSslContext(sslc, true, ClientAuth.OPTIONAL)); }
Example 5
Source File: Utils.java From odo with Apache License 2.0 | 6 votes |
/** * Copies file from a resource to a local temp file * * @param sourceResource * @return Absolute filename of the temp file * @throws Exception */ public static File copyResourceToLocalFile(String sourceResource, String destFileName) throws Exception { try { Resource keystoreFile = new ClassPathResource(sourceResource); InputStream in = keystoreFile.getInputStream(); File outKeyStoreFile = new File(destFileName); FileOutputStream fop = new FileOutputStream(outKeyStoreFile); byte[] buf = new byte[512]; int num; while ((num = in.read(buf)) != -1) { fop.write(buf, 0, num); } fop.flush(); fop.close(); in.close(); return outKeyStoreFile; } catch (IOException ioe) { throw new Exception("Could not copy keystore file: " + ioe.getMessage()); } }
Example 6
Source File: PropertiesLoaderUtils.java From ace-cache with Apache License 2.0 | 6 votes |
/** * 载入多个文件, 文件路径使用Spring Resource格式. */ private Properties loadProperties(String... resourcesPaths) { Properties props = new Properties(); for (String location : resourcesPaths) { //logger.debug("Loading properties file from:" + location); InputStream is = null; try { Resource resource = resourceLoader.getResource(location); is = resource.getInputStream(); props.load(is); } catch (IOException ex) { logger.info("Could not load properties from path:" + location + ", " + ex.getMessage()); } finally { if(is!=null){ try { is.close(); } catch (IOException e) { } } } } return props; }
Example 7
Source File: StyleController.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@GetMapping("/css/bootstrap-{bootstrap-version}/{theme}") @ResponseStatus(OK) public ResponseEntity getThemeCss( @PathVariable("bootstrap-version") String bootstrapVersion, @PathVariable("theme") String theme, HttpServletResponse response) { response.setHeader("Content-Type", "text/css"); response.setHeader("Cache-Control", "max-age=31536000"); final String themeName = theme.endsWith(".css") ? theme : theme + ".css"; BootstrapVersion version = bootstrapVersion.equals("4") ? BOOTSTRAP_VERSION_4 : BOOTSTRAP_VERSION_3; Resource styleSheetResource = styleService.getThemeData(themeName, version); try (InputStream inputStream = styleSheetResource.getInputStream()) { IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { throw new GetThemeException(theme, e); } return new ResponseEntity(HttpStatus.OK); }
Example 8
Source File: ShortcutLoader.java From entando-core with GNU Lesser General Public License v3.0 | 6 votes |
private void loadShortcutObjects(String locationPattern, ServletContext servletContext) throws Exception { Resource[] resources = ApsWebApplicationUtils.getResources(locationPattern, servletContext); ShortcutDefDOM dom = null; for (int i = 0; i < resources.length; i++) { Resource resource = resources[i]; InputStream is = null; try { String path = resource.getFilename(); is = resource.getInputStream(); String xml = FileTextReader.getText(is); dom = new ShortcutDefDOM(xml, path); this.getManuSections().putAll(dom.getSectionMenus()); this.getShortcuts().putAll(dom.getShortcuts()); _logger.trace("Loaded Shortcut definition by file {}", path); } catch (Throwable t) { _logger.error("Error loading Shortcut definition by file {}", locationPattern, t); } finally { if (null != is) { is.close(); } } } }
Example 9
Source File: ResourceFinder.java From sakai with Educational Community License v2.0 | 5 votes |
public static InputStream[] getInputStreams(List<String> paths) { List<Resource> rs = makeResources(paths); InputStream[] streams = new InputStream[rs.size()]; for (int i = 0; i < rs.size(); i++) { Resource r = rs.get(i); try { streams[i] = r.getInputStream(); } catch (IOException e) { throw new RuntimeException("Failed to get inputstream for: " + r.getFilename(), e); } } return streams; }
Example 10
Source File: OAuth2ConfigResourceClientTest.java From spring-cloud-services-connector with Apache License 2.0 | 5 votes |
public String read(Resource resource) { try (BufferedReader buffer = new BufferedReader( new InputStreamReader(resource.getInputStream()))) { return buffer.lines().collect(Collectors.joining("\n")); } catch (IOException e) { throw new RuntimeException(e); } }
Example 11
Source File: LabelImageTensorflowOutputConverter.java From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 | 5 votes |
public LabelImageTensorflowOutputConverter(Resource labelsLocation, int alternativesLength) { this.alternativesLength = alternativesLength; try (InputStream is = labelsLocation.getInputStream()) { labels = IOUtils.readLines(is, Charset.forName("UTF-8")); objectMapper = new ObjectMapper(); Assert.notNull(labels, "Failed to initialize the labels list"); Assert.notNull(objectMapper, "Failed to initialize the objectMapper"); } catch (IOException e) { throw new RuntimeException("Failed to initialize the Vocabulary", e); } logger.info("Word Vocabulary Initialized"); }
Example 12
Source File: ResourceController.java From spring-cloud-config with Apache License 2.0 | 5 votes |
private synchronized byte[] binary(ServletWebRequest request, String name, String profile, String label, String path) throws IOException { name = Environment.normalize(name); label = Environment.normalize(label); Resource resource = this.resourceRepository.findOne(name, profile, label, path); if (checkNotModified(request, resource)) { // Content was not modified. Just return. return null; } // TODO: is this line needed for side effects? prepareEnvironment(this.environmentRepository.findOne(name, profile, label)); try (InputStream is = resource.getInputStream()) { return StreamUtils.copyToByteArray(is); } }
Example 13
Source File: BeansDtdResolver.java From blog_demos with Apache License 2.0 | 5 votes |
@Override public InputSource resolveEntity(String publicId, String systemId) throws IOException { if (logger.isTraceEnabled()) { logger.trace("Trying to resolve XML entity with public ID [" + publicId + "] and system ID [" + systemId + "]"); } if (systemId != null && systemId.endsWith(DTD_EXTENSION)) { int lastPathSeparator = systemId.lastIndexOf("/"); for (String DTD_NAME : DTD_NAMES) { int dtdNameStart = systemId.indexOf(DTD_NAME); if (dtdNameStart > lastPathSeparator) { String dtdFile = systemId.substring(dtdNameStart); if (logger.isTraceEnabled()) { logger.trace("Trying to locate [" + dtdFile + "] in Spring jar"); } try { Resource resource = new ClassPathResource(dtdFile, getClass()); InputSource source = new InputSource(resource.getInputStream()); source.setPublicId(publicId); source.setSystemId(systemId); if (logger.isDebugEnabled()) { logger.debug("Found beans DTD [" + systemId + "] in classpath: " + dtdFile); } return source; } catch (IOException ex) { if (logger.isDebugEnabled()) { logger.debug("Could not resolve beans DTD [" + systemId + "]: not found in class path", ex); } } } } } // Use the default behavior -> download from website or wherever. return null; }
Example 14
Source File: XsltView.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Get the XSLT {@link Source} for the XSLT template under the {@link #setUrl configured URL}. * @return the Source object */ protected Source getStylesheetSource() { String url = getUrl(); if (logger.isDebugEnabled()) { logger.debug("Loading XSLT stylesheet from '" + url + "'"); } try { Resource resource = getApplicationContext().getResource(url); return new StreamSource(resource.getInputStream(), resource.getURI().toASCIIString()); } catch (IOException ex) { throw new ApplicationContextException("Can't load XSLT stylesheet from '" + url + "'", ex); } }
Example 15
Source File: XMLToSchemaTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
@Before public void setUp() throws Exception { Resource testFileResource = new ClassPathResource("schemacomp/xml_to_schema_test.xml"); in = new BufferedInputStream(testFileResource.getInputStream()); xmlToSchema = new XMLToSchema(in); }
Example 16
Source File: SpringTemplateLoader.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public Reader getReader(Object templateSource, String encoding) throws IOException { Resource resource = (Resource) templateSource; try { return new InputStreamReader(resource.getInputStream(), encoding); } catch (IOException ex) { if (logger.isDebugEnabled()) { logger.debug("Could not find FreeMarker template: " + resource); } throw ex; } }
Example 17
Source File: ResourceFinder.java From sakai with Educational Community License v2.0 | 5 votes |
public static InputStream[] getInputStreams(List<String> paths) { List<Resource> rs = makeResources(paths); InputStream[] streams = new InputStream[rs.size()]; for (int i = 0; i < rs.size(); i++) { Resource r = rs.get(i); try { streams[i] = r.getInputStream(); } catch (IOException e) { throw new RuntimeException("Failed to get inputstream for: " + r.getFilename(), e); } } return streams; }
Example 18
Source File: ModelExtractor.java From tensorflow with Apache License 2.0 | 4 votes |
public byte[] getModel(Resource modelResource) { Assert.notNull(modelResource, "Not null model resource is required!"); try (InputStream is = modelResource.getInputStream(); InputStream bi = new BufferedInputStream(is)) { String[] archiveCompressor = detectArchiveAndCompressor(modelResource.getFilename()); String archive = archiveCompressor[0]; String compressor = archiveCompressor[1]; String fragment = modelResource.getURI().getFragment(); if (StringUtils.hasText(compressor)) { try (CompressorInputStream cis = new CompressorStreamFactory().createCompressorInputStream(compressor, bi)) { if (StringUtils.hasText(archive)) { try (ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(archive, cis)) { // Compressor with Archive return findInArchiveStream(fragment, ais); } } else { // Compressor only return StreamUtils.copyToByteArray(cis); } } } else if (StringUtils.hasText(archive)) { // Archive only try (ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(archive, bi)) { return findInArchiveStream(fragment, ais); } } else { // No compressor nor Archive return StreamUtils.copyToByteArray(bi); } } catch (Exception e) { throw new IllegalStateException("Failed to extract a model from: " + modelResource.getDescription(), e); } }
Example 19
Source File: PipeStreamsTest.java From airsonic-advanced with GNU General Public License v3.0 | 4 votes |
@Test public void testMonitoredResource() throws Exception { TransferStatus status = new TransferStatus(null); RateLimiter limit = RateLimiter.create(4.0); Path file = Paths.get(Resources.getResource("MEDIAS/piano.mp3").toURI()); Set<String> eventSet = new HashSet<>(); Resource r = new MonitoredResource(new FileSystemResource(file), limit, () -> status, s -> { if (!eventSet.add("statusClosed")) { fail("statusClosed multiple times"); } }, (i, s) -> { if (!eventSet.add("inputStreamOpened")) { fail("inputStream opened multiple times"); } }); assertThat(r.contentLength()).isEqualTo(FileUtil.size(file)); assertThat(eventSet).isEmpty(); // these are timed tests and a degree of variability is to be expected try (InputStream is = r.getInputStream()) { assertThat(eventSet).containsOnly("inputStreamOpened"); long start = System.currentTimeMillis(); is.skip(2); is.skip(2); is.skip(2); is.skip(2); is.skip(2); is.skip(2); // skips shouldn't be rate-limited assertThat(System.currentTimeMillis() - start).isLessThan(1000); assertThat(status.getBytesTransferred()).isEqualTo(0); assertThat(status.getBytesSkipped()).isEqualTo(12); assertThat(eventSet).containsOnly("inputStreamOpened"); byte[] b = new byte[2]; start = System.currentTimeMillis(); is.read(b); is.read(b); is.read(b); is.read(b); is.read(b); is.read(b); is.read(); is.read(); // reads should be rate-limited assertThat(System.currentTimeMillis() - start).isGreaterThan(2000); assertThat(status.getBytesTransferred()).isEqualTo(14); assertThat(status.getBytesSkipped()).isEqualTo(12); assertThat(eventSet).containsOnly("inputStreamOpened"); } assertThat(eventSet).containsOnly("inputStreamOpened", "statusClosed"); }
Example 20
Source File: SaxResourceUtils.java From spring-analysis-note with MIT License | 2 votes |
/** * Create a SAX {@code InputSource} from the given resource. * <p>Sets the system identifier to the resource's {@code URL}, if available. * @param resource the resource * @return the input source created from the resource * @throws IOException if an I/O exception occurs * @see InputSource#setSystemId(String) * @see #getSystemId(org.springframework.core.io.Resource) */ public static InputSource createInputSource(Resource resource) throws IOException { InputSource inputSource = new InputSource(resource.getInputStream()); inputSource.setSystemId(getSystemId(resource)); return inputSource; }