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:inti.ws.spring.resource.WebResource.java

public void update() throws Exception {
    StringBuilder builder = new StringBuilder(32);
    MessageDigest digest = DIGESTS.get();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    InputStream inputStream = resource.getInputStream();

    try {//  w  w  w  .j a va 2  s . co m
        lastModified = resource.lastModified();
        IOUtils.copyLarge(inputStream, outputStream);
        compressedFile = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
    } finally {
        inputStream.close();
    }

    if (minify) {
        compressedFile = minifier.minify(compressedFile);
    }

    digest.reset();
    builder.append(Hex.encodeHexString(digest.digest(compressedFile.getBytes(StandardCharsets.UTF_8))));
    messageDigest = builder.toString();
    builder.delete(0, builder.length());

    DATE_FORMATTER.formatDate(lastModified, builder);
    lastModifiedString = builder.toString();
    bytes = null;
}

From source file:ch.cyberduck.core.onedrive.OneDriveWriteFeatureTest.java

@Test
public void testWriteUmlaut() throws Exception {
    final OneDriveWriteFeature feature = new OneDriveWriteFeature(session);
    final Path container = new OneDriveHomeFinderFeature(session).find();
    final byte[] content = RandomUtils.nextBytes(2048);
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);// w ww.  ja v  a  2s .  c  om
    final Path file = new Path(container, String.format("%s", new AlphanumericRandomStringService().random()),
            EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    assertEquals(content.length, IOUtils.copyLarge(in, out));
    in.close();
    out.close();
    assertNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new OneDriveReadFeature(session).read(file,
            new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new OneDriveDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:cn.lhfei.fu.service.impl.ThesisBaseServiceImpl.java

@Override
public boolean update(ThesisBaseModel model, String userType) throws Exception {
    OutputStream out = null;/*from  w ww  .  java2 s .  c  o m*/
    BufferedOutputStream bf = null;
    Date currentTime = new Date();

    boolean result = false;
    List<MultipartFile> files = model.getFiles();

    try {

        boolean modelIsValid = this.updateThesis(model);

        if (!modelIsValid) {
            return result;
        }

        int num = 1;
        for (MultipartFile file : files) {// save archive file

            if (file.getSize() > 0) {
                String filePath = filePathBuilder.buildThesisFullPath(model, model.getStudentName());
                String fileName = filePathBuilder.buildThesisFileName(model, model.getStudentName(), num);

                String[] names = file.getOriginalFilename().split("[.]");

                String fileType = names[names.length - 1];

                String fullPath = filePath + File.separator + fileName + "." + fileType;

                out = new FileOutputStream(new File(fullPath));

                bf = new BufferedOutputStream(out);

                IOUtils.copyLarge(file.getInputStream(), bf);

                ThesisArchive archive = new ThesisArchive();
                archive.setThesisBaseId(model.getBaseId());
                archive.setStudentId(model.getStudentId());
                archive.setArchiveName(fileName);
                archive.setArchivePath(fullPath);
                archive.setCreateTime(currentTime);
                archive.setModifyTime(currentTime);
                archive.setStudentBaseId(model.getStudentBaseId());
                archive.setThesisTitle(model.getThesisTitle());
                archive.setExtend(model.getThesisEnTitle()); // 
                archive.setExtend1(model.getThesisType()); // 

                // ?
                if (userType != null && userType.equals(UserTypeEnum.STUDENT.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.DSH.getCode());
                } else if (userType != null && userType.equals(UserTypeEnum.TEACHER.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.DSH.getCode());
                } else if (userType != null && userType.equals(UserTypeEnum.ADMIN.getCode())) {
                    archive.setStatus("" + ApproveStatusEnum.YSH.getCode());
                }

                thesisArchiveDAO.save(archive);

                // auto increment archives number.
                num++;
            }
        }

        result = true;

    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new IOException(e.getMessage(), e);

    } catch (NullPointerException e) {
        log.error("File name arguments missed.", e);

        throw new NullPointerException(e.getMessage());
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (bf != null) {
            try {
                bf.flush();
                bf.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    return result;
}

From source file:herddb.upgrade.ZIPUtils.java

private static void addFileToZip(int skipprefix, File file, ZipOutputStream zipper) throws IOException {
    String raw = file.getAbsolutePath().replace("\\", "/");
    if (raw.length() == skipprefix) {
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles != null) {
                for (File child : listFiles) {
                    addFileToZip(skipprefix, child, zipper);
                }// ww w . java  2 s.c o m
            }
        }
    } else {
        String path = raw.substring(skipprefix + 1);
        if (file.isDirectory()) {
            ZipEntry entry = new ZipEntry(path);
            zipper.putNextEntry(entry);
            zipper.closeEntry();
            File[] listFiles = file.listFiles();
            if (listFiles != null) {
                for (File child : listFiles) {
                    addFileToZip(skipprefix, child, zipper);
                }
            }
        } else {
            ZipEntry entry = new ZipEntry(path);
            zipper.putNextEntry(entry);
            try (FileInputStream in = new FileInputStream(file)) {
                IOUtils.copyLarge(in, zipper);
            }
            zipper.closeEntry();
        }
    }

}

From source file:de.huxhorn.lilith.log4j.xml.Log4jImportCallableTest.java

public void createTempFile(String resourceName) throws IOException {
    InputStream input = Log4jImportCallableTest.class.getResourceAsStream(resourceName);
    if (input == null) {
        fail("Couldn't resolve resource '" + resourceName + "'!");
    }/*www. j av a2  s. c  o  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.client.plugins.outputplugin.mtomws.WsCxfIT.java

private void saveAttachment(final ResponseTransport responseTransport) throws IOException {
    final DataHandler dataHandler = responseTransport.getTransportBody().getData().getBase64CharSequence()
            .getValue();/*from   w  w w  . ja v  a 2  s  .  c o  m*/
    final File receivedFile = new File(outputDirectory,
            "tempClientInput" + DateFormatUtils.ISO_DATE_FORMAT.format(new Date()) + ".txt");

    final FileOutputStream fileOutputStream = new FileOutputStream(receivedFile);
    IOUtils.copyLarge(dataHandler.getInputStream(), fileOutputStream);
    logger.info("Attachment saved into " + receivedFile.getAbsolutePath());
}

From source file:io.druid.emitter.graphite.WhiteListBasedConverterTest.java

@Test
public void testWhiteListedStringArrayDimension() throws IOException {
    File mapFile = File.createTempFile("testing-" + System.nanoTime(), ".json");
    mapFile.deleteOnExit();/*from w w w.j  a va2 s.co  m*/

    try (OutputStream outputStream = new FileOutputStream(mapFile)) {
        IOUtils.copyLarge(getClass().getResourceAsStream("/testWhiteListedStringArrayDimension.json"),
                outputStream);
    }

    WhiteListBasedConverter converter = new WhiteListBasedConverter(prefix, false, false, false,
            mapFile.getAbsolutePath(), new DefaultObjectMapper());

    ServiceMetricEvent event = new ServiceMetricEvent.Builder().setDimension("gcName", new String[] { "g1" })
            .build(createdTime, "jvm/gc/cpu", 10).build(serviceName, hostname);

    GraphiteEvent graphiteEvent = converter.druidEventToGraphite(event);

    Assert.assertNotNull(graphiteEvent);
    Assert.assertEquals(defaultNamespace + ".g1.jvm/gc/cpu", graphiteEvent.getEventPath());
}

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

public static final long copy(final Reader input, final OutputStream output) throws IOException {
    final OutputStreamWriter writer = new OutputStreamWriter(output, UTF_8_CHARSET);

    final long length = IOUtils.copyLarge(input, writer);

    writer.flush();//  w ww.  j av a2  s  .  c  o m

    return length;
}

From source file:ddf.catalog.source.solr.ConfigurationFileProxy.java

/**
 * Writes the solr configuration files out of the bundle onto the disk. This method requires
 * that the dataDirectoryPath has been set. If the code is run in an OSGi container, it will
 * automatically have a default dataDirectory location set and will not require setting
 * dataDirectory ahead of time./*  w  w w  .  j  a va 2 s.  com*/
 */
public void writeBundleFilesTo(File configDir) {
    if (bundleContext != null && configDir != null) {

        boolean directoriesMade = configDir.mkdirs();

        LOGGER.info("Solr Config directories made?  " + directoriesMade);

        @SuppressWarnings("rawtypes")
        Enumeration entries = bundleContext.getBundle().findEntries(SOLR_CONFIG_LOCATION_IN_BUNDLE, "*.*",
                false);

        while (entries.hasMoreElements()) {
            URL resourceURL = (URL) (entries.nextElement());
            LOGGER.debug("Found " + resourceURL);

            InputStream inputStream = null;
            try {
                inputStream = resourceURL.openStream();

                String fileName = FilenameUtils.getName(resourceURL.getPath());

                File currentFile = new File(configDir, fileName);

                if (!currentFile.exists()) {
                    FileOutputStream outputStream = null;

                    try {
                        outputStream = new FileOutputStream(currentFile);

                        long byteCount = IOUtils.copyLarge(inputStream, outputStream);

                        LOGGER.debug("Wrote out " + byteCount + " bytes.");

                    } finally {
                        IOUtils.closeQuietly(outputStream);
                    }
                }

            } catch (IOException e) {
                LOGGER.warn(e);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }

        }
    }
}

From source file:io.druid.emitter.ambari.metrics.WhiteListBasedDruidToTimelineEventConverterTest.java

@Test
public void testWhiteListedStringArrayDimension() throws IOException {
    File mapFile = File.createTempFile("testing-" + System.nanoTime(), ".json");
    mapFile.deleteOnExit();//from  w ww  .j a va2  s .  com

    try (OutputStream outputStream = new FileOutputStream(mapFile)) {
        IOUtils.copyLarge(getClass().getResourceAsStream("/testWhiteListedStringArrayDimension.json"),
                outputStream);
    }

    WhiteListBasedDruidToTimelineEventConverter converter = new WhiteListBasedDruidToTimelineEventConverter(
            prefix, "druid", mapFile.getAbsolutePath(), new DefaultObjectMapper());

    ServiceMetricEvent event = new ServiceMetricEvent.Builder().setDimension("gcName", new String[] { "g1" })
            .build(createdTime, "jvm/gc/cpu", 10).build(serviceName, hostname);

    TimelineMetric metric = converter.druidEventToTimelineMetric(event);

    Assert.assertNotNull(metric);
    Assert.assertEquals(defaultNamespace + ".g1.jvm/gc/cpu", metric.getMetricName());
}