@Test public void testCopyToLocalMulti() throws Exception { String fName1 = UUID.randomUUID() + ".txt"; String name1 = "local/" + fName1; String fName2 = UUID.randomUUID() + ".txt"; String name2 = "local/" + fName2; File dir = new File("local"); dir.mkdir(); Resource res1 = TestUtils.writeToFS(cfg, name1); Resource res2 = TestUtils.writeToFS(cfg, name2); shell.copyToLocal(name1, "local"); shell.copyToLocal(false, true, name2, "local"); File fl1 = new File(name1); File fl2 = new File(name2); try { assertTrue(fl1.exists()); assertTrue(fl2.exists()); assertArrayEquals( FileCopyUtils.copyToByteArray(res1.getInputStream()), FileCopyUtils.copyToByteArray(fl1)); assertArrayEquals( FileCopyUtils.copyToByteArray(res2.getInputStream()), FileCopyUtils.copyToByteArray(fl2)); } finally { FileSystemUtils.deleteRecursively(dir); } }
@Test public void testCopyToLocal() throws Exception { String fName = UUID.randomUUID() + ".txt"; String name = "local/" + fName; Resource res = TestUtils.writeToFS(cfg, name); shell.copyToLocal(name, "."); File fl = new File(fName); try { assertTrue(fl.exists()); assertArrayEquals( FileCopyUtils.copyToByteArray(res.getInputStream()), FileCopyUtils.copyToByteArray(fl)); } finally { fl.delete(); } }
@RequestMapping(value = "/handle44/{imageId}") public ResponseEntity<byte[]> handle44(@PathVariable("imageId") String imageId) throws Throwable { Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(fileData, HttpStatus.OK); return responseEntity; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { byte[] body = "gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip " .getBytes("UTF-8"); resp.setStatus(HttpServletResponse.SC_OK); if (containsHeader(req, "Content-Encoding", "gzip")) { GZIPInputStream gzipInputStream = new GZIPInputStream(req.getInputStream()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int byteCount = 0; byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = gzipInputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); byteCount += bytesRead; } byteArrayOutputStream.flush(); gzipInputStream.close(); assertEquals("Content length does not match", body.length, byteCount); assertTrue("Invalid body", Arrays.equals(byteArrayOutputStream.toByteArray(), body)); } else { byte[] decompressedBody = FileCopyUtils.copyToByteArray(req.getInputStream()); assertTrue("Invalid body", Arrays.equals(decompressedBody, body)); } }
@MediumTest public void testGetAcceptEncodingGzip() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/gzip"), HttpMethod.GET); assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod()); request.getHeaders().add("Accept-Encoding", "gzip"); ClientHttpResponse response = request.execute(); try { assertNotNull(response.getStatusText()); assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); assertTrue("Header not found", response.getHeaders().containsKey("Content-Encoding")); assertEquals( "Header value not found", Arrays.asList("gzip"), response.getHeaders().get("Content-Encoding")); byte[] body = "gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip " .getBytes("UTF-8"); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); assertTrue("Invalid body", Arrays.equals(body, result)); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(body.length); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream); FileCopyUtils.copy(body, gzipOutputStream); byte[] compressedBody = byteArrayOutputStream.toByteArray(); assertEquals( "Invalid content-length", response.getHeaders().getContentLength(), compressedBody.length); } finally { response.close(); } }
@MediumTest public void testEchoNoContentLength() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT); assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod()); String headerName = "MyHeader"; String headerValue1 = "value1"; request.getHeaders().add(headerName, headerValue1); String headerValue2 = "value2"; request.getHeaders().add(headerName, headerValue2); byte[] body = "Hello World".getBytes("UTF-8"); FileCopyUtils.copy(body, request.getBody()); ClientHttpResponse response = request.execute(); try { assertNotNull(response.getStatusText()); assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); assertTrue("Header not found", response.getHeaders().containsKey(headerName)); assertEquals( "Header value not found", Arrays.asList(headerValue1, headerValue2), response.getHeaders().get(headerName)); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); assertTrue("Invalid body", Arrays.equals(body, result)); } finally { response.close(); } }
@Test public void getResourcesWithUpdated() throws Exception { String name = PACKAGE_PATH + "/Sample.txt"; byte[] bytes = "abc".getBytes(); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, bytes)); List<URL> resources = toList(this.reloadClassLoader.getResources(name)); assertThat(FileCopyUtils.copyToByteArray(resources.get(0).openStream())).isEqualTo(bytes); }
@Test public void getBody() throws Exception { byte[] content = "Hello World".getBytes("UTF-8"); mockRequest.setContent(content); byte[] result = FileCopyUtils.copyToByteArray(request.getBody()); assertArrayEquals("Invalid content returned", content, result); }
@ResponseBody @RequestMapping(value = "/handle42/{imageId}") public byte[] handle42(@PathVariable("imageId") String imageId) throws IOException { System.out.println("load image of " + imageId); Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); return fileData; }
@Test public void getAddedClass() throws Exception { String name = PACKAGE_PATH + "/SampleParent.class"; byte[] bytes = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("SampleParent.class")); this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.ADDED, bytes)); Class<?> loaded = this.reloadClassLoader.loadClass(PACKAGE + ".SampleParent"); assertThat(loaded.getClassLoader()).isEqualTo(this.reloadClassLoader); }
@Test public void body() throws Exception { byte[] body = "Hello World".getBytes("UTF-8"); this.builder.content(body); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); byte[] result = FileCopyUtils.copyToByteArray(request.getInputStream()); assertArrayEquals(body, result); }
public InputStream getBody() throws IOException { if (this.body == null) { if (response.getBody() != null) { this.body = FileCopyUtils.copyToByteArray(response.getBody()); } else { body = new byte[] {}; } } return new ByteArrayInputStream(this.body); }
private byte[] getResponseBody(ClientHttpResponse response) { try { InputStream responseBody = response.getBody(); if (responseBody != null) { return FileCopyUtils.copyToByteArray(responseBody); } } catch (IOException ex) { // ignore } return new byte[0]; }
@Test public void addClassLoaderFiles() throws Exception { ClassLoaderFiles classLoaderFiles = new ClassLoaderFiles(); classLoaderFiles.addFile("f", new ClassLoaderFile(Kind.ADDED, "abc".getBytes())); Restarter restarter = Restarter.getInstance(); restarter.addClassLoaderFiles(classLoaderFiles); restarter.restart(); ClassLoader classLoader = ((TestableRestarter) restarter).getRelaunchClassLoader(); assertThat(FileCopyUtils.copyToByteArray(classLoader.getResourceAsStream("f"))) .isEqualTo("abc".getBytes()); }
/** {@inheritDoc} */ @Override public RrdGraphDetails createGraphReturnDetails(String command, File workDir) throws IOException, org.opennms.netmgt.rrd.RrdException { // Creating Temp PNG File File pngFile = File.createTempFile("opennms.rrdtool.", ".png"); command = command.replaceFirst("graph - ", "graph " + pngFile.getAbsolutePath() + " "); int width; int height; String[] printLines; InputStream pngStream; try { // Executing RRD Command InputStream is = createGraph(command, workDir); // Processing Command Output BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { String line = null; if ((line = reader.readLine()) == null) { throw new IOException("No output from the createGraph() command"); } String[] s = line.split("x"); width = Integer.parseInt(s[0]); height = Integer.parseInt(s[1]); List<String> printLinesList = new ArrayList<String>(); while ((line = reader.readLine()) != null) { printLinesList.add(line); } printLines = printLinesList.toArray(new String[printLinesList.size()]); } finally { reader.close(); } // Creating PNG InputStream byte[] byteArray = FileCopyUtils.copyToByteArray(pngFile); pngStream = new ByteArrayInputStream(byteArray); } catch (Throwable e) { throw new RrdException("Can't execute command " + command, e); } finally { pngFile.delete(); } // Creating Graph Details return new JniGraphDetails(width, height, printLines, pngStream); }
@Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); Resource resource = new ClassPathResource("public.cert"); String publicKey = null; try { publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); } catch (IOException e) { throw new RuntimeException(e); } converter.setVerifierKey(publicKey); return converter; }
/** * Load the defining bytes for the given class, to be turned into a Class object through a {@link * #defineClass} call. * * <p>The default implementation delegates to {@link #openStreamForClass} and {@link * #transformIfNecessary}. * * @param name the name of the class * @return the byte content (with transformers already applied), or <code>null</code> if no class * defined for that name * @throws ClassNotFoundException if the class for the given name couldn't be loaded */ protected byte[] loadBytesForClass(String name) throws ClassNotFoundException { InputStream is = openStreamForClass(name); if (is == null) { return null; } try { // Load the raw bytes. byte[] bytes = FileCopyUtils.copyToByteArray(is); // Transform if necessary and use the potentially transformed bytes. return transformIfNecessary(name, bytes); } catch (IOException ex) { throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex); } }
@MediumTest public void testGetAcceptEncodingIdentity() throws Exception { ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/gzip"), HttpMethod.GET); assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod()); // setting the following header in Gingerbread and newer disables automatic gzip compression request.getHeaders().add("Accept-Encoding", "identity"); ClientHttpResponse response = request.execute(); try { assertNotNull(response.getStatusText()); assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode()); assertFalse("Header found", response.getHeaders().containsKey("Content-Encoding")); byte[] body = "gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip gzip " .getBytes("UTF-8"); byte[] result = FileCopyUtils.copyToByteArray(response.getBody()); assertTrue("Invalid body", Arrays.equals(body, result)); assertEquals("Invalid content-length", response.getHeaders().getContentLength(), body.length); } finally { response.close(); } }
private byte[] createGraphAsByteArray(String command, File workDir) throws IOException, RrdException { String[] commandArray = StringUtils.createCommandArray(command, '@'); Process process; try { process = Runtime.getRuntime().exec(commandArray, null, workDir); } catch (IOException e) { IOException newE = new IOException( "IOException thrown while executing command '" + command + "' in " + workDir.getAbsolutePath() + ": " + e); newE.initCause(e); throw newE; } // this closes the stream when its finished byte[] byteArray = FileCopyUtils.copyToByteArray(process.getInputStream()); // this close the stream when its finished String errors = FileCopyUtils.copyToString(new InputStreamReader(process.getErrorStream())); // one particular warning message that originates in libart should be ignored if (errors.length() > 0 && errors.contains(IGNORABLE_LIBART_WARNING_STRING)) { LOG.debug( "Ignoring libart warning message in rrdtool stderr stream: {}", IGNORABLE_LIBART_WARNING_STRING); errors = errors.replaceAll(IGNORABLE_LIBART_WARNING_REGEX, ""); } if (errors.length() > 0) { throw new RrdException(errors); } return byteArray; }
private String readString(InputStream in) throws IOException { return new String(FileCopyUtils.copyToByteArray(in)); }