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

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

Introduction

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

Prototype

public static long copyLarge(Reader input, Writer output) throws IOException 

Source Link

Document

Copy chars from a large (over 2GB) Reader to a Writer.

Usage

From source file:edu.uci.ics.hyracks.control.cc.web.ApplicationInstallationHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {//from   www. j  a v a  2s.com
        while (target.startsWith("/")) {
            target = target.substring(1);
        }
        while (target.endsWith("/")) {
            target = target.substring(0, target.length() - 1);
        }
        String[] parts = target.split("/");
        if (parts.length != 1) {
            return;
        }
        final String[] params = parts[0].split("&");
        String deployIdString = params[0];
        String rootDir = ccs.getServerContext().getBaseDir().toString();
        final String deploymentDir = rootDir.endsWith(File.separator)
                ? rootDir + "applications/" + deployIdString
                : rootDir + File.separator + "/applications/" + File.separator + deployIdString;
        if (HttpMethods.PUT.equals(request.getMethod())) {
            class OutputStreamGetter extends SynchronizableWork {
                private OutputStream os;

                @Override
                protected void doRun() throws Exception {
                    FileUtils.forceMkdir(new File(deploymentDir));
                    String fileName = params[1];
                    File jarFile = new File(deploymentDir, fileName);
                    os = new FileOutputStream(jarFile);
                }
            }
            OutputStreamGetter r = new OutputStreamGetter();
            try {
                ccs.getWorkQueue().scheduleAndSync(r);
            } catch (Exception e) {
                throw new IOException(e);
            }
            try {
                IOUtils.copyLarge(request.getInputStream(), r.os);
            } finally {
                r.os.close();
            }
        } else if (HttpMethods.GET.equals(request.getMethod())) {
            class InputStreamGetter extends SynchronizableWork {
                private InputStream is;

                @Override
                protected void doRun() throws Exception {
                    String fileName = params[1];
                    File jarFile = new File(deploymentDir, fileName);
                    is = new FileInputStream(jarFile);
                }
            }
            InputStreamGetter r = new InputStreamGetter();
            try {
                ccs.getWorkQueue().scheduleAndSync(r);
            } catch (Exception e) {
                throw new IOException(e);
            }
            if (r.is == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            } else {
                response.setContentType("application/octet-stream");
                response.setStatus(HttpServletResponse.SC_OK);
                try {
                    IOUtils.copyLarge(r.is, response.getOutputStream());
                } finally {
                    r.is.close();
                }
            }
        }
        baseRequest.setHandled(true);
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:de.huxhorn.lilith.jul.xml.JulImportCallableTest.java

public void createTempFile(String resourceName) throws IOException {
    InputStream input = JulImportCallableTest.class.getResourceAsStream(resourceName);
    if (input == null) {
        fail("Couldn't resolve resource '" + resourceName + "'!");
    }/*from w  ww. j av  a 2 s. co m*/
    inputFile = File.createTempFile("Import", "test");
    inputFile.delete();
    FileOutputStream output = new FileOutputStream(inputFile);
    IOUtils.copyLarge(input, output);
    IOUtilities.closeQuietly(output);
}

From source file:de.extra_standard.namespace.webservice.ExtraServiceImpl.java

@Override
@WebMethod(action = "http://www.extra-standard.de/namespace/webservice/execute")
@WebResult(name = "Transport", targetNamespace = "http://www.extra-standard.de/namespace/response/1", partName = "response")
public ResponseTransport execute(
        @WebParam(name = "Transport", targetNamespace = "http://www.extra-standard.de/namespace/request/1", partName = "request") final de.drv.dsrv.extrastandard.namespace.request.RequestTransport request)
        throws ExtraFault {
    try {//from   w  w  w  . j a va  2  s .  c o m
        logger.info("receive Extra ResponseTransport");
        final Base64CharSequenceType base64CharSequence = request.getTransportBody().getData()
                .getBase64CharSequence();
        final DataHandler dataHandler = base64CharSequence.getValue();
        final InputStream inputStream = dataHandler.getInputStream();
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        final String dateSuffix = sdf.format(new Date(System.currentTimeMillis()));
        final String dataHandlerName = dataHandler.getName();
        logger.info("Receiving File : " + dataHandlerName);
        final File receivedFile = new File(outputDirectory, dataHandlerName + "_" + dateSuffix);
        final FileOutputStream fileOutputStream = new FileOutputStream(receivedFile);
        IOUtils.copyLarge(inputStream, fileOutputStream);
        logger.info("Input file is stored under " + receivedFile.getAbsolutePath());
        logger.info("ChecksumCRC32 " + FileUtils.checksumCRC32(receivedFile));
        logger.info("Filesize: " + FileUtils.sizeOf(receivedFile));
    } catch (final IOException e) {
        logger.error("IOException in Server:", e);
    }
    // TODO TestTransport erzeugen!!
    final ResponseTransport responseTransport = new ResponseTransport();
    final ResponseTransportBody responseTransportBody = new ResponseTransportBody();
    final DataType dataType = new DataType();
    final Base64CharSequenceType base64CharSequenceType = new Base64CharSequenceType();
    final DataSource ds = new FileDataSource(testDataFile);
    final DataHandler dataHandler = new DataHandler(ds);
    base64CharSequenceType.setValue(dataHandler);
    dataType.setBase64CharSequence(base64CharSequenceType);
    responseTransportBody.setData(dataType);
    responseTransport.setTransportBody(responseTransportBody);
    return responseTransport;
}

From source file:com.oprisnik.semdroid.utils.FileUtils.java

public static void copy(InputStream is, OutputStream os) throws IOException {
    try {//from  ww  w  .j a v  a 2s . co m
        IOUtils.copyLarge(is, os);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.RuntimeProvider.java

public void install() throws IOException {
    if (installed) {
        return;//w  w w.  j  a va  2 s .  c  o  m
    }

    Properties manifest = getManifest();
    for (String filename : manifest.stringPropertyNames()) {
        URL source = resolveLocation(baseLocation + platform + "/" + filename, this, null);
        File target = new File(getWorkspace(), filename);
        InputStream is = null;
        OutputStream os = null;
        try {
            is = source.openStream();
            os = new FileOutputStream(target);
            IOUtils.copyLarge(is, os);
        } finally {
            closeQuietly(is);
            closeQuietly(os);
        }

        if (MODE_EXECUTABLE.equals(manifest.getProperty(filename))) {
            target.setExecutable(true);
        }

        target.deleteOnExit();
    }

    installed = true;
}

From source file:gov.nih.nci.calims2.ui.report.filledreport.FilledReportController.java

/**
 * /*w w w.j  ava  2  s. c  o m*/
 * @param response The servlet response.
 * @param id The id of the filledreport to view.
 * @param formatName The format of the pdf file.
 */
@RequestMapping("/exportReport.do")
public void exportReport(HttpServletResponse response, @RequestParam("id") Long id,
        @RequestParam("format") String formatName) {

    FilledReport filledReport = getMainService().findById(FilledReport.class, id);
    Report report = filledReport.getReport();
    FilledReportFormat format = FilledReportFormat.valueOf(formatName);
    try {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        File exportedFile = ((FilledReportService) getMainService()).exportJasperReport(id, tempfiledir,
                format);
        response.setContentType(format.getContentType());
        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd-HHmmss");
        String filename = report.getName() + fmt.print(filledReport.getExecutionTime()) + format.getExtention();
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        FileInputStream fileInputStream = new FileInputStream(exportedFile);
        IOUtils.copyLarge(fileInputStream, servletOutputStream);
        IOUtils.closeQuietly(fileInputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
        exportedFile.delete();
    } catch (IOException e1) {
        throw new RuntimeException("IOException in exportReport", e1);
    } catch (ReportingException e) {
        throw new RuntimeException("ReportingException in exportReport", e);
    }
}

From source file:ch.cyberduck.core.shared.DefaultFindFeatureTest.java

@Test
public void testFindLargeUpload() 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 file = new Path(bucket, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    final StatusOutputStream<VersionId> out = new B2LargeUploadWriteFeature(session).write(file,
            new TransferStatus(), new DisabledConnectionCallback());
    IOUtils.copyLarge(new ByteArrayInputStream(RandomUtils.nextBytes(100)), out);
    out.close();// w  ww  .java 2s .  co m
    assertTrue(new DefaultFindFeature(session).find(file));
    session.close();
}

From source file:eu.planets_project.services.utils.DigitalObjectUtils.java

/**
 * @param object The digital object to copy to a file
 * @param file The file to copy the digital object's byte stream to
 * @return The number of bytes copied//from w ww .j av a2s.  c  o m
 */
public static long toFile(final DigitalObject object, final File file) {
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        long bytesCopied = IOUtils.copyLarge(object.getContent().getInputStream(), fOut);
        fOut.close();
        return bytesCopied;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}

From source file:cz.zcu.kiv.eegdatabase.logic.zip.ZipGenerator.java

public File generate(Experiment exp, MetadataCommand mc, Set<DataFile> dataFiles, byte[] licenseFile,
        String licenseFileName) throws Exception, SQLException, IOException {

    ZipOutputStream zipOutputStream = null;
    FileOutputStream fileOutputStream = null;
    File tempZipFile = null;/*from   w  w  w.j  av a  2s .  com*/

    try {
        log.debug("creating output stream");
        // create temp zip file
        tempZipFile = File.createTempFile("experimentDownload_", ".zip");
        // open stream to temp zip file
        fileOutputStream = new FileOutputStream(tempZipFile);
        // prepare zip stream
        zipOutputStream = new ZipOutputStream(fileOutputStream);

        log.debug("transforming metadata from database to xml file");
        OutputStream meta = getTransformer().transformElasticToXml(exp);
        Scenario scen = exp.getScenario();
        log.debug("getting scenario file");

        byte[] xmlMetadata = null;
        if (meta instanceof ByteArrayOutputStream) {
            xmlMetadata = ((ByteArrayOutputStream) meta).toByteArray();
        }

        ZipEntry entry;

        if (licenseFileName != null && !licenseFileName.isEmpty()) {
            zipOutputStream.putNextEntry(entry = new ZipEntry("License/" + licenseFileName));
            IOUtils.copyLarge(new ByteArrayInputStream(licenseFile), zipOutputStream);
            zipOutputStream.closeEntry();
        }

        if (mc.isScenFile() && scen.getScenarioFile() != null) {
            try {

                log.debug("saving scenario file (" + scen.getScenarioName() + ") into a zip file");
                entry = new ZipEntry("Scenario/" + scen.getScenarioName());
                zipOutputStream.putNextEntry(entry);
                IOUtils.copyLarge(scen.getScenarioFile().getBinaryStream(), zipOutputStream);
                zipOutputStream.closeEntry();

            } catch (Exception ex) {
                log.error(ex);
            }
        }

        if (xmlMetadata != null) {
            log.debug("saving xml file of metadata to zip file");
            entry = new ZipEntry(getMetadata() + ".xml");
            zipOutputStream.putNextEntry(entry);
            zipOutputStream.write(xmlMetadata);
            zipOutputStream.closeEntry();
        }

        for (DataFile dataFile : dataFiles) {
            entry = new ZipEntry(getDataZip() + "/" + dataFile.getFilename());

            if (dataFile.getFileContent().length() > 0) {

                log.debug("saving data file to zip file");

                try {

                    zipOutputStream.putNextEntry(entry);

                } catch (ZipException ex) {

                    String[] partOfName = dataFile.getFilename().split("[.]");
                    String filename;
                    if (partOfName.length < 2) {
                        filename = partOfName[0] + "" + fileCounter;
                    } else {
                        filename = partOfName[0] + "" + fileCounter + "." + partOfName[1];
                    }
                    entry = new ZipEntry(getDataZip() + "/" + filename);
                    zipOutputStream.putNextEntry(entry);
                    fileCounter++;
                }

                IOUtils.copyLarge(dataFile.getFileContent().getBinaryStream(), zipOutputStream);
                zipOutputStream.closeEntry();
            }
        }

        log.debug("returning output stream of zip file");
        return tempZipFile;

    } finally {

        zipOutputStream.flush();
        zipOutputStream.close();
        fileOutputStream.flush();
        fileOutputStream.close();
        fileCounter = 0;

    }
}

From source file:com.themodernway.server.core.io.IO.java

public static final long copy(final Reader input, final Writer output) throws IOException {
    return IOUtils.copyLarge(input, output);
}