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.taobao.tanggong.handler.FileLoader.java
protected void save(List<String> lines) { if (null != lines && null != this.dataDirectory) { File masterFile = new File(this.dataDirectory, this.getFilename()); File backupFile = new File(this.dataDirectory, this.getFilename() + ".bak"); if (masterFile.exists()) { masterFile.renameTo(backupFile); }//from w w w. j a v a 2 s .c o m OutputStream output = null; try { output = new FileOutputStream(masterFile); StringBuilder sb = new StringBuilder(); for (String k : lines) { sb.append(k); sb.append("\n"); } IOUtils.write(sb.toString(), output); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { IOUtils.closeQuietly(output); } } }
From source file:eu.europa.esig.dss.client.http.NativeHTTPDataLoader.java
@Override public byte[] post(String url, byte[] content) { OutputStream out = null;/* w ww . j a va 2 s .c o m*/ InputStream inputStream = null; byte[] result = null; try { URLConnection connection = new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); out = connection.getOutputStream(); IOUtils.write(content, out); inputStream = connection.getInputStream(); result = IOUtils.toByteArray(inputStream); } catch (IOException e) { throw new DSSException("An error occured while HTTP POST for url '" + url + "' : " + e.getMessage(), e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(inputStream); } return result; }
From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java
private synchronized void logString(final String message, final String user) throws BackendException { FileWriter fw = null;//w ww .j a v a 2s. co m try { fw = new FileWriter(this.logFile, true); IOUtils.write(String.format("%s: %s: %s\n", new Date().toString(), user, message), fw); } catch (IOException e) { throw new BackendException( String.format("Cannot write to log file %s.", this.logFile.getAbsoluteFile())); } finally { IOUtils.closeQuietly(fw); } }
From source file:ezbake.deployer.cli.commands.SSLCertsCommand.java
@Override public void call() throws IOException, TException { String[] args = globalParameters.unparsedArgs; minExpectedArgs(2, args, this); String securityId = args[0];//from ww w .ja va 2 s . c o m String filePath = args[1]; List<ArtifactDataEntry> certs = new ArrayList<>(); EzSecurityRegistration.Client client = null; ThriftClientPool pool = poolSupplier.get(); try { client = pool.getClient(EzSecurityRegistrationConstants.SERVICE_NAME, EzSecurityRegistration.Client.class); AppCerts s = client.getAppCerts( getSecurityToken(pool.getSecurityId(EzSecurityRegistrationConstants.SERVICE_NAME)), securityId); for (AppCerts._Fields fields : AppCerts._Fields.values()) { Object o = s.getFieldValue(fields); if (o instanceof byte[]) { String fieldName = fields.getFieldName().replace("_", "."); TarArchiveEntry tae = new TarArchiveEntry( new File(new File(SSL_CONFIG_DIRECTORY, securityId), fieldName)); certs.add(new ArtifactDataEntry(tae, (byte[]) o)); } } ArchiveStreamFactory asf = new ArchiveStreamFactory(); FileOutputStream fos = new FileOutputStream(filePath); GZIPOutputStream gzs = new GZIPOutputStream(fos); try (TarArchiveOutputStream aos = (TarArchiveOutputStream) asf .createArchiveOutputStream(ArchiveStreamFactory.TAR, gzs)) { aos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); for (ArtifactDataEntry entry : certs) { aos.putArchiveEntry(entry.getEntry()); IOUtils.write(entry.getData(), aos); aos.closeArchiveEntry(); } aos.finish(); gzs.finish(); } catch (ArchiveException ex) { throw new DeploymentException(ex.getMessage()); } finally { IOUtils.closeQuietly(fos); } } finally { pool.returnToPool(client); } }
From source file:net.gbmb.collector.example.SimpleLogPush.java
private String storeArchive(Collection collection) throws IOException { String cid = collection.getId(); java.util.Collection<CollectionRecord> records = collectionRecords.get(cid); // index// w w w . ja va 2 s.co m ByteArrayOutputStream indexStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); PrintStream output = new PrintStream(indexStream); // zip ByteArrayOutputStream archiveStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); ZipOutputStream zos = new ZipOutputStream(archiveStream); output.println("Serialize collection: " + collection.getId()); output.println(" creation date: " + collection.getCreationDate()); output.println(" end date: " + collection.getEndDate()); for (CollectionRecord cr : records) { output.print(cr.getRecordDate()); output.print(" "); output.println(cr.getContent()); if (cr.getAttachment() != null) { String attName = cr.getAttachment(); output.println(" > " + attName); ZipEntry entry = new ZipEntry(cr.getAttachment()); zos.putNextEntry(entry); InputStream content = temporaryStorage.get(cid, attName); IOUtils.copy(content, zos); } } // add the index file output.close(); ZipEntry index = new ZipEntry("index"); zos.putNextEntry(index); IOUtils.write(indexStream.toByteArray(), zos); // close zip zos.close(); ByteArrayInputStream content = new ByteArrayInputStream(archiveStream.toByteArray()); // send to final storage return finalStorage.store(cid, content); }
From source file:com.github.buildnum.servlet.VersionServlet.java
protected static void writeOutput(String s, HttpServletResponse resp) throws UnsupportedEncodingException, IOException { resp.setContentType("text/plain; encoding=ISO-8859-1"); IOUtils.write(s.getBytes("8859_1"), resp.getOutputStream()); }
From source file:com.shaobo.MyMojo.java
public void config() throws IOException { FileOutputStream fos = null;/*from www . ja v a 2 s .com*/ List<String> lines = null; List<String> res = null; int cnt = 0; for (String afile : allFiles) { fos = new FileOutputStream(afile); lines = fileLines.get(cnt); cnt += 1; res = replace(properties, lines); for (String line : res) { IOUtils.write(line + "\n", fos); } IOUtils.closeQuietly(fos); } }
From source file:io.inkstand.scribble.jcr.rules.RemoteContentRepositoryTest.java
/** * This tests implements an exploit to the XML External Entity Attack {@see http://www.ws-attacks.org/index.php/XML_Entity_Reference_Attack}. * The attack targets a file in the filesystem containing a secret, i.e. a password, which is not untypical for * build servers containing passwords for artifact repositories. The attacking file defines an entity that resolves * to the file containing the secret. The entity (&xxx;) is used in the xml file and can be read using xpath. * The RemoteContentRepository rule uses an arquillian.xml file to resolve the hostname of the target server using * an xpath expression. A test may use a specially prepared xml file and (optionally) an xpath injection to resolve * the contents of a system file. Of course this is more a hypothetical attack in a test framework as the attacker * may freely access the file directly with the same privileges as the user that started the JVM. * * @throws Throwable/*from w w w . ja va2 s. com*/ */ @Test(expected = AssertionError.class) public void test_ExternalitEntityAttack_notVulnerable() throws Throwable { //prepare //the attacked file containing the secret final File attackedFile = folder.newFile("attackedFile.txt"); try (FileOutputStream fos = new FileOutputStream(attackedFile)) { IOUtils.write("secretContent", fos); } //as attacker file we use a template and replacing a %s placeholder with the url of the attacked file //in a real-world attack we would use a valuable target such as /etc/passwd final File attackerFile = folder.newFile("attackerFile.xml"); //load the template file from the classpath try (InputStream is = getClass().getResourceAsStream("RemoteContentRepositoryTest_attacker.xml"); FileOutputStream fos = new FileOutputStream(attackerFile)) { final String attackerContent = prepareAttackerContent(is, attackedFile); IOUtils.write(attackerContent, fos); } System.setProperty("arquillian.launch", "testContainer"); subject.onArquillianHost(attackerFile.toURI().toURL()); subject.setupManually(); //act subject.before(); //assert //the content from the attacked file is put into the attacking xml where it resolves to the hostname assertEquals("secretContent", subject.getRemoteHost()); }
From source file:be.fedict.eid.dss.sp.servlet.UploadServlet.java
@Override @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doPost"); String fileName = null;//from ww w . ja v a 2s . co m String contentType; byte[] document = null; FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = upload.parseRequest(request); if (!items.isEmpty()) { fileName = items.get(0).getName(); // contentType = items.get(0).getContentType(); document = items.get(0).get(); } } catch (FileUploadException e) { throw new ServletException(e); } String extension = FilenameUtils.getExtension(fileName).toLowerCase(); contentType = supportedFileExtensions.get(extension); if (null == contentType) { /* * Unsupported content-type is converted to a ZIP container. */ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); ZipEntry zipEntry = new ZipEntry(fileName); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(document, zipOutputStream); zipOutputStream.close(); fileName = FilenameUtils.getBaseName(fileName) + ".zip"; document = outputStream.toByteArray(); contentType = "application/zip"; } LOG.debug("File name: " + fileName); LOG.debug("Content Type: " + contentType); String signatureRequest = new String(Base64.encode(document)); request.getSession().setAttribute(DOCUMENT_SESSION_ATTRIBUTE, document); request.getSession().setAttribute("SignatureRequest", signatureRequest); request.getSession().setAttribute("ContentType", contentType); response.sendRedirect(request.getContextPath() + this.postPage); }
From source file:com.github.born2snipe.maven.plugin.idea.sandbox.IdeaCacheLocatorTest.java
private void initializeIdeaProperties(boolean hasOverriddenPath) { File bin = new File(root, "bin"); bin.mkdirs();/*from w ww .j av a 2s .c om*/ String contents = ""; File properties = new File(bin, "idea.properties"); if (hasOverriddenPath) { contents = "idea.system.path=" + cache.getAbsolutePath(); } try (OutputStream output = new FileOutputStream(properties)) { IOUtils.write(contents, output); } catch (IOException e) { throw new RuntimeException(e); } }