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:ch.cyberduck.core.b2.B2ReadFeatureTest.java

@Test
public void testReadChunkedTransfer() 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 LoginConnectionService service = new LoginConnectionService(new DisabledLoginCallback(),
            new DisabledHostKeyCallback(), new DisabledPasswordStore(), new DisabledProgressListener());
    service.connect(session, PathCache.empty(), new DisabledCancelCallback());
    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final byte[] content = RandomUtils.nextBytes(923);
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);/*from   w w  w.j av a2  s.co  m*/
    status.setChecksum(new SHA1ChecksumCompute().compute(new ByteArrayInputStream(content), status));
    final HttpResponseOutputStream<BaseB2Response> out = new B2WriteFeature(session).write(file, status,
            new DisabledConnectionCallback());
    IOUtils.write(content, out);
    out.close();
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    assertEquals(-1L, local.attributes().getSize());
    new DefaultDownloadFeature(new B2ReadFeature(session)).download(file, local,
            new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            new TransferStatus() {
                @Override
                public void setLength(long length) {
                    assertEquals(923L, length);
                    // Ignore update. As with unknown length for chunked transfer
                }
            }, new DisabledLoginCallback(), new DisabledPasswordCallback());
    assertEquals(923L, local.attributes().getSize());
    new B2DeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:com.taobao.itest.tb.tfs.mock.TfsManagerXmlStoreImpl.java

/**
 * ?tfs//from   w  w  w  .  j av a 2s  . c  o m
 * 
 * @param tfsFileName
 *            tfs file name
 * @param suffix
 *            suffix
 * @param localFileName
 *            local file name
 * @return ?
 */
public boolean fetchFile(String tfsFileName, String suffix, String localFileName) {
    if (tfsStore.containsKey(tfsFileName) && tfsStore.get(tfsFileName).isSuffixSame(suffix)) {
        try {
            FileOutputStream fileInputOutput = new FileOutputStream(new File(localFileName));
            IOUtils.write(tfsStore.get(tfsFileName).getRawContent(), fileInputOutput);
            IOUtils.closeQuietly(fileInputOutput);
            return true;
        } catch (Exception ignore) {
            return false;
        }

    }
    return false;
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSUtil.java

public static void insertNeedle(FileObject root, String source, String needlePointer, String needleContent,
        ProgressHandler handler) {// w w w.  j av  a2 s  . co  m
    if (StringUtils.isEmpty(needleContent)) {
        return;
    }
    Charset charset = Charset.forName("UTF-8");
    BufferedReader reader;
    BufferedWriter writer;
    if (source.endsWith("json")) {
        needlePointer = "\"" + needlePointer + "\"";
    } else {
        needlePointer = " " + needlePointer + " ";
    }
    try {
        // temp file
        File outFile = File.createTempFile("needle", "tmp");
        // input
        FileObject sourceFileObject = root.getFileObject(source);
        if (sourceFileObject == null) {
            handler.error("Needle file", String.format("needle file '%s' not found ", source));
            return;
        }
        File sourceFile = FileUtil.toFile(sourceFileObject);
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile), charset));
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), charset));
        StringBuilder content = new StringBuilder();
        boolean contentUpdated = false;
        String thisLine;
        while ((thisLine = reader.readLine()) != null) {
            if (thisLine.contains(needlePointer)) {
                content.append(needleContent);
                contentUpdated = true;
            }
            content.append(thisLine).append("\n");
        }

        IOUtils.write(content.toString(), writer);

        try {
            reader.close();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        try {
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        if (contentUpdated) {
            sourceFile.delete();
            outFile.renameTo(sourceFile);
        } else {
            outFile.delete();
        }
    } catch (FileNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:com.elasticgrid.examples.video.MencoderEncoder.java

public File convertVideo(File original, String destName, String format, int width, int height, Integer start,
        Integer end, int vbr, int abr, int fps) throws VideoConversionException, InterruptedException {
    File videoConverted = new File(original.getParent(), destName);

    logger.log(Level.FINE, "Converting video {0} into {1} as {2} format...",
            new Object[] { original, videoConverted, format });

    String command = String.format("%s %s -ofps %d -of lavf"
            + " -ovc lavc -lavcopts vcodec=%s:vbitrate=%d:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -vf scale=%d:%d"
            + " -oac mp3lame -lameopts cbr:br=%d -srate 22050 -o %s", encoderLocation,
            original.getAbsolutePath(), fps, format, vbr, width, height, abr, videoConverted.getAbsolutePath());
    if (start != null && end != null)
        command = String.format("%s -ss %d -endpos %d", command, start, end);

    logger.info("Command is: " + command);

    // run the external conversion program
    File log = new File(videoConverted.getParent(), videoConverted.getName().replace(format, "log"));
    logger.info("Writing output into " + log.getAbsolutePath());
    FileWriter fileWriter = null;
    try {// w w w  .j a va2 s .co m
        fileWriter = enableLog ? new FileWriter(log) : null;
        logger.log(Level.FINEST, "Created log file in {0}", log);
    } catch (IOException e) {
        logger.log(Level.WARNING, "Can't open log file. Skipping...", e);
        fileWriter = null;
    }
    try {
        logger.finest(command);
        final Writer logWriter = enableLog ? new BufferedWriter(fileWriter) : null;
        final Process process = Runtime.getRuntime().exec(command);
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            if (enableLog)
                                IOUtils.write(line, logWriter);
                        }
                    } finally {
                        reader.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            if (enableLog)
                                IOUtils.write(line, logWriter);
                        }
                    } finally {
                        reader.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }).start();
        process.waitFor();
        return videoConverted;
    } catch (IOException e) {
        throw new VideoConversionException("Can't run video conversion software", e);
    } finally {
        if (enableLog)
            IOUtils.closeQuietly(fileWriter);
    }
}

From source file:io.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java

@Test
public void multiple_uploads_works() throws IOException {
    File file = folder.newFile("something");
    IOUtils.write("Something3210", new FileOutputStream(file));

    RestAssuredMockMvc.given().multiPart("controlName1", "original1", "something123".getBytes(), "mime-type1")
            .multiPart("controlName2", "original2", new FileInputStream(file), "mime-type2").when()
            .post("/multiFileUpload").then().root("[%d]").body("size", withArgs(0), is(12))
            .body("name", withArgs(0), equalTo("controlName1"))
            .body("originalName", withArgs(0), equalTo("original1"))
            .body("mimeType", withArgs(0), equalTo("mime-type1"))
            .body("content", withArgs(0), equalTo("something123")).body("size", withArgs(1), is(13))
            .body("name", withArgs(1), equalTo("controlName2"))
            .body("originalName", withArgs(1), equalTo("original2"))
            .body("mimeType", withArgs(1), equalTo("mime-type2"))
            .body("content", withArgs(1), equalTo("Something3210"));
}

From source file:net.nicholaswilliams.java.licensing.TestLicenseManager.java

@BeforeClass
public static void setUpClass() throws Exception {
    TestLicenseManager.control = EasyMock.createStrictControl();

    TestLicenseManager.licenseProvider = TestLicenseManager.control.createMock(LicenseProvider.class);
    TestLicenseManager.publicKeyPasswordProvider = TestLicenseManager.control
            .createMock(PasswordProvider.class);
    TestLicenseManager.licensePasswordProvider = TestLicenseManager.control.createMock(PasswordProvider.class);
    TestLicenseManager.keyDataProvider = TestLicenseManager.control.createMock(PublicKeyDataProvider.class);
    TestLicenseManager.licenseValidator = TestLicenseManager.control.createMock(LicenseValidator.class);

    try {//from ww w.j ava 2 s. co  m
        LicenseManager.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseManagerProperties.setLicenseProvider(TestLicenseManager.licenseProvider);

    try {
        LicenseManager.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseManagerProperties.setPublicKeyDataProvider(TestLicenseManager.keyDataProvider);

    try {
        LicenseManager.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseManagerProperties.setPublicKeyPasswordProvider(TestLicenseManager.publicKeyPasswordProvider);
    LicenseManagerProperties.setLicensePasswordProvider(TestLicenseManager.licensePasswordProvider);
    LicenseManagerProperties.setLicenseValidator(TestLicenseManager.licenseValidator);
    LicenseManagerProperties.setCacheTimeInMinutes(0);

    LicenseManager.getInstance();

    KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair();

    TestLicenseManager.privateKey = keyPair.getPrivate();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());
    IOUtils.write(Encryptor.encryptRaw(x509EncodedKeySpec.getEncoded(), TestLicenseManager.keyPassword),
            outputStream);
    TestLicenseManager.encryptedPublicKey = outputStream.toByteArray();
}

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

@Test
public void testWrite() throws Exception {
    // 5L * 1024L * 1024L
    final Host host = new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(), new Credentials(
            System.getProperties().getProperty("b2.user"), System.getProperties().getProperty("b2.key")));
    final B2Session session = new B2Session(host);
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new Path("/test-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
    final CryptoVault cryptomator = new CryptoVault(
            new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)),
            new DisabledPasswordStore());
    final Path vault = cryptomator.create(session, null, new VaultCredentials("test"));
    session.withRegistry(/*from   w w w .ja va2  s .c o  m*/
            new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    final CryptoUploadFeature m = new CryptoUploadFeature<>(session,
            new B2LargeUploadService(session, new B2WriteFeature(session), 5242880L, 5),
            new B2WriteFeature(session), cryptomator);
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = RandomUtils.nextBytes(5242885);
    IOUtils.write(content, local.getOutputStream(false));
    final TransferStatus writeStatus = new TransferStatus();
    final Cryptor cryptor = cryptomator.getCryptor();
    final FileHeader header = cryptor.fileHeaderCryptor().create();
    writeStatus.setHeader(cryptor.fileHeaderCryptor().encryptHeader(header));
    writeStatus.setLength(content.length);
    final Path test = new Path(vault, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    m.upload(test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            writeStatus, null);
    assertEquals((long) content.length, writeStatus.getOffset(), 0L);
    assertTrue(writeStatus.isComplete());
    assertTrue(new CryptoFindFeature(session, new B2FindFeature(session), cryptomator).find(test));
    assertEquals(content.length,
            new CryptoAttributesFeature(session, new B2AttributesFinderFeature(session), cryptomator).find(test)
                    .getSize());
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
    final TransferStatus readStatus = new TransferStatus().length(content.length);
    final InputStream in = new CryptoReadFeature(session, new B2ReadFeature(session), cryptomator).read(test,
            readStatus, new DisabledConnectionCallback());
    new StreamCopier(readStatus, readStatus).transfer(in, buffer);
    assertArrayEquals(content, buffer.toByteArray());
    new CryptoDeleteFeature(session, new B2DeleteFeature(session), cryptomator)
            .delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback());
    local.delete();
    session.close();
}

From source file:ctrus.pa.bow.core.Vocabulary.java

public final void writeTermVocabularyTo(OutputStream out) throws IOException {
    IOUtils.write("TERM,FREQ,HASH \n", out);
    for (String term : _termVocabulary.keySet()) {
        TermMeta t = _termVocabulary.get(term);
        // Add the term frequency
        if (_termFrequency.containsKey(t.freq)) {
            TermFreq tfreq = _termFrequency.get(t.freq);
            tfreq.freq++;//from w  w  w.j a  v a  2s  .c  o m
        } else {
            TermFreq tfq = new TermFreq();
            tfq.bucket = t.freq;
            _termFrequency.put(t.freq, tfq);
        }
        StringBuffer sb = new StringBuffer();
        if (t.minHash != null) {
            for (String s : t.minHash)
                sb.append(s).append(" ");
            IOUtils.write(term + "," + t.freq + "," + sb.toString() + "\n", out);
        } else {
            IOUtils.write(term + "," + t.freq + "\n", out);
        }
    }
}

From source file:hudson.remoting.DefaultClassFilterTest.java

/**
 * Checks that if given an invalid pattern in the overrides then the defaults are used.
 *///w w  w . j  ava 2s.  c  o  m
@Test(expected = Error.class)
public void testDefaultsAreUsedIfOverridesAreGarbage() throws Exception {
    List<String> badClasses = Arrays.asList("Z{100,0}" /* min > max for repetition */);
    File f = folder.newFile("overrides.txt");
    FileOutputStream fos = new FileOutputStream(f);
    try {
        for (String s : badClasses) {
            IOUtils.write(s, fos);
            IOUtils.write("\n", fos);
        }
    } finally {
        fos.close();
    }
    setOverrideProperty(f.getAbsolutePath());

    ClassFilter.createDefaultInstance();
}

From source file:com.jayway.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java

@Test
public void multiple_uploads_works() throws IOException {
    File file = folder.newFile("something");
    IOUtils.write("Something3210", new FileOutputStream(file));

    given().multiPart("controlName1", "original1", "something123".getBytes(), "mime-type1")
            .multiPart("controlName2", "original2", new FileInputStream(file), "mime-type2").when()
            .post("/multiFileUpload").then().root("[%d]").body("size", withArgs(0), is(12))
            .body("name", withArgs(0), equalTo("controlName1"))
            .body("originalName", withArgs(0), equalTo("original1"))
            .body("mimeType", withArgs(0), equalTo("mime-type1"))
            .body("content", withArgs(0), equalTo("something123")).body("size", withArgs(1), is(13))
            .body("name", withArgs(1), equalTo("controlName2"))
            .body("originalName", withArgs(1), equalTo("original2"))
            .body("mimeType", withArgs(1), equalTo("mime-type2"))
            .body("content", withArgs(1), equalTo("Something3210"));
}