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:deployer.TestUtils.java

public static ByteBuffer createSampleAppTarBall(ArtifactType type) throws IOException, ArchiveException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(8096);
    CompressorOutputStream gzs = new GzipCompressorOutputStream(bos);
    ArchiveOutputStream aos = new TarArchiveOutputStream(gzs);
    {//w  w w  .  j  a  v  a 2  s  .c om
        TarArchiveEntry nextEntry = new TarArchiveEntry(CONFIG_DIRECTORY + "/app.conf");
        byte[] sampleConf = SAMPLE_CONF_DATA.getBytes();
        nextEntry.setSize(sampleConf.length);
        aos.putArchiveEntry(nextEntry);
        IOUtils.write(sampleConf, aos);
        aos.closeArchiveEntry();
    }
    if (type != ArtifactType.WebApp) {
        TarArchiveEntry nextEntry = new TarArchiveEntry("bin/myApplication.jar");
        byte[] jarData = SAMPLE_JAR_DATA.getBytes();
        nextEntry.setSize(jarData.length);
        aos.putArchiveEntry(nextEntry);
        IOUtils.write(jarData, aos);
        aos.closeArchiveEntry();
    } else {
        TarArchiveEntry nextEntry = new TarArchiveEntry("deployments/ROOT.war");
        byte[] jarData = SAMPLE_JAR_DATA.getBytes();
        nextEntry.setSize(jarData.length);
        aos.putArchiveEntry(nextEntry);
        IOUtils.write(jarData, aos);
        aos.closeArchiveEntry();
    }
    aos.finish();
    gzs.close();
    bos.flush();
    return ByteBuffer.wrap(bos.toByteArray());
}

From source file:ee.ria.xroad.signer.console.Utils.java

static void base64ToFile(String file, byte[] bytes) throws Exception {
    try (FileOutputStream out = new FileOutputStream(file)) {
        IOUtils.write(encodeBase64(bytes), out);

        System.out.println("Saved to file " + file);
    } catch (Exception e) {
        System.out.println("ERROR: Cannot save to file " + file + ":" + e);
    }/*from w ww .j a  v  a  2  s  . c o m*/
}

From source file:com.tc.object.config.ConfigInfoFromL2Test.java

private void writeConfigFile(String fileContents) {
    try {/* ww w.  j a v  a 2 s. c  om*/
        FileOutputStream out = new FileOutputStream(tcConfig);
        IOUtils.write(fileContents, out);
        out.close();
    } catch (Exception e) {
        throw Assert.failure("Can't create config file", e);
    }
}

From source file:hudson.plugins.sonar.SonarBuildWrapperTest.java

@Test
public void maskAuthToken() throws IOException, InterruptedException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    configureSonar(new SonarInstallation("local", "http://localhost:9001", SQServerVersions.SQ_5_3_OR_HIGHER,
            "mytoken", null, null, null, null, null, new TriggersConfig(), "$SONAR_CONFIG_NAME", null, null));

    OutputStream os = wrapper.decorateLogger(mock(AbstractBuild.class), bos);
    IOUtils.write("test sonar\ntest mytoken\n", os);
    assertThat(new String(bos.toByteArray())).isEqualTo("test sonar\ntest ******\n");
}

From source file:ch.cyberduck.core.b2.B2LargeUploadServiceTest.java

@Test
public void testAppendNoPartCompleted() 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"))));
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path test = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final int length = 102 * 1024 * 1024;
    final byte[] content = RandomUtils.nextBytes(length);
    IOUtils.write(content, local.getOutputStream(false));
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);//  w ww.ja  v  a  2s .c o m
    final AtomicBoolean interrupt = new AtomicBoolean();
    final B2LargeUploadService service = new B2LargeUploadService(session, new B2WriteFeature(session),
            100 * 1024L * 1024L, 1);
    try {
        service.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
                new DisabledStreamListener() {
                    long count;

                    @Override
                    public void sent(final long bytes) {
                        count += bytes;
                        if (count >= 5 * 1024L * 1024L) {
                            throw new RuntimeException();
                        }
                    }
                }, status, new DisabledLoginCallback());
    } catch (BackgroundException e) {
        // Expected
        interrupt.set(true);
    }
    assertTrue(interrupt.get());
    assertEquals(0L, status.getOffset(), 0L);
    assertFalse(status.isComplete());

    final TransferStatus append = new TransferStatus().append(true).length(content.length);
    service.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
            new DisabledStreamListener(), append, new DisabledLoginCallback());
    assertTrue(new B2FindFeature(session).find(test));
    assertEquals(content.length, new B2AttributesFinderFeature(session).find(test).getSize());
    assertEquals(content.length, append.getOffset(), 0L);
    assertTrue(append.isComplete());
    final byte[] buffer = new byte[content.length];
    final InputStream in = new B2ReadFeature(session).read(test, new TransferStatus(),
            new DisabledConnectionCallback());
    IOUtils.readFully(in, buffer);
    in.close();
    assertArrayEquals(content, buffer);
    new B2DeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    local.delete();
    session.close();
}

From source file:ch.cyberduck.core.spectra.SpectraUploadFeatureTest.java

@Test
public void testUploadMultipleFiles() throws Exception {
    final Host host = new Host(new SpectraProtocol() {
        @Override//from ww w . j av  a  2  s .c  o  m
        public Scheme getScheme() {
            return Scheme.http;
        }
    }, System.getProperties().getProperty("spectra.hostname"),
            Integer.valueOf(System.getProperties().getProperty("spectra.port")),
            new Credentials(System.getProperties().getProperty("spectra.user"),
                    System.getProperties().getProperty("spectra.key")));
    final SpectraSession session = new SpectraSession(host, new DisabledX509TrustManager(),
            new DefaultX509KeyManager());
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Local local1 = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final TransferStatus status1;
    {
        final int length = 32770;
        final byte[] content = RandomUtils.nextBytes(length);
        final OutputStream out = local1.getOutputStream(false);
        IOUtils.write(content, out);
        out.close();
        status1 = new TransferStatus().length(content.length);
    }
    final Local local2 = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final TransferStatus status2;
    {
        final int length = 32770;
        final byte[] content = RandomUtils.nextBytes(length);
        final OutputStream out = local2.getOutputStream(false);
        IOUtils.write(content, out);
        out.close();
        status2 = new TransferStatus().length(content.length);
    }
    final Path container = new Path("cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path test1 = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final Path test2 = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final SpectraBulkService bulk = new SpectraBulkService(session);
    final HashMap<Path, TransferStatus> files = new HashMap<>();
    files.put(test1, status1);
    files.put(test2, status2);
    bulk.pre(Transfer.Type.upload, files, new DisabledConnectionCallback());
    final SpectraUploadFeature upload = new SpectraUploadFeature(new SpectraWriteFeature(session),
            new SpectraBulkService(session));
    upload.upload(test1, local1, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
            new DisabledStreamListener(), status1, new DisabledConnectionCallback());
    upload.upload(test2, local2, new BandwidthThrottle(BandwidthThrottle.UNLIMITED),
            new DisabledStreamListener(), status2, new DisabledConnectionCallback());
    new SpectraDeleteFeature(session).delete(Arrays.asList(test1, test2), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    local1.delete();
    local2.delete();
    session.close();
}

From source file:mitm.common.security.crl.GenerateTestCRLs.java

@Test
public void testGenerateCACRL() throws Exception {
    X509CRLBuilder crlGenerator = createX509CRLBuilder();

    Date thisDate = TestUtils.parseDate("30-Nov-2007 11:38:35 GMT");

    Date nextDate = TestUtils.parseDate("30-Nov-2027 11:38:35 GMT");

    crlGenerator.setThisUpdate(thisDate);
    crlGenerator.setNextUpdate(nextDate);
    crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/" + "valid_certificate_mitm_test_ca.cer");
    assertNotNull(certificate);/*w w w .  j  a  va 2s. com*/

    crlGenerator.addCRLEntry(certificate.getSerialNumber(), thisDate, CRLReason.privilegeWithdrawn);

    X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(caPrivateKey, caCertificate));

    assertEquals("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL",
            crl.getIssuerX500Principal().toString());
    assertEquals(thisDate, crl.getThisUpdate());
    assertEquals(nextDate, crl.getNextUpdate());
    assertEquals(1, crl.getRevokedCertificates().size());
    assertTrue(crl.isRevoked(certificate));

    File crlFile = new File("test/tmp/test-generate-ca.crl");

    FileOutputStream fos = new FileOutputStream(crlFile);

    IOUtils.write(crl.getEncoded(), fos);

    fos.close();
}

From source file:com.igormaznitsa.mindmap.plugins.exporters.PNGImageExporter.java

@Override
public void doExport(@Nonnull final MindMapPanel panel, @Nullable final JComponent options,
        @Nullable final OutputStream out) throws IOException {
    for (final Component compo : Assertions.assertNotNull(options).getComponents()) {
        if (compo instanceof JCheckBox) {
            final JCheckBox cb = (JCheckBox) compo;
            if ("unfold".equalsIgnoreCase(cb.getActionCommand())) {
                flagExpandAllNodes = cb.isSelected();
            } else if ("back".equalsIgnoreCase(cb.getActionCommand())) {
                flagSaveBackground = cb.isSelected();
            }//from  w ww .jav a 2s.co m
        }
    }

    final MindMapPanelConfig newConfig = new MindMapPanelConfig(panel.getConfiguration(), false);
    newConfig.setDrawBackground(flagSaveBackground);
    newConfig.setScale(1.0f);

    final RenderedImage image = MindMapPanel.renderMindMapAsImage(panel.getModel(), newConfig,
            flagExpandAllNodes);

    if (image == null) {
        if (out == null) {
            LOGGER.error("Can't render map as image");
            panel.getController().getDialogProvider(panel)
                    .msgError(Texts.getString("PNGImageExporter.msgErrorDuringRendering"));
            return;
        } else {
            throw new IOException("Can't render image");
        }
    }

    final ByteArrayOutputStream buff = new ByteArrayOutputStream(128000);
    ImageIO.write(image, "png", buff);//NOI18N

    final byte[] imageData = buff.toByteArray();

    File fileToSaveMap = null;
    OutputStream theOut = out;
    if (theOut == null) {
        fileToSaveMap = MindMapUtils.selectFileToSaveForFileFilter(panel,
                Texts.getString("PNGImageExporter.saveDialogTitle"), ".png",
                Texts.getString("PNGImageExporter.filterDescription"),
                Texts.getString("PNGImageExporter.approveButtonText"));
        fileToSaveMap = MindMapUtils.checkFileAndExtension(panel, fileToSaveMap, ".png");//NOI18N
        theOut = fileToSaveMap == null ? null
                : new BufferedOutputStream(new FileOutputStream(fileToSaveMap, false));
    }
    if (theOut != null) {
        try {
            IOUtils.write(imageData, theOut);
        } finally {
            if (fileToSaveMap != null) {
                IOUtils.closeQuietly(theOut);
            }
        }
    }
}

From source file:com.seleniumtests.util.FileUtility.java

/**
 * Create a zip file from list of files to a temp directory. They will be added at the root of zip file
 * @param files/*from ww w .  j a  v  a  2  s.  c om*/
 * @return the zipped file
 * @throws IOException
 */
public static File createZipArchiveFromFiles(List<File> files) throws IOException {
    final File zipArchive = File.createTempFile("temp_zip_", ".zip");
    try (final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipArchive))) {
        for (File f : files) {
            if (!f.exists()) {
                logger.warn(String.format("File %s does not exist", f.getName()));
                continue;
            }
            ZipEntry e = new ZipEntry(f.getName());
            out.putNextEntry(e);
            IOUtils.write(FileUtils.readFileToByteArray(f), out);
            out.closeEntry();
        }
    }
    return zipArchive;
}

From source file:ee.ria.xroad.common.conf.globalconf.GenerateTestData.java

static String hash(byte[] content) throws Exception {
    DigestCalculator dc = createDigestCalculator("SHA-512");
    IOUtils.write(content, dc.getOutputStream());

    return encodeBase64(dc.getDigest());
}