Example usage for org.apache.commons.io IOUtils write

List of usage examples for org.apache.commons.io IOUtils write

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils write.

Prototype

public static void write(StringBuffer data, OutputStream output) throws IOException 

Source Link

Document

Writes chars from a StringBuffer to bytes on an OutputStream using the default character encoding of the platform.

Usage

From source file:ch.cyberduck.core.b2.B2ObjectListServiceTest.java

@Test
public void testList() throws Exception {
    final B2Session session = new B2Session(new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("b2.user"),
                    System.getProperties().getProperty("b2.key"))));
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path bucket = new B2DirectoryFeature(session)
            .mkdir(new Path(String.format("test-%s", UUID.randomUUID().toString()),
                    EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus());
    final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final TransferStatus status = new TransferStatus();
    status.setChecksum(Checksum.parse("da39a3ee5e6b4b0d3255bfef95601890afd80709"));
    final HttpResponseOutputStream<BaseB2Response> out = new B2WriteFeature(session).write(file, status,
            new DisabledConnectionCallback());
    IOUtils.write(new byte[0], out);
    out.close();/*from  ww w.j av  a 2s .  c o  m*/
    final B2FileResponse resopnse = (B2FileResponse) out.getStatus();
    final AttributedList<Path> list = new B2ObjectListService(session).list(bucket,
            new DisabledListProgressListener());
    assertNotNull(list.find(new SimplePathPredicate(file)));
    assertEquals("1", list.find(new SimplePathPredicate(file)).attributes().getRevision());
    assertEquals(0L, list.find(new SimplePathPredicate(file)).attributes().getSize());
    new B2DeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    assertFalse(
            new B2ObjectListService(session).list(bucket, new DisabledListProgressListener()).contains(file));
    new B2DeleteFeature(session).delete(Collections.singletonList(bucket), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:com.tc.webshell.servlets.Upload.java

/**
  * Processes requests for both HTTP/* w w w .j a  v  a 2s .  c  o m*/
  * <code>GET</code> and
  * <code>POST</code> methods.
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */

@SuppressWarnings("unchecked")
protected void processRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    res.setContentType("application/json");

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

    upload.setFileSizeMax(60000000);

    // Parse the request
    try {
        Database db = ContextInfo.getUserDatabase();

        for (FileItem item : (List<FileItem>) upload.parseRequest(req)) {
            if (!item.isFormField()) {

                InputStream in = item.getInputStream();

                File file = this.createTempFile("upload", item.getName());

                OutputStream fout = new FileOutputStream(file);

                try {
                    byte[] bytes = IOUtils.toByteArray(in);

                    IOUtils.write(bytes, fout);

                    Map<String, String> queryMap = XSPUtils.getQueryMap(req.getQueryString());

                    Document doc = null;

                    if (queryMap.containsKey("documentId")) {
                        doc = new DocFactory().attachToDocument(db, queryMap.get("documentId"), file);
                    } else {
                        doc = new DocFactory().buildDocument(req, db, file);
                    }

                    doc.save();

                    Prompt prompt = new Prompt();

                    prompt.setMessage("file uploaded successfully");

                    prompt.setTitle("info");

                    prompt.addProperty("noteId", doc.getNoteID());

                    prompt.addProperty("unid", doc.getUniversalID());

                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd G 'at' HH:mm:ss z");

                    String strdate = formatter.format(doc.getCreated().toJavaDate());

                    prompt.addProperty("created", strdate);

                    Vector<Item> items = doc.getItems();
                    for (Item notesItem : items) {
                        prompt.addProperty(notesItem.getName(), notesItem.getText());
                    }

                    String json = MapperFactory.mapper().writeValueAsString(prompt);

                    this.compressResponse(req, res, json);

                    doc.recycle();

                } finally {
                    in.close();

                    if (fout != null) {
                        fout.close();
                        file.delete();//make sure we cleanup
                    }
                }
            } else {
                //
            }
            break;

        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);

    } finally {
        res.getOutputStream().close();

    }

}

From source file:net.mindengine.blogix.web.BlogixServlet.java

private void printResponseText(HttpServletResponse res, String responseText) {
    try {/*from   www .  j  a v a 2  s  . c o m*/
        IOUtils.write(responseText, res.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.tc.utils.DxlUtils.java

private static void write(File dir, String fileName, byte[] byteMe) {
    OutputStream out = null;//  ww  w  . j ava 2s .  co m
    try {
        out = new FileOutputStream(dir.getPath() + IOUtils.DIR_SEPARATOR + fileName);
        IOUtils.write(byteMe, out);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(out);
    }

}

From source file:ch.cyberduck.core.b2.B2LargeUploadServiceTest.java

@Test
public void testUpload() throws Exception {
    final B2Session session = new B2Session(new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("b2.user"),
                    System.getProperties().getProperty("b2.key"))));
    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());

    final Path test = new Path(bucket, UUID.randomUUID().toString() + ".txt", EnumSet.of(Path.Type.file));
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());

    // Each segment, except the last, must be larger than 100MB.
    final int length = 100 * 1024 * 1024 + 1;
    final byte[] content = RandomUtils.nextBytes(length);

    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);
    out.close();/*w  ww.  java  2 s .c  o  m*/
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    final Checksum checksum = new SHA1ChecksumCompute().compute(new ByteArrayInputStream(content),
            new TransferStatus());
    status.setChecksum(checksum);

    final B2LargeUploadService upload = new B2LargeUploadService(session, new B2WriteFeature(session),
            PreferencesFactory.get().getLong("b2.upload.largeobject.size"),
            PreferencesFactory.get().getInteger("b2.upload.largeobject.concurrency"));

    upload.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            status, new DisabledConnectionCallback());
    assertEquals(checksum, new B2AttributesFinderFeature(session).find(test).getChecksum());

    assertTrue(status.isComplete());
    assertFalse(status.isCanceled());
    assertEquals(content.length, status.getOffset());

    assertTrue(new DefaultFindFeature(session).find(test));
    final InputStream in = new B2ReadFeature(session).read(test, new TransferStatus(),
            new DisabledConnectionCallback());
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
    new StreamCopier(status, status).transfer(in, buffer);
    in.close();
    buffer.close();
    assertArrayEquals(content, buffer.toByteArray());
    new B2DeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    local.delete();
    session.close();
}

From source file:com.jayway.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java

@Test
public void input_stream_uploading_works() throws IOException {
    File file = folder.newFile("something");
    IOUtils.write("Something21", new FileOutputStream(file));

    given().multiPart("controlName", "original", new FileInputStream(file)).when().post("/fileUpload2").then()
            .body("size", greaterThan(10)).body("name", equalTo("controlName"))
            .body("originalName", equalTo("original"));
}

From source file:caarray.client.examples.java.DownloadMageTabExport.java

private void download() throws InvalidInputException, DataTransferException, IOException {
    CaArrayEntityReference experimentRef = searchForExperiment();
    if (experimentRef == null) {
        System.err.println("Could not find experiment with the requested title.");
        return;// ww  w.j  a  v a 2  s .  com
    }
    long startTime = System.currentTimeMillis();
    MageTabFileSet fileSet = dataService.exportMageTab(experimentRef);
    long totalTime = System.currentTimeMillis() - startTime;
    byte[] idfContents = fileSet.getIdf().getContents();
    byte[] sdrfContents = fileSet.getSdrf().getContents();
    Set<File> dataFiles = fileSet.getDataFiles();
    int bytesRetrieved = idfContents.length + sdrfContents.length;
    int numDataFileRefs = dataFiles == null || dataFiles.size() <= 0 ? 0 : dataFiles.size();

    System.out.println("Retrieved " + bytesRetrieved + " bytes and " + numDataFileRefs
            + " data file references in " + totalTime + " ms.");
    System.out.println("IDF:");
    IOUtils.write(idfContents, System.out);
    System.out.println("SDRF:");
    IOUtils.write(sdrfContents, System.out);

}

From source file:de.cosmocode.palava.core.Main.java

private void persistState() {
    if (options.getStateFile() == null)
        return;// w  w  w . ja v  a2  s. c o  m

    try {
        final State state = framework == null ? State.FAILED : framework.currentState();
        final Writer writer = new FileWriter(options.getStateFile());
        try {
            IOUtils.write(state.name() + "\n", writer);
        } finally {
            writer.close();
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("cannot persist state to file", e);
    }
}

From source file:com.cloudera.csd.tools.codahale.AbstractCodahaleFixtureGenerator.java

public AbstractCodahaleFixtureGenerator(String[] args, Options options) throws Exception {
    Preconditions.checkNotNull(args);//from  ww w.ja  va  2  s .c o  m
    Preconditions.checkNotNull(options);

    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine cmdLine = parser.parse(options, args);
        if (!cmdLine.getArgList().isEmpty()) {
            throw new ParseException("Unexpected extra arguments: " + cmdLine.getArgList());
        }
        config = new MapConfiguration(Maps.<String, Object>newHashMap());
        for (Option option : cmdLine.getOptions()) {
            config.addProperty(option.getLongOpt(), option.getValue());
        }
    } catch (ParseException ex) {
        IOUtils.write("Error: " + ex.getMessage() + "\n", System.err);
        printUsageMessage(System.err, options);
        throw ex;
    }
}

From source file:eu.europa.ec.markt.dss.signature.cades.CMSSignedDocument.java

@Override
public void save(String filePath) {

    try {//from   w  ww. j  a v a 2 s  . com

        FileOutputStream fos = new FileOutputStream(filePath);
        IOUtils.write(getBytes(), fos);
        fos.close();
    } catch (FileNotFoundException e) {
        throw new DSSException(e);
    } catch (DSSException e) {
        throw new DSSException(e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}