Deprecated as of 4.3.13, in favor of selective use of ClassPathResource.ClassPathResource(String, ClassLoader) vs ClassPathResource.ClassPathResource(String, Class)
ClassPathResource cpr = new ClassPathResource("folder/file.xsd"); InputStream is = cpr.getInputStream();
ClassPathResource resource = new ClassPathResource( "app.properties" ); p = new Properties(); InputStream inputStream = null; try { inputStream = resource.getInputStream(); cloudProperties.load( inputStream ); } catch ( IOException e ) { LOGGER.error( e.getMessage(), e ); } finally { Closeables.closeQuietly( inputStream ); }
public List<UrlGroup> getUrlGroups() throws IOException { ClassPathResource resource = new ClassPathResource("performance-url-groups.yml"); Yaml yaml = new Yaml(); List<Map<String,Object>> load = (List<Map<String, Object>>) yaml.load(resource.getInputStream()); return load.stream().map(map -> UrlGroup.from(map)).collect(Collectors.toList()); }
public static String readFileFromClasspath(String url) { StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { ClassPathResource classPathResource = new ClassPathResource(url); InputStreamReader inputStreamReader = new InputStreamReader(classPathResource.getInputStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; String lineSeparator = System.getProperty("line.separator"); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append(lineSeparator); } } catch (Exception e) { logger.debug(String.format("Failed to load file from url: %s: %s", url, e.getMessage())); return null; } finally { if (bufferedReader != null) try { bufferedReader.close(); } catch (IOException e) { logger.debug(String.format("Unable to close buffered reader.. %s", e.getMessage())); } } return stringBuilder.toString(); }
BufferedImage red = ImageIO.read(redResource.getInputStream());
private String fetchMacro(String name) throws Exception { ClassPathResource resource = new ClassPathResource("test.ftl", getClass()); assertTrue(resource.exists()); String all = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream())); all = all.replace("\r\n", "\n"); String[] macros = StringUtils.delimitedListToStringArray(all, "\n\n"); for (String macro : macros) { if (macro.startsWith(name)) { return macro.substring(macro.indexOf("\n")).trim(); } } return null; }
private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) { try { resource.getInputStream(); fail("FileNotFoundException expected for resource: " + resource); } catch (IOException ex) { assertThat(ex, instanceOf(FileNotFoundException.class)); assertThat(ex.getMessage(), containsString(FQ_RESOURCE_PATH)); } }
protected InputStream fixture(String path) throws IOException { return new ClassPathResource(Paths.get("fixtures", path).toString()).getInputStream(); }
private SqlSessionFactory buildSqlSessionFactory() throws IOException { SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); Configuration baseConfiguration = new XMLConfigBuilder(configLocation.getInputStream()).parse(); String ibatisConfigXmlLocation = databaseStrategy.getIbatisConfigXmlLocation(); if (isNotBlank(ibatisConfigXmlLocation)) { XMLConfigBuilder builder = new XMLConfigBuilder(new ClassPathResource(ibatisConfigXmlLocation).getInputStream()); // hacky way to "inject" a previous configuration Field configurationField = ReflectionUtils.findField(XMLConfigBuilder.class, "configuration"); ReflectionUtils.makeAccessible(configurationField); ReflectionUtils.setField(configurationField, builder, baseConfiguration); baseConfiguration = builder.parse(); } baseConfiguration.setEnvironment(new Environment(getClass().getSimpleName(), new SpringManagedTransactionFactory(), this.dataSource)); return factoryBuilder.build(baseConfiguration); }
@Test public void shouldParseChangesWithLotsOfFilesWithoutError() throws Exception { final StringWriter writer = new StringWriter(); IOUtils.copy(new ClassPathResource("/BIG_P4_OUTPUT.txt").getInputStream(), writer, Charset.defaultCharset()); String output = writer.toString(); Modification modification = parser.modificationFromDescription(output, new ConsoleResult(0, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>())); assertThat(modification.getModifiedFiles().size(), is(1304)); assertThat(modification.getModifiedFiles().get(0).getFileName(), is("Internal Projects/ABC/Customers3/ABC/RIP/SomeProject/data/main/config/lib/java/AdvJDBCColumnHandler.jar")); }
@Override public InputStream getClasspathResource(String name) { try { ClassPathResource resource = lookupResourceOnClassPath(name); if (resource != null && resource.exists()) { InputStream assetFile = resource.getInputStream(); BufferedInputStream bufferedStream = new BufferedInputStream(assetFile); // Wrapping the buffered input stream with a globally shared stream allows us to // vary the way the file names are generated on the file system. // This benefits us (mainly in our demo site but their could be other uses) when we // have assets that are shared across sites that we also need to resize. GloballySharedInputStream globallySharedStream = new GloballySharedInputStream(bufferedStream); globallySharedStream.mark(0); return globallySharedStream; } else { return null; } } catch (Exception e) { LOG.error("Error getting resource from classpath", e); } return null; }
public XmlNode parse(String location) throws IOException { ClassPathResource resource = new ClassPathResource(location); this.parser = new XmlParser(resource.getInputStream()); return this.parser.parse(); }
private InputStream source(String filename) throws IOException { return new ClassPathResource(FileUtil.fileseparator() + "data" + FileUtil.fileseparator() + filename).getInputStream(); }
private InputStream source(String filename) throws IOException { return new ClassPathResource(FileUtil.fileseparator() + "data" + FileUtil.fileseparator() + filename).getInputStream(); }
new ClassPathResource(JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE).getInputStream(), envScriptPath, StandardCopyOption.REPLACE_EXISTING
protected JSONObject readJsonFrom(String path) { try { ClassPathResource resource = new ClassPathResource(path); try (InputStream stream = resource.getInputStream()) { String json = StreamUtils.copyToString(stream, Charset.forName("UTF-8")); String placeholder = ""; if (this instanceof AbstractInitializrControllerIntegrationTests) { placeholder = ((AbstractInitializrControllerIntegrationTests) this).host; } if (this instanceof AbstractFullStackInitializrIntegrationTests) { AbstractFullStackInitializrIntegrationTests test = (AbstractFullStackInitializrIntegrationTests) this; placeholder = test.host + ":" + test.port; } // Let's parse the port as it is random // TODO: put the port back somehow so it appears in stubs String content = json.replaceAll("@host@", placeholder); return new JSONObject(content); } } catch (Exception ex) { throw new IllegalStateException("Cannot read JSON from path=" + path); } }
private PublicKey decodePublicKey() throws Exception { InputStream stream = new ClassPathResource("META-INF/keys/sftp_rsa.pub").getInputStream(); byte[] keyBytes = StreamUtils.copyToByteArray(stream); // strip any newline chars while (keyBytes[keyBytes.length - 1] == 0x0a || keyBytes[keyBytes.length - 1] == 0x0d) { keyBytes = Arrays.copyOf(keyBytes, keyBytes.length - 1); } byte[] decodeBuffer = Base64Utils.decode(keyBytes); ByteBuffer bb = ByteBuffer.wrap(decodeBuffer); int len = bb.getInt(); byte[] type = new byte[len]; bb.get(type); if ("ssh-rsa".equals(new String(type))) { BigInteger e = decodeBigInt(bb); BigInteger m = decodeBigInt(bb); RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e); return KeyFactory.getInstance("RSA").generatePublic(spec); } else { throw new IllegalArgumentException("Only supports RSA"); } }
@Test // SPR-15041 public void applicationOctetStreamDefaultContentType() throws Exception { MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); ClassPathResource body = Mockito.mock(ClassPathResource.class); BDDMockito.given(body.getFilename()).willReturn("spring.dat"); BDDMockito.given(body.contentLength()).willReturn(12L); BDDMockito.given(body.getInputStream()).willReturn(new ByteArrayInputStream("Spring Framework".getBytes())); HttpRange range = HttpRange.createByteRange(0, 5); ResourceRegion resourceRegion = range.toResourceRegion(body); converter.write(Collections.singletonList(resourceRegion), null, outputMessage); assertThat(outputMessage.getHeaders().getContentType(), is(MediaType.APPLICATION_OCTET_STREAM)); assertThat(outputMessage.getHeaders().getFirst(HttpHeaders.CONTENT_RANGE), is("bytes 0-5/12")); assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), is("Spring")); }
Scanner scanner = new Scanner(resource.getInputStream()); String line = scanner.nextLine(); scanner.close();
@Test public void testConvertStreamSourceToDocument() throws Exception { ClassPathResource resource = new ClassPathResource("org/springframework/integration/xml/customSource.data"); StreamSource source = new StreamSource(resource.getInputStream()); Document doc = converter.convertToDocument(source); assertThat(XmlTestUtil.docToString(doc)).isXmlEqualTo(TEST_DOCUMENT_AS_STRING); }