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

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

Introduction

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

Prototype

public static void copy(Reader input, OutputStream output) throws IOException 

Source Link

Document

Copy chars from a Reader to bytes on an OutputStream using the default character encoding of the platform, and calling flush.

Usage

From source file:com.datatorrent.lib.io.HttpInputOperatorTest.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test//from   www  .j av a2s. c o m
public void testHttpInputModule() throws Exception {

    final List<String> receivedMessages = new ArrayList<String>();
    Handler handler = new AbstractHandler() {
        int responseCount = 0;

        @Override
        public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), bos);
            receivedMessages.add(new String(bos.toByteArray()));
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Transfer-Encoding", "chunked");
            try {
                JSONObject json = new JSONObject();
                json.put("responseId", "response" + ++responseCount);
                byte[] bytes = json.toString().getBytes();
                response.getOutputStream().println(bytes.length);
                response.getOutputStream().write(bytes);
                response.getOutputStream().println();
                response.getOutputStream().println(0);
                response.getOutputStream().flush();
            } catch (JSONException e) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error generating response: " + e.toString());
            }

            ((Request) request).setHandled(true);
        }
    };

    Server server = new Server(0);
    server.setHandler(handler);
    server.start();

    String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext";
    System.out.println(url);

    final AbstractHttpInputOperator operator = new HttpJsonChunksInputOperator();

    CollectorTestSink sink = new CollectorTestSink();

    operator.outputPort.setSink(sink);
    operator.setName("testHttpInputNode");
    operator.setUrl(new URI(url));

    operator.setup(null);
    operator.activate(null);

    int timeoutMillis = 3000;
    while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) {
        operator.emitTuples();
        timeoutMillis -= 20;
        Thread.sleep(20);
    }

    Assert.assertTrue("tuple emmitted", sink.collectedTuples.size() > 0);

    Map<String, String> tuple = (Map<String, String>) sink.collectedTuples.get(0);
    Assert.assertEquals("", tuple.get("responseId"), "response1");

    operator.deactivate();
    operator.teardown();
    server.stop();

}

From source file:com.twitter.heron.common.config.ConfigReaderTest.java

@Test
public void testLoadFile() throws IOException {
    InputStream inputStream = loadResource();
    File file = File.createTempFile("defaults_temp", "yaml");
    file.deleteOnExit();/*from  ww  w. jav  a2  s .  co  m*/
    OutputStream outputStream = new FileOutputStream(file);
    IOUtils.copy(inputStream, outputStream);
    outputStream.close();
    Map<String, Object> props = ConfigReader.loadFile(file.getAbsolutePath());
    testProperty(props);
}

From source file:it.unitn.elisco.servlet.ImageUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  w  w. j a va 2s . com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(false);
    Person user;

    if (request.getRequestURI().equals("/admin/image_upload")) {
        user = (Person) session.getAttribute("admin");
    } else {
        user = (Person) session.getAttribute("student");
    }
    // Get the image uploaded by the user as a stream
    Part imagePart = request.getPart("image");
    String imageExtension = "." + imagePart.getSubmittedFileName().split("\\.")[1];

    // Write to a temp file
    File tempFile = File.createTempFile("tmp", imageExtension);
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    IOUtils.copy(imagePart.getInputStream(), out);

    // Upload the image to Cloudinary
    ImageUploader uploader = ImageUploader.getInstance();
    String imageId = uploader.uploadImageToCloud(user, tempFile);

    // Get the url for the uploaded image
    String imageUrl = uploader.getURLWithDimensions(imageId, 200, 200);

    // Send JSON response back to ajax
    String json = new Gson().toJson(imageUrl);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:net.duckling.ddl.util.ImageUtils.java

/**
 * ??//from  ww  w  .jav  a  2s .  com
 * @param  in ?
 * @return ?
 * */
public static String saveAsFile(InputStream in) {
    String fileName = PATH + TEMP + System.nanoTime();
    try {
        File directory = new File(PATH);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(fileName);
        FileOutputStream fos = new FileOutputStream(file);
        IOUtils.copy(in, fos);
        in.close();
        fos.close();
    } catch (IOException e) {
        throw new RuntimeException("save tmp file error:" + fileName, e);
    }
    return fileName;
}

From source file:de.taimos.daemon.plugin.AbstractJarHeaderMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    File artifactFile = new File(this.artifact);
    if (!artifactFile.exists()) {
        throw new MojoExecutionException("artifact does not exist: " + this.artifact);
    }//from  w  w w .  ja  va  2s  .co m
    File artifactTmpFile = new File(this.artifact + ".tmp");

    try (FileOutputStream fos = new FileOutputStream(artifactTmpFile);
            FileInputStream fis = new FileInputStream(artifactFile)) {
        StringBuilder header = new StringBuilder();
        header.append("#!/bin/bash");
        header.append('\n');
        header.append(this.getCommand());
        header.append('\n');
        header.append("exit");
        header.append('\n');

        fos.write(header.toString().getBytes());
        IOUtils.copy(fis, fos);

        artifactTmpFile.setExecutable(true, false);
    } catch (Exception e) {
        throw new MojoExecutionException("Error writing stream", e);
    }

    artifactFile.delete();
    artifactTmpFile.renameTo(artifactFile);
}

From source file:edu.cornell.med.icb.learning.libsvm.LibSvmModel.java

@Override
public void write(final OutputStream stream) throws IOException {

    // write the model to a temporary file, then copy the file content to the stream.
    File tmp;/*  w w w . j  a va2s. c om*/
    FileInputStream fis = null;
    try {
        tmp = File.createTempFile("model", ".svm");
        this.write(tmp.getAbsolutePath());

        fis = new FileInputStream(tmp);
        IOUtils.copy(fis, stream);
        tmp.delete();
    } catch (IOException e) {
        throw new RuntimeException("Unable to write model to output stream.", e);
    } finally {
        IOUtils.closeQuietly(fis);
    }
    //throw new UnsupportedOperationException("Unable to write model to a stream in libSVM 3.18");
    //svm.svm_save_model(stream, nativeModel);
}

From source file:mn.sict.krono.renders.UploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w w.  j  av a  2s  .c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    String templateName = request.getParameter("demo_name");
    Part filePart = request.getPart("demo_img");
    try {
        // String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
        InputStream fileContent = filePart.getInputStream();
        System.out.println(templateName);
        File file = new File("uploads/" + templateName + ".png");
        System.out.println(file.getAbsolutePath());
        OutputStream outputStream = new FileOutputStream(file);
        IOUtils.copy(fileContent, outputStream);
        outputStream.close();

        Thumbnails.of(new File("uploads/" + templateName + ".png")).size(500, 707).outputFormat("PNG")
                .toFiles(Rename.NO_CHANGE);

    } catch (NullPointerException ex) {
        System.out.println("null param");
    }

    response.getWriter().write("uploaded lmao");

    System.out.println("fking shit");
    response.sendRedirect("init.jsp?req=" + templateName);
}

From source file:com.arpnetworking.tsdaggregator.perf.CollectdPipelineTest.java

@Test
public void test() throws IOException, InterruptedException, URISyntaxException {
    // Extract the sample file

    final Path gzipPath = Paths.get("build/resources/perf/collectd-sample1.log.gz");
    final FileInputStream fileInputStream = new FileInputStream(gzipPath.toFile());
    final GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
    final Path path = Paths.get("build/tmp/perf/collectd-sample1.log");
    final FileOutputStream outputStream = new FileOutputStream(path.toFile());

    IOUtils.copy(gzipInputStream, outputStream);

    benchmark(new File(Resources.getResource("collectd_sample1_pipeline.json").toURI()),
            Duration.standardMinutes(20));
}

From source file:de.jcup.code2doc.renderer.docbook.ExamplePDFGenerator.java

protected void generateImpl() {
    String xml = "";
    xml = "res:docbook-example-04.xml";
    //      xml = "res:docbook-example-05-article.xml";
    xml = "res:docbook-example-06-article.xml";
    xml = "res:example-specification.xml";
    PDFRenderer pdfRenderer = PDFRenderer.create(xml);
    pdfRenderer.parameter("toc.section.depth", "5");
    try {/*from  w  w  w  . j  a  v  a  2s.co m*/
        InputStream in = pdfRenderer.render();
        File newFile = new File("C:\\temp\\output_generated.pdf");
        FileOutputStream out = new FileOutputStream(newFile);
        IOUtils.copy(in, out);
        System.out.println("DONE:" + newFile.getAbsolutePath());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    RTFRenderer rtfRenderer = RTFRenderer.create(xml);
    rtfRenderer.parameter("toc.section.depth", "5");

    try {
        InputStream in = rtfRenderer.render();
        File newFile = new File("C:\\temp\\output_generated.rtf");
        FileOutputStream out = new FileOutputStream(newFile);
        IOUtils.copy(in, out);
        System.out.println("DONE:" + newFile.getAbsolutePath());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HTMLRenderer htmlRenderer = HTMLRenderer.create(xml);
    htmlRenderer.parameter("toc.section.depth", "5");

    try {
        InputStream in = htmlRenderer.render();
        File newFile = new File("C:\\temp\\output_generated.html");
        FileOutputStream out = new FileOutputStream(newFile);
        IOUtils.copy(in, out);
        System.out.println("DONE:" + newFile.getAbsolutePath());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.efficio.fieldbook.service.FileServiceImpl.java

@Override
public String saveTemporaryFile(InputStream userFile) throws IOException {
    String tempFileName = RandomStringUtils.randomAlphanumeric(15);

    File file = null;/*from ww w  .  ja v  a2 s. c o m*/
    FileOutputStream fos = null;
    try {
        file = new File(getFilePath(tempFileName));
        file.createNewFile();
        fos = new FileOutputStream(file);
        int bytes = IOUtils.copy(userFile, fos);

    } finally {
        IOUtils.closeQuietly(fos);
    }

    return tempFileName;

}