List of usage examples for org.apache.commons.io IOUtils write
public static void write(StringBuffer data, OutputStream output) throws IOException
StringBuffer
to bytes on an OutputStream
using the default character encoding of the platform. From source file:com.opentable.db.postgres.embedded.BundledPostgresBinaryResolver.java
/** * Unpack archive compressed by tar with bzip2 compression. By default system tar is used * (faster). If not found, then the java implementation takes place. * * @param tbzPath// www . j ava 2 s . co m * The archive path. * @param targetDir * The directory to extract the content to. */ private static void extractTxz(String tbzPath, String targetDir) throws IOException { try (InputStream in = Files.newInputStream(Paths.get(tbzPath)); XZInputStream xzIn = new XZInputStream(in); TarArchiveInputStream tarIn = new TarArchiveInputStream(xzIn)) { TarArchiveEntry entry; while ((entry = tarIn.getNextTarEntry()) != null) { final String individualFile = entry.getName(); final File fsObject = new File(targetDir + "/" + individualFile); if (entry.isSymbolicLink() || entry.isLink()) { Path target = FileSystems.getDefault().getPath(entry.getLinkName()); Files.createSymbolicLink(fsObject.toPath(), target); } else if (entry.isFile()) { byte[] content = new byte[(int) entry.getSize()]; int read = tarIn.read(content, 0, content.length); Verify.verify(read != -1, "could not read %s", individualFile); mkdirs(fsObject.getParentFile()); try (OutputStream outputFile = new FileOutputStream(fsObject)) { IOUtils.write(content, outputFile); } } else if (entry.isDirectory()) { mkdirs(fsObject); } else { throw new UnsupportedOperationException( String.format("Unsupported entry found: %s", individualFile)); } if (individualFile.startsWith("bin/") || individualFile.startsWith("./bin/")) { fsObject.setExecutable(true); } } } }
From source file:com.streamsets.datacollector.el.TestRuntimeEL.java
@Test public void testAuthToken() throws IOException { // create application token file with some string File appTokenFile = new File(runtimeInfo.getConfigDir(), "application-token.txt"); OutputStream appTokenStream = new FileOutputStream(appTokenFile); IOUtils.write("San Francisco", appTokenStream); appTokenStream.close();/*from w ww . j av a 2 s. c o m*/ File domProps = new File(runtimeInfo.getConfigDir(), "dpm.properties"); OutputStream dpmPropsStream = new FileOutputStream(domProps); IOUtils.write("dpm.applicationToken=@application-token.txt@", dpmPropsStream); dpmPropsStream.close(); OutputStream sdcProps = new FileOutputStream(new File(runtimeInfo.getConfigDir(), "sdc.properties")); IOUtils.write("config.includes=dpm.properties", sdcProps); sdcProps.close(); Configuration.setFileRefsBaseDir(new File(runtimeInfo.getConfigDir())); RuntimeEL.loadRuntimeConfiguration(runtimeInfo); Assert.assertEquals("San Francisco", RuntimeEL.authToken()); }
From source file:com.ning.http.client.async.MultipartUploadTest.java
/** * Tests that the streaming of a file works. *//*from w w w. java 2 s .co m*/ @Test(enabled = true) public void testSendingSmallFilesAndByteArray() { String expectedContents = "filecontent: hello"; String expectedContents2 = "gzipcontent: hello"; String expectedContents3 = "filecontent: hello2"; String testResource1 = "textfile.txt"; String testResource2 = "gzip.txt.gz"; String testResource3 = "textfile2.txt"; File testResource1File = null; try { testResource1File = getClasspathFile(testResource1); } catch (FileNotFoundException e) { // TODO Auto-generated catch block fail("unable to find " + testResource1); } File testResource2File = null; try { testResource2File = getClasspathFile(testResource2); } catch (FileNotFoundException e) { // TODO Auto-generated catch block fail("unable to find " + testResource2); } File testResource3File = null; try { testResource3File = getClasspathFile(testResource3); } catch (FileNotFoundException e) { // TODO Auto-generated catch block fail("unable to find " + testResource3); } List<File> testFiles = new ArrayList<File>(); testFiles.add(testResource1File); testFiles.add(testResource2File); testFiles.add(testResource3File); List<String> expected = new ArrayList<String>(); expected.add(expectedContents); expected.add(expectedContents2); expected.add(expectedContents3); List<Boolean> gzipped = new ArrayList<Boolean>(); gzipped.add(false); gzipped.add(true); gzipped.add(false); boolean tmpFileCreated = false; File tmpFile = null; FileOutputStream os = null; try { tmpFile = File.createTempFile("textbytearray", ".txt"); os = new FileOutputStream(tmpFile); IOUtils.write(expectedContents.getBytes("UTF-8"), os); tmpFileCreated = true; testFiles.add(tmpFile); expected.add(expectedContents); gzipped.add(false); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { if (os != null) { IOUtils.closeQuietly(os); } } if (!tmpFileCreated) { fail("Unable to test ByteArrayMultiPart, as unable to write to filesystem the tmp test content"); } AsyncHttpClientConfig.Builder bc = new AsyncHttpClientConfig.Builder(); bc.setFollowRedirects(true); AsyncHttpClient c = new AsyncHttpClient(bc.build()); try { RequestBuilder builder = new RequestBuilder("POST"); builder.setUrl(servletEndpointRedirectUrl + "/upload/bob"); builder.addBodyPart(new FilePart("file1", testResource1File, "text/plain", "UTF-8")); builder.addBodyPart(new FilePart("file2", testResource2File, "application/x-gzip", null)); builder.addBodyPart(new StringPart("Name", "Dominic")); builder.addBodyPart(new FilePart("file3", testResource3File, "text/plain", "UTF-8")); builder.addBodyPart(new StringPart("Age", "3", AsyncHttpProviderUtils.DEFAULT_CHARSET)); builder.addBodyPart(new StringPart("Height", "shrimplike", AsyncHttpProviderUtils.DEFAULT_CHARSET)); builder.addBodyPart(new StringPart("Hair", "ridiculous", AsyncHttpProviderUtils.DEFAULT_CHARSET)); builder.addBodyPart(new ByteArrayPart("file4", "bytearray.txt", expectedContents.getBytes("UTF-8"), "text/plain", "UTF-8")); com.ning.http.client.Request r = builder.build(); Response res = c.executeRequest(r).get(); assertEquals(200, res.getStatusCode()); testSentFile(expected, testFiles, res, gzipped); c.close(); } catch (Exception e) { e.printStackTrace(); fail("Download Exception"); } finally { FileUtils.deleteQuietly(tmpFile); } }
From source file:com.palantir.docker.compose.logging.FileLogCollectorShould.java
@Test public void collect_logs_in_parallel_for_two_containers() throws IOException, InterruptedException { when(compose.ps()).thenReturn(TestContainerNames.of("db", "db2")); CountDownLatch dbLatch = new CountDownLatch(1); when(compose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> { OutputStream outputStream = (OutputStream) args.getArguments()[1]; IOUtils.write("log", outputStream); dbLatch.countDown();// w w w .j av a2s.co m return true; }); CountDownLatch db2Latch = new CountDownLatch(1); when(compose.writeLogs(eq("db2"), any(OutputStream.class))).thenAnswer((args) -> { OutputStream outputStream = (OutputStream) args.getArguments()[1]; IOUtils.write("other", outputStream); db2Latch.countDown(); return true; }); logCollector.startCollecting(compose); assertThat(dbLatch.await(1, TimeUnit.SECONDS), is(true)); assertThat(db2Latch.await(1, TimeUnit.SECONDS), is(true)); assertThat(logDirectory.listFiles(), arrayContainingInAnyOrder(fileWithName("db.log"), fileWithName("db2.log"))); assertThat(new File(logDirectory, "db.log"), is(fileContainingString("log"))); assertThat(new File(logDirectory, "db2.log"), is(fileContainingString("other"))); logCollector.stopCollecting(); }
From source file:jp.eisbahn.oauth2.server.spi.servlet.TokenServlet.java
/** * Issue the token against the request based on OAuth 2.0. * //from w w w . java 2s. c o m * @param req The request object. * @param resp The response object. * @exception IOException When the error regarding I/O occurred. * @exception ServletException When other error occurred. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpServletRequestAdapter request = new HttpServletRequestAdapter(req); Response response = token.handleRequest(request); resp.setStatus(response.getCode()); resp.setContentType("application/json; charset=UTF-8"); PrintWriter writer = resp.getWriter(); IOUtils.write(response.getBody(), writer); writer.flush(); }
From source file:com.github.hipchat.api.Room.java
public boolean sendMessage(String message, UserId from, boolean notify, Color color) { String query = String.format(HipChatConstants.ROOMS_MESSAGE_QUERY_FORMAT, HipChatConstants.JSON_FORMAT, getOrigin().getAuthToken()); StringBuilder params = new StringBuilder(); if (message == null || from == null) { throw new IllegalArgumentException("Cant send message with null message or null user"); } else {/*from w ww . j a v a 2 s. c o m*/ params.append("room_id="); params.append(getId()); params.append("&from="); try { params.append(URLEncoder.encode(from.getName(), "UTF-8")); params.append("&message="); params.append(URLEncoder.encode(message, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } if (notify) { params.append("¬ify=1"); } if (color != null) { params.append("&color="); params.append(color.name().toLowerCase()); } final String paramsToSend = params.toString(); OutputStream output = null; InputStream input = null; HttpURLConnection connection = null; boolean result = false; try { URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_MESSAGE + query); connection = (HttpURLConnection) requestUrl.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); output = new BufferedOutputStream(connection.getOutputStream()); IOUtils.write(paramsToSend, output); IOUtils.closeQuietly(output); input = connection.getInputStream(); result = UtilParser.parseMessageResult(input); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(output); connection.disconnect(); } return result; }
From source file:com.github.rwitzel.streamflyer.experimental.bytestream.ByteStreamTest.java
private void assertOutputConversion_viaCharsetEncoder(String charsetName, boolean conversionErrorsExpected) throws Exception { // find charset Charset charset = Charset.forName(charsetName); // // configure decoder // CharsetDecoder decoder = charset.newDecoder(); // decoder.onUnmappableCharacter(CodingErrorAction.REPORT); // configure encoder CharsetEncoder encoder = charset.newEncoder(); encoder.onUnmappableCharacter(CodingErrorAction.REPORT); byte[] originalBytes = createBytes(); boolean conversionErrorsFound; try {/*from w ww .j ava2 s . c o m*/ // byte array as byte stream ByteArrayOutputStream targetByteStream = new ByteArrayOutputStream(); // byte stream as character stream Writer targetWriter = new OutputStreamWriter(targetByteStream, encoder); // modifying writer (we don't modify here) Writer modifyingWriter = new ModifyingWriter(targetWriter, new RegexModifier("a", 0, "a")); // character stream as byte stream OutputStream modifyingByteStream = new WriterOutputStream(modifyingWriter, charset); // encoder // not // supported // here!!! // byte stream as byte array IOUtils.write(originalBytes, modifyingByteStream); modifyingByteStream.close(); assertBytes(originalBytes, targetByteStream.toByteArray(), conversionErrorsExpected); conversionErrorsFound = false; } catch (MalformedInputException e) { conversionErrorsFound = true; } assertEquals(conversionErrorsExpected, conversionErrorsFound); }
From source file:ee.ria.xroad.proxy.clientproxy.WsdlRequestProcessor.java
HttpURLConnection createConnection(SoapMessageImpl message) throws Exception { URL url = new URL("http://127.0.0.1:" + SystemProperties.getClientProxyHttpPort()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true);//w w w .j a v a2 s. c o m con.setDoOutput(true); // Use the same timeouts as client proxy to server proxy connections. con.setConnectTimeout(SystemProperties.getClientProxyTimeout()); con.setReadTimeout(SystemProperties.getClientProxyHttpClientTimeout()); con.setRequestMethod("POST"); con.setRequestProperty(HttpHeaders.CONTENT_TYPE, MimeUtils.contentTypeWithCharset(MimeTypes.TEXT_XML, StandardCharsets.UTF_8.name())); IOUtils.write(message.getBytes(), con.getOutputStream()); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException( "Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage()); } return con; }
From source file:com.netflix.nicobar.core.persistence.JarArchiveRepository.java
@Override public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException { Objects.requireNonNull(jarScriptArchive, "jarScriptArchive"); ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec(); ModuleId moduleId = moduleSpec.getModuleId(); Path moduleJarPath = getModuleJarPath(moduleId); Files.deleteIfExists(moduleJarPath); JarFile sourceJarFile;/* w w w .j a v a 2s. co m*/ try { sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath()); } catch (URISyntaxException e) { throw new IOException(e); } JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile())); try { String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName(); Enumeration<JarEntry> sourceEntries = sourceJarFile.entries(); while (sourceEntries.hasMoreElements()) { JarEntry sourceEntry = sourceEntries.nextElement(); if (sourceEntry.getName().equals(moduleSpecFileName)) { // avoid double entry for module spec continue; } destJarFile.putNextEntry(sourceEntry); if (!sourceEntry.isDirectory()) { InputStream inputStream = sourceJarFile.getInputStream(sourceEntry); IOUtils.copy(inputStream, destJarFile); IOUtils.closeQuietly(inputStream); } destJarFile.closeEntry(); } // write the module spec String serialized = moduleSpecSerializer.serialize(moduleSpec); JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName()); destJarFile.putNextEntry(moduleSpecEntry); IOUtils.write(serialized, destJarFile); destJarFile.closeEntry(); } finally { IOUtils.closeQuietly(sourceJarFile); IOUtils.closeQuietly(destJarFile); } // update the timestamp on the jar file to indicate that the module has been updated Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime())); }
From source file:com.fusesource.forge.jmstest.benchmark.BenchmarkConfig.java
public ApplicationContext getApplicationContext() { if (applictionContext == null) { log().info("getSpringConfigurations() --> " + getSpringConfigurations()); if (getSpringConfigurations().size() > 0) { log().info("tmpdir --> " + System.getProperty("java.io.tmpdir")); File tmpDir = new File(System.getProperty("java.io.tmpdir"), getBenchmarkId()); if (tmpDir.exists()) { if (tmpDir.isFile()) { FileUtils.deleteQuietly(tmpDir); } else if (tmpDir.isDirectory()) { try { FileUtils.deleteDirectory(tmpDir); } catch (IOException ioe) { log().error("Error deleting directory: " + tmpDir, ioe); }/* w ww . ja va2 s . c om*/ } } tmpDir.mkdirs(); log().debug("Created directory: " + tmpDir); String[] tempFiles = new String[getSpringConfigurations().size()]; int cfgNumber = 0; for (String config : getSpringConfigurations()) { log().debug("Config to be written " + config); File cfgFile = new File(tmpDir, "SpringConfig-" + (cfgNumber) + ".xml"); tempFiles[cfgNumber++] = "file:/" + cfgFile.getAbsolutePath(); //tempFiles[cfgNumber++] = "file:\\\\localhost\\c$\\" + cfgFile.getAbsolutePath().substring(2); log().debug("file location " + tempFiles[cfgNumber - 1]); log().debug("Dumping : " + cfgFile.getAbsolutePath()); try { OutputStream os = new FileOutputStream(cfgFile); IOUtils.write(config.getBytes("UTF-8"), os); os.close(); } catch (Exception e) { log().error("Error Dumping: " + cfgFile.getAbsolutePath()); } } log().debug("Creating ApplicationContext from temporary files."); applictionContext = new FileSystemXmlApplicationContext(tempFiles); } else { applictionContext = new FileSystemXmlApplicationContext(); } } return applictionContext; }