private void doTest(AnnotationConfigEmbeddedWebApplicationContext context, String resourcePath) throws Exception { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); ClientHttpRequest request = clientHttpRequestFactory.createRequest( new URI("http://localhost:" + context.getEmbeddedServletContainer().getPort() + resourcePath), HttpMethod.GET); ClientHttpResponse response = request.execute(); try { String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); assertThat(actual).isEqualTo("Hello World"); } finally { response.close(); } }
@Test public void shouldSerialize() throws Exception { Rule rule = Rule.builder().path("secret/*") .capabilities("create", "read", "update") .allowedParameter("ttl", "1h", "2h").deniedParameter("password").build(); Rule another = Rule.builder().path("secret/foo") .capabilities("create", "read", "update", "delete", "list") .minWrappingTtl(Duration.ofMinutes(1)) .maxWrappingTtl(Duration.ofHours(1)).allowedParameter("ttl", "1h", "2h") .deniedParameter("password").build(); Policy policy = Policy.of(rule, another); try (InputStream is = new ClassPathResource("policy.json").getInputStream()) { String expected = StreamUtils.copyToString(is, StandardCharsets.UTF_8); JSONAssert.assertEquals(expected, objectMapper.writeValueAsString(policy), JSONCompareMode.STRICT); } }
private void updateResponse(String requestURI, ContentCachingResponseWrapper responseWrapper) throws IOException { try { HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse(); byte[] body = responseWrapper.getContentAsByteArray(); ServletOutputStream outputStream = rawResponse.getOutputStream(); if (rawResponse.isCommitted()) { if (body.length > 0) { StreamUtils.copy(body, outputStream); } } else { if (body.length > 0) { rawResponse.setContentLength(body.length); StreamUtils.copy(body, rawResponse.getOutputStream()); } } finishResponse(outputStream, body); } catch (Exception ex) { logger.error("请求地址为" + requestURI + "的连接返回报文失败,原因是{}", ex.getMessage()); } }
@Override public void write(InputStream inputStream, String destination) throws IOException { String[] tokens = getBucketAndObjectFromPath(destination); Assert.state(tokens.length == 2, "Can only write to files, not buckets."); BlobInfo gcsBlobInfo = BlobInfo.newBuilder(BlobId.of(tokens[0], tokens[1])).build(); try (InputStream is = inputStream) { try (WriteChannel channel = this.gcs.writer(gcsBlobInfo)) { channel.write(ByteBuffer.wrap(StreamUtils.copyToByteArray(is))); } } }
@Test @SuppressWarnings("unchecked") public void testMustasche() throws IOException { Yaml yaml = new Yaml(); Map model = (Map) yaml.load(valuesResource.getInputStream()); String templateAsString = StreamUtils.copyToString(nestedMapResource.getInputStream(), Charset.defaultCharset()); Template mustacheTemplate = Mustache.compiler().compile(templateAsString); String resolvedYml = mustacheTemplate.execute(model); Map map = (Map) yaml.load(resolvedYml); logger.info("Resolved yml = " + resolvedYml); assertThat(map).containsKeys("apiVersion", "deployment"); Map deploymentMap = (Map) map.get("deployment"); assertThat(deploymentMap).contains(entry("name", "time")) .contains(entry("count", 10)); Map applicationProperties = (Map) deploymentMap.get("applicationProperties"); assertThat(applicationProperties).contains(entry("log.level", "DEBUG"), entry("server.port", 8089)); Map deploymentProperties = (Map) deploymentMap.get("deploymentProperties"); assertThat(deploymentProperties).contains(entry("app.time.producer.partitionKeyExpression", "payload"), entry("app.log.spring.cloud.stream.bindings.input.consumer.maxAttempts", 5)); }
@Test public void testInvalidVersions() throws IOException { UploadRequest uploadRequest = new UploadRequest(); uploadRequest.setRepoName("local"); uploadRequest.setName("log"); uploadRequest.setVersion("abc"); uploadRequest.setExtension("zip"); Resource resource = new ClassPathResource("/org/springframework/cloud/skipper/server/service/log-9.9.9.zip"); assertThat(resource.exists()).isTrue(); byte[] originalPackageBytes = StreamUtils.copyToByteArray(resource.getInputStream()); assertThat(originalPackageBytes).isNotEmpty(); Assert.isTrue(originalPackageBytes.length != 0, "PackageServiceTests.Assert.isTrue: Package file as bytes must not be empty"); assertInvalidPackageVersion(uploadRequest); uploadRequest.setVersion("1abc"); assertInvalidPackageVersion(uploadRequest); uploadRequest.setVersion("1.abc.2"); assertInvalidPackageVersion(uploadRequest); uploadRequest.setVersion("a.b.c"); assertInvalidPackageVersion(uploadRequest); uploadRequest.setVersion("a.b.c.2"); assertInvalidPackageVersion(uploadRequest); }
private void writeForm(MultiValueMap<String, String> form, MediaType contentType, HttpOutputMessage outputMessage) throws IOException { Charset charset; if (contentType != null) { outputMessage.getHeaders().setContentType(contentType); charset = contentType.getCharset() != null ? contentType.getCharset() : this.defaultCharset; } else { outputMessage.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED); charset = this.defaultCharset; } StringBuilder builder = new StringBuilder(); buildByNames(form, charset, builder); final byte[] bytes = builder.toString().getBytes(charset.name()); outputMessage.getHeaders().setContentLength(bytes.length); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(bytes, outputStream)); } else { StreamUtils.copy(bytes, outputMessage.getBody()); } }
@Override protected void writeInternal(Resource resource, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { InputStream in = resource.getInputStream(); try { StreamUtils.copy(in, outputMessage.getBody()); } finally { try { in.close(); } catch (IOException ex) { } } outputMessage.getBody().flush(); }
@Override protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException { if (this.body == null) { if (this.outputStreaming) { int contentLength = (int) headers.getContentLength(); if (contentLength >= 0) { this.connection.setFixedLengthStreamingMode(contentLength); } else { this.connection.setChunkedStreamingMode(this.chunkSize); } } writeHeaders(headers); this.connection.connect(); this.body = this.connection.getOutputStream(); } return StreamUtils.nonClosing(this.body); }
@Override protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException { if (this.body == null) { if(this.outputStreaming) { int contentLength = (int) headers.getContentLength(); if (contentLength >= 0) { this.connection.setFixedLengthStreamingMode(contentLength); } else { this.connection.setChunkedStreamingMode(this.chunkSize); } } writeHeaders(headers); this.connection.connect(); this.body = this.connection.getOutputStream(); } return StreamUtils.nonClosing(this.body); }
@Override public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException { if (iterator.hasNext()) { ClientHttpRequestInterceptor nextInterceptor = iterator.next(); return nextInterceptor.intercept(request, body, this); } else { ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod()); delegate.getHeaders().putAll(request.getHeaders()); if (body.length > 0) { StreamUtils.copy(body, delegate.getBody()); } return delegate.execute(); } }
public static Checksums calculate(InputStream content) throws IOException { Assert.notNull(content, "Content must not be null"); try { DigestInputStream sha1 = new DigestInputStream(content, MessageDigest.getInstance("SHA-1")); DigestInputStream md5 = new DigestInputStream(sha1, MessageDigest.getInstance("MD5")); StreamUtils.drain(md5); return new Checksums(getDigestHex(sha1), getDigestHex(md5)); } catch (Exception ex) { throw new RuntimeException(ex); } finally { content.close(); } }
String fetchConfigXml(AddOnToIndex addOnToIndex, AddOnVersion addOnVersion) throws IOException { logger.info("fetching config.xml from " + addOnVersion.getDownloadUri()); Resource resource = restTemplateBuilder.build().getForObject(addOnVersion.getDownloadUri(), Resource.class); try ( InputStream inputStream = resource.getInputStream(); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputStream)) ) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.getName().equals("config.xml")) { return StreamUtils.copyToString(zis, Charset.defaultCharset()); } } } return null; }
@RequestMapping(method = RequestMethod.GET, value = "/api/v1/addon/{uid}/{version}/download") public void downloadWithCorrectName(@PathVariable("uid") String addonUid, @PathVariable("version") String version, HttpServletResponse response) throws Exception { AddOnInfoAndVersions addOn = index.getByUid(addonUid); if (addOn == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Optional<AddOnVersion> addOnVersion = addOn.getVersion(new Version(version)); if (!addOnVersion.isPresent()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (addOnVersion.get().getRenameTo() == null || !addOnVersion.get().getDownloadUri().startsWith("http://mavenrepo.openmrs.org/nexus/")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } Resource resource = restTemplateBuilder.build().getForObject(addOnVersion.get().getDownloadUri(), Resource.class); response.setHeader("Content-Disposition", "inline;filename=" + addOnVersion.get().getRenameTo()); StreamUtils.copy(resource.getInputStream(), response.getOutputStream()); }
private void buildRequestBody(PactDslRequestWithPath pactRequest) throws IOException { final RequestContext context = RequestContext.getCurrentContext(); String requestBody = null; InputStream in = (InputStream) context.get("requestEntity"); if (in == null) { in = context.getRequest().getInputStream(); } if (in != null) { String encoding = context.getRequest().getCharacterEncoding(); requestBody = StreamUtils.copyToString(in, Charset.forName(encoding != null ? encoding : "UTF-8")); } if (requestBody != null && requestBody.length() > 0) { pactRequest.body(requestBody); } }
public Object run() { try { RequestContext context = getCurrentContext(); InputStream in = (InputStream) context.get("requestEntity"); if (in == null) { in = context.getRequest().getInputStream(); } String body = StreamUtils.copyToString(in, Charset.forName("UTF-8")); // body = "request body modified via set('requestEntity'): "+ body; body = body.toUpperCase(); context.set("requestEntity", new ByteArrayInputStream(body.getBytes("UTF-8"))); } catch (IOException e) { rethrowRuntimeException(e); } return null; }
@BeforeClass public static void beforeClass() throws Exception { elasticsearchServer = new EmbeddedElasticsearchServer(); elasticsearchTemplate = new ElasticsearchTemplate(elasticsearchServer.getClient()); elasticsearchTemplate.deleteIndex(INDEX_NAME); String mappings = StreamUtils.copyToString( ODataIntegrationTest.class.getResourceAsStream("mappings.json"), StandardCharsets.UTF_8); createIndex(INDEX_NAME, mappings); waitForGreenStatus(INDEX_NAME); indexDocument("entityId1", "entity1-source.json"); indexDocument("entityId2", "entity2-source.json"); indexDocument("entityId3", "entity3-source.json"); refresh(INDEX_NAME); }
private static String httpRequest(String url, Object data, String method, int timeoutMilliseconds/*毫秒*/, int retryTimes) { Preconditions.checkArgument(retryTimes <= 10 && retryTimes >= 0, "retryTimes should between 0(include) and 10(include)"); method = StringUtils.upperCase(method); Preconditions.checkArgument(HttpMethod.resolve(method) != null, "http request method error"); try { HttpRequest request = getHttpRequest(url, data, method); long start = System.currentTimeMillis(); String uuid = StringUtils.left(UUID.randomUUID().toString(), 13); logger.info("UUID:{}, Request URL:{} , method:{}, Request data:{}", uuid, url, method, JsonUtil.writeValueQuite(data)); request.setNumberOfRetries(retryTimes); request.setConnectTimeout(timeoutMilliseconds); request.setLoggingEnabled(LOGGING_ENABLED); HttpResponse response = request.execute(); response.setLoggingEnabled(LOGGING_ENABLED); InputStream in = new BufferedInputStream(response.getContent()); String res = StreamUtils.copyToString(in, Charsets.UTF_8); logger.info("UUID:{}, Request cost [{}ms], Response data:{}", uuid, (System.currentTimeMillis() - start), res); return res; } catch (IOException e) { logger.warn("Http request error", e); } return StringUtils.EMPTY; }
private String getOutput() throws Exception { Future<String> future = Executors.newSingleThreadExecutor() .submit(new Callable<String>() { @Override public String call() throws Exception { Resource[] resources = getResourcesWithContent(); while (resources.length == 0) { Thread.sleep(200); resources = getResourcesWithContent(); } StringBuilder builder = new StringBuilder(); for (Resource resource : resources) { builder.append(new String(StreamUtils .copyToByteArray(resource.getInputStream()))); } return builder.toString(); } }); return future.get(30, TimeUnit.SECONDS); }
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"); } }
@Override public String saveStaticFile(InputStream fileStream, String fileName) throws IOException { //文件后缀 String suffix = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : ""; //以日期划分目录 String filePath = DateFormatter.toString(new Date(), "yyyyMMdd"); //创建目录 new File(getStaticFilePath() + "/" + filePath).mkdirs(); // 存储的文件名 String realFileName = System.nanoTime() + suffix; String fileAbsName = getStaticFilePath() + "/" + filePath + "/" + realFileName; try (FileOutputStream out = new FileOutputStream(fileAbsName)) { StreamUtils.copy(fileStream, out); } //响应上传成功的资源信息 return getStaticLocation() + filePath + "/" + realFileName; }
/** * 读取流程资源 * * @param processDefinitionId 流程定义ID * @param resourceName 资源名称 */ @GetMapping(value = "/{processDefinitionId}/resource/{resourceName}") public void readResource(@PathVariable String processDefinitionId , @PathVariable String resourceName, HttpServletResponse response) throws Exception { ProcessDefinitionQuery pdq = repositoryService.createProcessDefinitionQuery(); ProcessDefinition pd = pdq.processDefinitionId(processDefinitionId).singleResult(); // 通过接口读取 InputStream resourceAsStream = repositoryService.getResourceAsStream(pd.getDeploymentId(), resourceName); StreamUtils.copy(resourceAsStream, response.getOutputStream()); // // 输出资源内容到相应对象 // byte[] b = new byte[1024]; // int len = -1; // while ((len = resourceAsStream.read(b, 0, 1024)) != -1) { // response.getOutputStream().write(b, 0, len); // } }
public static Map<String, String> parseRequest2(InputStream inputStream) { String string = null; StreamUtils.nonClosing(inputStream); try { string = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } System.out.println(string); // string = string.replaceAll("<xml>", "<" + ScanCodeEventRequestMessage.class.getSimpleName() + ">") // .replaceAll("</xml>", "</" + ScanCodeEventRequestMessage.class.getSimpleName() + ">"); xstream.alias("xml", Object.class); Object object = xstream.fromXML(string); System.out.println(object); Map<String, String> map = new HashMap<>(); return map; }
@Test public void lastModifiedWorksWithResourceThatDoesNotSupportFileBasedReading() throws Exception { Resource resource = mock(Resource.class); // underlying File is asked for so that the last modified time can be checked... // And then mock the file changing; i.e. the File says it has been modified given(resource.lastModified()).willReturn(100L, 100L, 200L); // does not support File-based reading; delegates to InputStream-style reading... //resource.getFile(); //mock.setThrowable(new FileNotFoundException()); given(resource.getInputStream()).willReturn(StreamUtils.emptyInput()); ResourceScriptSource scriptSource = new ResourceScriptSource(resource); assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified()); scriptSource.getScriptAsString(); assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified()); // Must now report back as having been modified assertTrue("ResourceScriptSource must report back as being modified if the underlying File resource is reporting a changed lastModified time.", scriptSource.isModified()); }
private void copyRange(InputStream in, OutputStream out, long start, long end) throws IOException { long skipped = in.skip(start); if (skipped < start) { throw new IOException("Skipped only " + skipped + " bytes out of " + start + " required."); } long bytesToCopy = end - start + 1; byte buffer[] = new byte[StreamUtils.BUFFER_SIZE]; while (bytesToCopy > 0) { int bytesRead = in.read(buffer); if (bytesRead <= bytesToCopy) { out.write(buffer, 0, bytesRead); bytesToCopy -= bytesRead; } else { out.write(buffer, 0, (int) bytesToCopy); bytesToCopy = 0; } if (bytesRead == -1) { break; } } }
@Test public void testCompression() throws Exception { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity<byte[]> entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody())); try { assertThat(StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))) .isEqualTo("Hello World"); } finally { inflater.close(); } }
@Override protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException { if (this.body == null) { if (this.outputStreaming) { int contentLength = (int) headers.getContentLength(); if (contentLength >= 0) { this.connection.setFixedLengthStreamingMode(contentLength); } else { this.connection.setChunkedStreamingMode(this.chunkSize); } } SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers); this.connection.connect(); this.body = this.connection.getOutputStream(); } return StreamUtils.nonClosing(this.body); }
@Test public void multipleWrites() throws Exception { AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); final byte[] body = "Hello World".getBytes("UTF-8"); if (request instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request; streamingRequest.setBody(outputStream -> StreamUtils.copy(body, outputStream)); } else { StreamUtils.copy(body, request.getBody()); } Future<ClientHttpResponse> futureResponse = request.executeAsync(); ClientHttpResponse response = futureResponse.get(); try { FileCopyUtils.copy(body, request.getBody()); fail("IllegalStateException expected"); } catch (IllegalStateException ex) { // expected } finally { response.close(); } }
@Test(expected = IllegalStateException.class) public void multipleWrites() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST); final byte[] body = "Hello World".getBytes("UTF-8"); if (request instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request; streamingRequest.setBody(new StreamingHttpOutputMessage.Body() { @Override public void writeTo(OutputStream outputStream) throws IOException { StreamUtils.copy(body, outputStream); } }); } else { StreamUtils.copy(body, request.getBody()); } ClientHttpResponse response = request.execute(); try { FileCopyUtils.copy(body, request.getBody()); } finally { response.close(); } }
@RequestMapping( value = { "/jnlpRemoteConsoleSupportFiles/{host_id}/**" }, method = RequestMethod.GET ) @ResponseBody public void getRemoteConsoleJnlpSupportFiles( HttpServletRequest request, HttpServletResponse response ) throws HMSRestException { URI uri = null; try { // TODO -move this oob call to https in future, currently this API // is not used uri = new URI( "http", null, hmsIpAddr, hmsPort, request.getServletPath() + request.getPathInfo(), request.getQueryString(), null ); // RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add( "Content-Type", "application/java-archive" ); InputStream input = new BufferedInputStream( uri.toURL().openStream() ); StreamUtils.copy( input, response.getOutputStream() ); } catch ( Exception e ) { throw new HMSRestException( HttpStatus.INTERNAL_SERVER_ERROR.value(), "Server Error", "Exception while connecting to hms." + ( ( uri != null ) ? uri.toString() : "" ) ); } }
@Test public void testCompression() throws Exception { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); RestTemplate restTemplate = new TestRestTemplate(); ResponseEntity<byte[]> entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); assertEquals(HttpStatus.OK, entity.getStatusCode()); GZIPInputStream inflater = new GZIPInputStream( new ByteArrayInputStream(entity.getBody())); try { assertEquals("welcome to the application Adarsh", StreamUtils.copyToString(inflater, Charset.forName("UTF-8"))); } finally { inflater.close(); } }
@Override public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) { try { String banner = StreamUtils.copyToString(this.resource.getInputStream(), environment.getProperty("banner.charset", Charset.class, Charset.forName("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 public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String content = "Hello World"; if (this.echoRequestInfo) { content += " scheme=" + request.getScheme(); content += " remoteaddr=" + request.getRemoteAddr(); } if (this.writeWithoutContentLength) { response.setContentType("text/plain"); ServletOutputStream outputStream = response.getOutputStream(); StreamUtils.copy(content.getBytes(), outputStream); outputStream.flush(); } else { response.getWriter().write(content); } }
private void extractFromStream(ZipInputStream zipStream, boolean overwrite, File outputFolder) throws IOException { ZipEntry entry = zipStream.getNextEntry(); while (entry != null) { File file = new File(outputFolder, entry.getName()); if (file.exists() && !overwrite) { throw new ReportableException((file.isDirectory() ? "Directory" : "File") + " '" + file.getName() + "' already exists. Use --force if you want to overwrite or " + "specify an alternate location."); } if (!entry.isDirectory()) { FileCopyUtils.copy(StreamUtils.nonClosing(zipStream), new FileOutputStream(file)); } else { file.mkdir(); } zipStream.closeEntry(); entry = zipStream.getNextEntry(); } }