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:eu.peppol.as2.evidence.TransmissionEvidenceTransformerAs2WithRemImplTest.java

@Test
public void loadTransmissionEvidenceTransformerInstance() throws Exception {

    TransmissionEvidenceTransformer transformer = TransmissionEvidenceTransformerAs2WithRemImpl.INSTANCE;

    assertNotNull(transformer);//from ww  w.  j  av a2  s .c  o  m

    TransmissionEvidence sample = sampleTransmissionEvidenceGenerator
            .createSampleTransmissionEvidenceWithRemAndMdn();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    IOUtils.copy(transformer.getInputStream(sample), outputStream);

    System.out.println(outputStream.toString("UTF-8"));

    java.security.cert.X509Certificate x509Certificate = XmldsigVerifier
            .verify(DomUtils.parse(new ByteArrayInputStream(outputStream.toByteArray())));
}

From source file:com.github.ipaas.ideploy.agent.util.ZipUtil.java

/**
 * /*w w  w. j  a  v  a2  s . c om*/
 * @param srcFile  ?
 * @param targetDir 
 * @throws Exception
 */
public static void unZip(String zipFile, String targetDir) throws Exception {
    ZipFile zipfile = new ZipFile(zipFile);
    try {
        Enumeration<ZipEntry> entries = zipfile.getEntries();
        if (entries == null || !entries.hasMoreElements()) {
            return;
        }
        //  
        FileUtils.forceMkdir(new File(targetDir));

        // ??

        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            String fname = zipEntry.getName();

            // 

            if (zipEntry.isDirectory()) {
                String fpath = FilenameUtils.normalize(targetDir + "/" + fname);
                FileUtils.forceMkdir(new File(fpath));
                continue;

            }
            // ?

            if (StringUtils.contains(fname, "/")) {
                String tpath = StringUtils.substringBeforeLast(fname, "/");
                String fpath = FilenameUtils.normalize(targetDir + "/" + tpath);
                FileUtils.forceMkdir(new File(fpath));
            }
            // ? 
            InputStream input = null;
            OutputStream output = null;

            try {
                input = zipfile.getInputStream(zipEntry);
                String file = FilenameUtils.normalize(targetDir + "/" + fname);
                output = new FileOutputStream(file);
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }
        }
    } finally {
        ZipFile.closeQuietly(zipfile);
    }

}

From source file:com.lushapp.common.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String displayName,
        byte[] bytes) throws IOException {

    if (ArrayUtils.isEmpty(bytes)) {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("??");
        return;//ww w .ja  va2 s .co m
    }

    response.reset();
    WebUtils.setNoCacheHeader(response);

    response.setContentType("application/x-download");
    response.setContentLength((int) bytes.length);

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    WebUtils.setDownloadableHeader(request, response, displayFilename);
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new ByteArrayInputStream(bytes));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:de.knurt.fam.service.pdf.handler.FamServicePDFHandler.java

@RequestMapping(value = "/generated.pdf", method = RequestMethod.POST)
public final ModelAndView generatePDF(HttpServletResponse response, HttpServletRequest request) {
    ServletOutputStream output = null;//from  www  .java  2  s.co m
    FileInputStream input = null;
    try {
        File file2write = new HttpServletRequest2File().process(request);
        input = new FileInputStream(file2write);
        output = response.getOutputStream();

        response.setContentType("application/pdf;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + file2write.getName());

        int nob = IOUtils.copy(input, output);
        if (nob < 1) {
            Logger.getRootLogger().fatal("201204231353");
        }
    } catch (IOException ex) {
        Logger.getRootLogger().fatal("201105301032");
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }
    return null;
}

From source file:com.nzion.web.PdfServlet.java

@Override
protected void service(HttpServletRequest reqqest, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/plm");
    response.setHeader("Content-Disposition", "attachment; filename=2D.plm");
    ServletOutputStream outputStream = response.getOutputStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(
            new FileInputStream(new File("F:\\PDF_Stamping\\2D\\2D.zip")));
    IOUtils.copy(bufferedInputStream, outputStream);
    bufferedInputStream.close();//from w w  w .  ja  v  a2 s.  c  o  m
    outputStream.flush();
}

From source file:mitm.application.djigzo.backup.TestBackupDriver.java

@Override
public void writeBackup(String filename, InputStream backup) throws BackupException {
    File file = new File(tempDir, filename);

    try {/*www .  j a v a2s.c o  m*/
        IOUtils.copy(backup, new FileOutputStream(file));
    } catch (FileNotFoundException e) {
        throw new BackupException(e);
    } catch (IOException e) {
        throw new BackupException(e);
    }
}

From source file:net.landora.video.playerbackends.GenericPlayerBackend.java

@Override
public void playFile(File file) {
    try {//  w w w.  j  ava 2s .  c om
        List<String> args = new ArrayList<String>();
        args.add(ProgramsAddon.getInstance().getConfiguredPath(program));
        args.addAll(Arrays.asList(extraArgs));
        args.add(file.getAbsolutePath());

        ProcessBuilder process = new ProcessBuilder(args);
        process.redirectErrorStream(true);
        Process p = process.start();

        StringWriter buffer = new StringWriter();
        IOUtils.copy(p.getInputStream(), buffer);
        p.waitFor();

    } catch (Exception e) {
        log.error("Error playing file with " + program.getName() + ": " + file, e);
    }
}

From source file:cltestgrid.GetBlob2.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String userAgent = req.getHeader("User-Agent");
    if (userAgent != null && userAgent.contains("Baiduspider")) {
        resp.setStatus(SC_MOVED_PERMANENTLY);
        resp.setHeader("Location", "http://www.baidu.com/search/spider.html");
        resp.setHeader("X-READ-ME",
                "Please honor robots.txt and don't waste our resources. http://cl-test-grid.appspot.com/robots.txt");
        return;/* w w w .j  a v  a2s.c om*/
    }

    final String key = req.getParameter("key");
    GcsFilename filename = new GcsFilename("cl-test-grid-logs", key);
    GcsInputChannel readChannel = null;
    InputStream inputStream = null;
    try {
        final boolean lock = false;
        //readChannel = FileServiceFactory.getFileService().openReadChannel(file, lock);
        readChannel = GcsServiceFactory.createGcsService().openReadChannel(filename, 0);
        inputStream = Channels.newInputStream(readChannel);
        resp.setContentType("text/plain");
        // The log files are gzipped, but the Cloud Storage Client Library ungzips them automatically.
        // After we return this data, GAE gzips our output in case client accepts 'gzip' contect encoding.
        IOUtils.copy(new BufferedInputStream(inputStream, 100 * 1024), resp.getOutputStream());
        resp.getOutputStream().flush();
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(readChannel);
    }
}

From source file:de.iai.ilcd.services.PostResourceHelper.java

public Response importByFileUpload(DataSetType type, InputStream fileInputStream, RootDataStock rds) {

    String tempFileName = ConfigurationService.INSTANCE.getUniqueUploadFileName("IMPORT", "xml");

    try { // we have to copy the uploaded file to a temporary space first; maybe later we find a better solution
        FileOutputStream fos = new FileOutputStream(tempFileName);
        IOUtils.copy(fileInputStream, fos);
        fileInputStream.close();/*www. ja  v a  2s .  co m*/
        fos.close();
    } catch (IOException e) {
        logger.error("Cannot save an uploaded file to temporary storage");
        logger.error("exception is: ", e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity("Cannot save uploaded file to temporary storage").build();
    }

    DataSetImporter importer = new DataSetImporter();
    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);

    try {
        if (importer.importFile(type, tempFileName, out, rds) == true) {
            logger.info("data set successfully imported.");
            logger.info("{}", writer.getBuffer());
            out.println("data set successfully imported.");
            out.flush();
            return Response.ok(writer.getBuffer().toString(), MediaType.TEXT_PLAIN).build();
        } else {
            logger.error("Cannot import data set");
            logger.error("output is: {}", writer.getBuffer());
            return Response.status(Response.Status.NOT_ACCEPTABLE).type(MediaType.TEXT_PLAIN)
                    .entity(writer.getBuffer().toString()).build();
        }
    } catch (Exception e) {
        logger.error("cannot import data set");
        logger.error("exception is: ", e);
        return Response.status(Response.Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN)
                .entity(writer.getBuffer().toString()).build();
    }
}

From source file:br.com.autonomiccs.autonomic.plugin.common.utils.ShellCommandUtils.java

/**
 * It executes the specified shell command and wait for the
 * end of command execution to continue with the application
 * flow./*from ww  w .  j  a  v a  2 s  .  com*/
 *
 * If an exception happens, it will get logged and the flow of execution continues.
 * This method will not break the flow of execution if an expected exception happens.
 *
 * @param command
 *            The command that will be executed.
 * @return
 *         A <code>String</code> that is the result from
 *         command executed.
 */
public String executeCommand(String command) {
    Writer output = new StringWriter();
    try {
        Process p = Runtime.getRuntime().exec(command);
        p.waitFor();
        IOUtils.copy(p.getInputStream(), output);
    } catch (IOException | InterruptedException e) {
        logger.error(String.format("An error happened while executing command[%s]", command), e);
    }
    return output.toString();
}