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:com.streamsets.pipeline.stage.origin.spooldir.TestLogSpoolDirSourceApacheCustomLogFormat.java

private File createLogFile() throws Exception {
    File f = new File(createTestDir(), "test.log");
    Writer writer = new FileWriter(f);
    IOUtils.write(LINE1 + "\n", writer);
    IOUtils.write(LINE2, writer);//from  w w  w  . java  2  s . c o m
    writer.close();
    return f;
}

From source file:com.adaptris.core.services.jdbc.types.ByteArrayColumnTranslator.java

private void write(byte[] bytes, OutputStream out) throws SQLException, IOException {
    IOUtils.write(bytes, out);
}

From source file:com.netsteadfast.greenstep.util.JReportUtils.java

public static void deployReport(TbSysJreport report) throws Exception {
    String reportDeployDirName = Constants.getDeployJasperReportDir() + "/";
    File reportDeployDir = new File(reportDeployDirName);
    try {//  w  ww. j  a  v a  2 s  .c  o m
        if (!reportDeployDir.exists()) {
            logger.warn("no exists dir, force mkdir " + reportDeployDirName);
            FileUtils.forceMkdir(reportDeployDir);
        }
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage().toString());
    }
    logger.info("REPORT-ID : " + report.getReportId());
    File reportFile = null;
    File reportZipFile = null;
    OutputStream os = null;
    try {
        String reportFileFullPath = reportDeployDirName + report.getReportId() + "/" + report.getFile();
        String reportZipFileFullPath = reportDeployDirName + report.getReportId() + ".zip";
        reportZipFile = new File(reportZipFileFullPath);
        if (reportZipFile.exists()) {
            logger.warn("delete " + reportZipFileFullPath);
            FileUtils.forceDelete(reportZipFile);
        }
        os = new FileOutputStream(reportZipFile);
        IOUtils.write(report.getContent(), os);
        os.flush();
        ZipFile zipFile = new ZipFile(reportZipFileFullPath);
        zipFile.extractAll(reportDeployDirName);
        reportFile = new File(reportFileFullPath);
        if (!reportFile.exists()) {
            logger.warn("report file is missing : " + reportFileFullPath);
            return;
        }
        if (YesNo.YES.equals(report.getIsCompile()) && report.getFile().endsWith("jrxml")) {
            logger.info("compile report...");
            String outJasper = compileReportToJasperFile(new String[] { reportFileFullPath },
                    reportDeployDirName + report.getReportId() + "/");
            logger.info("out : " + outJasper);
        }
    } catch (JRException re) {
        re.printStackTrace();
        logger.error(re.getMessage().toString());
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage().toString());
    } finally {
        if (os != null) {
            os.close();
        }
        os = null;
        reportFile = null;
        reportZipFile = null;
    }
    reportDeployDir = null;
}

From source file:ch.cyberduck.core.googledrive.DriveReadFeatureTest.java

@Test
public void testReadRange() throws Exception {

    final String name = "-" + UUID.randomUUID().toString();
    final Path test = new Path(new DriveHomeFinderService(session).find(), name, EnumSet.of(Path.Type.file));
    final Local local = new Local(System.getProperty("java.io.tmpdir"), name);
    final byte[] content = new RandomStringGenerator.Builder().build().generate(1000).getBytes();
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);/*from  ww  w  .  j  av a2s  . com*/
    IOUtils.write(content, out);
    out.close();
    new DriveUploadFeature(new DriveWriteFeature(session)).upload(test, local,
            new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            new TransferStatus().length(content.length), new DisabledConnectionCallback());
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    status.setAppend(true);
    status.setOffset(100L);
    final InputStream in = new DriveReadFeature(session).read(test, status.length(content.length - 100),
            new DisabledConnectionCallback());
    assertNotNull(in);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length - 100);
    new StreamCopier(status, status).transfer(in, buffer);
    final byte[] reference = new byte[content.length - 100];
    System.arraycopy(content, 100, reference, 0, content.length - 100);
    assertArrayEquals(reference, buffer.toByteArray());
    in.close();
    new DriveDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:com.amazonaws.util.FileUtils.java

public static File generateRandomAsciiFile(long byteSize, boolean deleteOnExit) throws IOException {
    File file = File.createTempFile("CryptoTestUtils", ".txt");
    System.out.println("Generating random ASCII file with size: " + byteSize + " at " + file);
    if (deleteOnExit)
        file.deleteOnExit();//  w  w w  .  j  a  v  a 2 s.  co  m
    OutputStream out = new FileOutputStream(file);
    int BUFSIZE = 1024 * 8;
    byte[] buf = new byte[1024 * 8];
    long counts = byteSize / BUFSIZE;
    try {
        while (counts-- > 0) {
            IOUtils.write(fillRandomAscii(buf), out);
        }
        int remainder = (int) byteSize % BUFSIZE;
        if (remainder > 0) {
            buf = new byte[remainder];
            IOUtils.write(fillRandomAscii(buf), out);
        }
    } finally {
        out.close();
    }
    return file;
}

From source file:com.github.tteofili.p2h.DataSplitTest.java

@Ignore
@Test/*from   w  w  w . j a v a 2 s. co m*/
public void testDataSplit() throws Exception {
    String regex = "\\n\\d(\\.\\d)*\\.?\\u0020[\\w|\\-|\\|\\:]+(\\u0020[\\w|\\-|\\:|\\]+){0,10}\\n";
    String prefix = "/path/to/h2v/";
    Pattern pattern = Pattern.compile(regex);
    Path path = Paths.get(getClass().getResource("/papers/raw/").getFile());
    File file = path.toFile();
    if (file.exists() && file.list() != null) {
        for (File doc : file.listFiles()) {
            String s = IOUtils.toString(new FileInputStream(doc));
            String docName = doc.getName();
            File fileDir = new File(prefix + docName);
            assert fileDir.mkdir();
            Matcher matcher = pattern.matcher(s);
            int start = 0;
            String sectionName = "abstract";
            while (matcher.find(start)) {
                String string = matcher.group(0);
                if (isValid(string)) {

                    String content;

                    if (start == 0) {
                        // abstract
                        content = s.substring(0, matcher.start());
                    } else {
                        content = s.substring(start, matcher.start());
                    }

                    File f = new File(prefix + docName + "/" + docName + "_" + sectionName);
                    assert f.createNewFile() : "could not create file" + f.getAbsolutePath();
                    FileOutputStream outputStream = new FileOutputStream(f);
                    IOUtils.write(content, outputStream);

                    start = matcher.end();
                    sectionName = string.replaceAll("\n", "").trim();
                } else {
                    start = matcher.end();
                }
            }
            // remaining
            File f = new File(prefix + docName + "/" + docName + "_" + sectionName);
            assert f.createNewFile();
            FileOutputStream outputStream = new FileOutputStream(f);

            IOUtils.write(s.substring(start), outputStream);
        }
    }
}

From source file:com.t3.image.ThumbnailManager.java

private Image createThumbnail(File file) throws IOException {

    // Gather info
    File thumbnailFile = getThumbnailFile(file);
    if (thumbnailFile.exists()) {
        return ImageUtil.getImage(thumbnailFile);
    }//from   ww  w .  ja v a2  s . c  o  m

    Image image = ImageUtil.getImage(file);

    // Should we bother making a thumbnail ?
    if (file.length() < 30 * 1024) {
        return image;
    }

    // Transform the image
    Dimension imgSize = new Dimension(image.getWidth(null), image.getHeight(null));
    SwingUtil.constrainTo(imgSize, thumbnailSize.width, thumbnailSize.height);

    BufferedImage thumbnailImage = new BufferedImage(imgSize.width, imgSize.height,
            ImageUtil.pickBestTransparency(image));

    Graphics2D g = thumbnailImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.drawImage(image, 0, 0, imgSize.width, imgSize.height, null);
    g.dispose();

    // Ensure path exists
    if (thumbnailFile.exists())
        thumbnailFile.delete();
    else
        thumbnailFile.getParentFile().mkdirs();

    try (OutputStream os = new FileOutputStream(thumbnailFile)) {
        IOUtils.write(ImageUtil.imageToBytes(thumbnailImage, "png"), os);
    }

    return thumbnailImage;
}

From source file:ch.cyberduck.core.SingleTransferWorkerTest.java

@Test
public void testTransferredSizeRepeat() throws Exception {
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = new byte[62768];
    new Random().nextBytes(content);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);
    out.close();//from  w  w  w  .j ava  2 s  . c  o m
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("webdav.user"),
                    System.getProperties().getProperty("webdav.password")));
    host.setDefaultPath("/dav/basic");
    final AtomicBoolean failed = new AtomicBoolean();
    final DAVSession session = new DAVSession(host) {
        final DAVUploadFeature upload = new DAVUploadFeature(this) {
            @Override
            protected InputStream decorate(final InputStream in, final MessageDigest digest)
                    throws IOException {
                if (failed.get()) {
                    // Second attempt successful
                    return in;
                }
                return new CountingInputStream(in) {
                    @Override
                    protected void beforeRead(final int n) throws IOException {
                        super.beforeRead(n);
                        if (this.getByteCount() >= 32768L) {
                            failed.set(true);
                            throw new SocketTimeoutException();
                        }
                    }
                };
            }
        };

        @Override
        @SuppressWarnings("unchecked")
        public <T> T getFeature(final Class<T> type) {
            if (type == Upload.class) {
                return (T) upload;
            }
            return super.getFeature(type);
        }
    };
    session.open(new DisabledHostKeyCallback(), new DisabledTranscriptListener());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path test = new Path(new DefaultHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    final Transfer t = new UploadTransfer(new Host(new TestProtocol()), test, local);
    final BytecountStreamListener counter = new BytecountStreamListener(new DisabledStreamListener());
    assertTrue(new SingleTransferWorker(session, t, new TransferOptions(), new TransferSpeedometer(t),
            new DisabledTransferPrompt() {
                @Override
                public TransferAction prompt(final TransferItem file) {
                    return TransferAction.overwrite;
                }
            }, new DisabledTransferErrorCallback(), new DisabledTransferItemCallback(),
            new DisabledProgressListener(), counter, new DisabledLoginCallback(), TransferItemCache.empty()) {

    }.run(session));
    local.delete();
    assertEquals(62768L, counter.getSent(), 0L);
    assertEquals(62768L, new DAVAttributesFeature(session).find(test).getSize());
    assertTrue(failed.get());
    new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
}

From source file:at.tfr.securefs.process.ProcessFilesTest.java

@Test
public void testCopyFile() throws Exception {

    // Given: the target directory, the source file
    toFilesPath = Files.createDirectories(toRoot.resolve(DATA_FILES));
    final String data = "Hallo Echo";
    try (OutputStream os = cp.getEncrypter(fromFile)) {
        IOUtils.write(data, os);
    }/*from  w ww .j  a v  a  2s. c o  m*/

    ProcessFilesData cfd = new ProcessFilesData().setFromRootPath(fromRoot.toString())
            .setToRootPath(toRoot.toString()).setUpdate(false).setProcessActive(true);

    // When: copy of source file to toRoot
    ProcessFilesBean pf = new ProcessFilesBean(new MockSecureFsCache());
    pf.copy(fromFile, fromRoot.getNameCount(), toRoot, cp, newSecret, cfd);

    // Then: a target file is created in same subpath like sourceFile:
    Assert.assertTrue(Files.exists(targetToFile));

    // Then: the content of target file is decryptable with newSecret 
    //    and equals content of source file
    byte[] buf = new byte[data.getBytes().length];
    try (InputStream is = cp.getDecrypter(targetToFile, newSecret)) {
        IOUtils.read(is, buf);
    }
    Assert.assertEquals("failed to decrypt data", data, String.valueOf(data));
}

From source file:be.fedict.eid.dss.document.zip.ZIPSignatureOutputStream.java

@Override
public void close() throws IOException {
    super.close();

    byte[] signatureData = toByteArray();

    /*//w w  w  . ja v a2 s.co  m
     * Copy the original ZIP content.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
            zipOutputStream.putNextEntry(newZipEntry);
            LOG.debug("copying " + zipEntry.getName());
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();

    /*
     * Add the XML signature file to the ZIP package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    LOG.debug("writing " + zipEntry.getName());
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}