@GetMapping("/file-resource") public String fileResource() { try { return "get file resource success. content: " + StreamUtils.copyToString( file.getInputStream(), Charset.forName(CharEncoding.UTF_8)); } catch (Exception e) { e.printStackTrace(); return "get resource fail: " + e.getMessage(); } }
@Override public MultiValueMap<String, String> read(@Nullable Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { MediaType contentType = inputMessage.getHeaders().getContentType(); Charset charset = (contentType != null && contentType.getCharset() != null ? contentType.getCharset() : this.charset); String body = StreamUtils.copyToString(inputMessage.getBody(), charset); String[] pairs = StringUtils.tokenizeToStringArray(body, "&"); MultiValueMap<String, String> result = new LinkedMultiValueMap<>(pairs.length); for (String pair : pairs) { int idx = pair.indexOf('='); if (idx == -1) { result.add(URLDecoder.decode(pair, charset.name()), null); } else { String name = URLDecoder.decode(pair.substring(0, idx), charset.name()); String value = URLDecoder.decode(pair.substring(idx + 1), charset.name()); result.add(name, value); } } return result; }
@Override public void customize(InitializrMetadata metadata) { log.info("Loading initializr metadata from " + this.resource); try { String content = StreamUtils.copyToString(this.resource.getInputStream(), UTF_8); ObjectMapper objectMapper = new ObjectMapper(); InitializrMetadata anotherMetadata = objectMapper.readValue(content, InitializrMetadata.class); metadata.merge(anotherMetadata); } catch (Exception ex) { throw new IllegalStateException("Cannot merge", ex); } }
/** * Return the textual content of the resource at the specified location. * @param location a resource location * @return the content of the resource */ @Cacheable("initializr.project-resources") public String getTextResource(String location) { try (InputStream stream = getInputStream(location)) { return StreamUtils.copyToString(stream, UTF_8); } catch (IOException ex) { throw new IllegalStateException("Cannot get resource", ex); } }
@Override public MultiValueMap<String, String> read(@Nullable Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { MediaType contentType = inputMessage.getHeaders().getContentType(); Charset charset = (contentType != null && contentType.getCharset() != null ? contentType.getCharset() : this.charset); String body = StreamUtils.copyToString(inputMessage.getBody(), charset); String[] pairs = StringUtils.tokenizeToStringArray(body, "&"); MultiValueMap<String, String> result = new LinkedMultiValueMap<>(pairs.length); for (String pair : pairs) { int idx = pair.indexOf('='); if (idx == -1) { result.add(URLDecoder.decode(pair, charset.name()), null); } else { String name = URLDecoder.decode(pair.substring(0, idx), charset.name()); String value = URLDecoder.decode(pair.substring(idx + 1), charset.name()); result.add(name, value); } } return result; }
@Override public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { try { String banner = StreamUtils.copyToString(this.resource.getInputStream(), environment.getProperty("spring.banner.charset", Charset.class, StandardCharsets.UTF_8)); for (PropertyResolver resolver : getPropertyResolvers(environment, sourceClass)) { banner = resolver.resolvePlaceholders(banner); } out.println(banner); } catch (Exception ex) { logger.warn("Banner not printable: " + this.resource + " (" + ex.getClass() + ": '" + ex.getMessage() + "')", ex); } }
@Override protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException { Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType()); return StreamUtils.copyToString(inputMessage.getBody(), charset); }
public String getContentString() throws MessagingException, IOException { return StreamUtils.copyToString(mimeMessage.getDataHandler().getInputStream(), Charset.forName("UTF-8")); }
private void initReadyToInstallDependencies() { DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine("js"); try { Resource[] resources = new PathMatchingResourcePatternResolver().getResources(installScriptPath); List<SimpleDependencyInstaller> installers = new ArrayList<>(); for (Resource resource : resources) { String script = StreamUtils.copyToString(resource.getInputStream(), Charset.forName("utf-8")); SimpleDependencyInstaller installer = new SimpleDependencyInstaller(); engine.compile("__tmp", script); Map<String, Object> context = getScriptContext(); context.put("dependency", installer); engine.execute("__tmp", context).getIfSuccess(); installers.add(installer); } readyToInstall = installers; } catch (Exception e) { throw new RuntimeException(e); } finally { engine.remove("__tmp"); } }
@Test public void copyToString() throws Exception { Charset charset = Charset.defaultCharset(); InputStream inputStream = spy(new ByteArrayInputStream(string.getBytes(charset))); String actual = StreamUtils.copyToString(inputStream, charset); assertThat(actual, equalTo(string)); verify(inputStream, never()).close(); }
public SourceCodeAssert equalsTo(Resource expected) { try (InputStream stream = expected.getInputStream()) { String expectedContent = StreamUtils.copyToString(stream, Charset.forName("UTF-8")); assertThat(this.content).describedAs("Content for %s", this.name) .isEqualTo(expectedContent.replaceAll("\r\n", "\n")); } catch (IOException ex) { throw new IllegalStateException("Cannot read file", ex); } return this; }
@Override protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException { Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType()); return StreamUtils.copyToString(inputMessage.getBody(), charset); }
/** * Return a {@link PomAssert} for this project. * @return a POM assert */ public PomAssert pomAssert() { try { return new PomAssert(StreamUtils.copyToString( new FileInputStream(file("pom.xml")), Charset.forName("UTF-8"))); } catch (IOException ex) { throw new IllegalArgumentException("Cannot resolve pom.xml", ex); } }
/** * Return a {@link GradleBuildAssert} for this project. * @return a gradle assert */ public GradleBuildAssert gradleBuildAssert() { try { return new GradleBuildAssert(StreamUtils.copyToString( new FileInputStream(file("build.gradle")), Charset.forName("UTF-8"))); } catch (IOException ex) { throw new IllegalArgumentException("Cannot resolve build.gradle", ex); } }
@Test public void setContentAndGetInputStream() throws IOException { byte[] bytes = "body".getBytes(Charset.defaultCharset()); request.setContent(bytes); assertEquals(bytes.length, request.getContentLength()); assertEquals("body", StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset())); request.setContent(bytes); assertEquals(bytes.length, request.getContentLength()); assertEquals("body", StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset())); }
/** * Return a {@link GradleSettingsAssert} for this project. * @return A gradle settings assert */ public GradleSettingsAssert gradleSettingsAssert() { try { return new GradleSettingsAssert( StreamUtils.copyToString(new FileInputStream(file("settings.gradle")), Charset.forName("UTF-8"))); } catch (IOException ex) { throw new IllegalArgumentException("Cannot resolve settings.gradle", ex); } }
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); } }
@Test // SPR-14040 public void shouldNotCloseConnectionWhenResponseClosed() throws Exception { TestByteArrayInputStream is = new TestByteArrayInputStream("Spring".getBytes(StandardCharsets.UTF_8)); given(this.connection.getErrorStream()).willReturn(null); given(this.connection.getInputStream()).willReturn(is); InputStream responseStream = this.response.getBody(); assertThat(StreamUtils.copyToString(responseStream, StandardCharsets.UTF_8), is("Spring")); this.response.close(); assertTrue(is.isClosed()); verify(this.connection, never()).disconnect(); }
/** * Return a {@link SourceCodeAssert} for the specified source code. * @param sourceCodePath the source code path * @return a source assert */ public SourceCodeAssert sourceCodeAssert(String sourceCodePath) { hasFile(sourceCodePath); try { return new SourceCodeAssert(sourceCodePath, StreamUtils.copyToString( new FileInputStream(file(sourceCodePath)), Charset.forName("UTF-8"))); } catch (IOException ex) { throw new IllegalArgumentException("Cannot resolve path: " + sourceCodePath, ex); } }
@Test // SPR-16604 public void bodyAvailableAfterHasErrorForUnknownStatusCode() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); TestByteArrayInputStream body = new TestByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)); given(response.getRawStatusCode()).willReturn(999); given(response.getStatusText()).willReturn("Custom status code"); given(response.getHeaders()).willReturn(headers); given(response.getBody()).willReturn(body); assertFalse(handler.hasError(response)); assertFalse(body.isClosed()); assertEquals("Hello World", StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8)); }