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:io.restassured.examples.springmvc.controller.MultiPartFileUploadITest.java

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

    RestAssuredMockMvc.given().multiPart("controlName", "original", new FileInputStream(file)).when()
            .post("/fileUpload2").then().body("size", greaterThan(10)).body("name", equalTo("controlName"))
            .body("originalName", equalTo("original"));
}

From source file:net.javacrumbs.mocksocket.SampleTest.java

@Test
public void testConditionalData() throws Exception {
    byte[] dataToWrite = new byte[] { 5, 4, 3, 2 };
    byte[] mockData = new byte[] { 1, 2, 3, 4 };
    expectCall().andWhenRequest(data(is(dataToWrite))).thenReturn(data(mockData));

    Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
    IOUtils.write(dataToWrite, socket.getOutputStream());
    byte[] data = IOUtils.toByteArray(socket.getInputStream());
    socket.close();/*  ww  w.java  2  s .  co m*/
    assertThat(data, is(mockData));
}

From source file:de.dennishoersch.web.css.parser.ParserTest.java

@Test
public void testCompressRulesSimple() throws Exception {

    StringWriter merged = new StringWriter();

    String css = getFileContent("simpleTest.css");

    Stylesheet stylesheet = Parser.parse(css);

    for (Rule rule : stylesheet.getRules()) {
        IOUtils.write(rule.toString() + "\n", merged);
    }//from   w  ww  .  j  a v a 2s.  com

    merged.flush();
    merged.close();

    //        System.out.println();
    //        System.out.println(merged);
    //        System.out.println();

    // The overriding removes the 'yellow' definition
    assertThat(merged.toString(), not(containsString("yellow")));

    // Vendor prefixes in values do not override
    assertThat(merged.toString(), containsString("-moz"));
    assertThat(merged.toString(), containsString("-webkit"));

    // was ist besser oder effizienter?

    // .paddingAll, .paddingWithMarginTop {padding: 20px;}
    // .paddingWithMarginTop {margin-top: 10px;}

    // vs:
    // .paddingAll{padding:20px;}
    // .paddingWithMarginTop{padding:20px;margin-top:10px;}
}

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

@Test
public void testWriteChecksumFailure() 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 file = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final TransferStatus status = new TransferStatus();
    final byte[] content = RandomUtils.nextBytes(1);
    status.setLength(content.length);// w w  w . j  a  v  a  2s  .  co m
    status.setChecksum(Checksum.parse("da39a3ee5e6b4b0d3255bfef95601890afd80709"));
    final HttpResponseOutputStream<BaseB2Response> out = new B2WriteFeature(session).write(file, status,
            new DisabledConnectionCallback());
    IOUtils.write(content, out);
    try {
        out.close();
        fail();
    } catch (IOException e) {
        assertTrue(e.getCause() instanceof ChecksumException);
    } finally {
        session.close();
    }
}

From source file:com.moz.fiji.mapreduce.testlib.IntegrationTestSimpleBulkImporter.java

private void writeBulkImportInput(Path path) throws Exception {
    final String[] inputLines = { "row1:1", "row2:2", "row3:2", "row4:2", "row5:5", "row6:1", "row7:2",
            "row8:1", "row9:2", "row10:2", };

    final OutputStream ostream = mFS.create(path);
    for (String line : inputLines) {
        IOUtils.write(line, ostream);
        ostream.write('\n');
    }/*ww  w .ja va  2  s  .  c  o m*/
    ostream.close();
}

From source file:ch.cyberduck.core.worker.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();/*  w  w w  .  ja v  a2s  . co  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(new DAVWriteFeature(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());
    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, session, t, new TransferOptions(), new TransferSpeedometer(t),
            new DisabledTransferPrompt() {
                @Override
                public TransferAction prompt(final TransferItem file) {
                    return TransferAction.overwrite;
                }
            }, new DisabledTransferErrorCallback(), new DisabledProgressListener(), counter,
            new DisabledLoginCallback(), new DisabledPasswordCallback(), TransferItemCache.empty()) {

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

From source file:io.datalayer.mime4j.parser.Mime4jStreamParserTest.java

@Override
protected void runTest() throws Throwable {
    MimeStreamParser parser = null;/*from w  w w. jav a 2  s . c o  m*/
    Mime4jTestHandler handler = null;
    MimeConfig config = new MimeConfig();
    if (getName().startsWith("malformedHeaderStartsBody")) {
        config.setMalformedHeaderStartsBody(true);
    }
    config.setMaxLineLen(-1);
    parser = new MimeStreamParser(config);
    handler = new Mime4jTestHandler();

    parser.setContentHandler(handler);
    parser.parse(url.openStream());

    String result = handler.sb.toString();

    String s = url.toString();
    String prefix = s.substring(0, s.lastIndexOf('.'));
    URL xmlFileUrl = new URL(prefix + ".xml");
    try {
        InputStream openStream = xmlFileUrl.openStream();
        String expected = IOUtils.toString(openStream, "ISO8859-1");
        assertEquals(expected, result);
    } catch (FileNotFoundException e) {
        IOUtils.write(result, new FileOutputStream(xmlFileUrl.getPath() + ".expected"));
        fail("Expected file created.");
    }
}

From source file:de.fau.cs.osr.hddiff.perfsuite.util.SerializationUtils.java

public File storeWomNiceTemp(PageRevWom prw, Revision rev, Wom3Document wom) throws Exception {
    File file = File.createTempFile(makeNicePrefix(prw, rev), ".xml", tempDir);
    file.deleteOnExit();//ww w.j  a v a  2s .  c  o  m
    try (FileOutputStream fos = new FileOutputStream(file)) {
        byte[] str = serializer.serialize(wom, WomSerializer.SerializationFormat.XML, false, true);
        IOUtils.write(str, fos);
    }
    return file;
}

From source file:mclub.util.loc.LocationCoderService.java

public void flushCache() {
    if (addressLocationCache == null || addressLocationCache.isEmpty()) {
        return;/*w w w  .  j  ava  2 s. co m*/
    }
    FileOutputStream out = null;
    try {
        String jsonString = JSON.toJSONString(addressLocationCache.values());
        out = new FileOutputStream(localCacheFileName);
        IOUtils.write(jsonString, out);
        log.info("Locatio coder cache file" + localCacheFileName + " saved");
    } catch (Exception e) {
        log.warn("Error saving location coder cache file: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:ch.cyberduck.core.irods.IRODSUploadFeatureTest.java

@Test
@Ignore/*w w  w.ja v a  2 s .com*/
public void testAppend() throws Exception {
    final ProtocolFactory factory = new ProtocolFactory(
            new HashSet<>(Collections.singleton(new IRODSProtocol())));
    final Profile profile = new ProfilePlistReader(factory)
            .read(new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile"));
    final Host host = new Host(profile, profile.getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("irods.key"),
                    System.getProperties().getProperty("irods.secret")));

    final IRODSSession session = new IRODSSession(host);
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final int length = 32770;
    final byte[] content = RandomUtils.nextBytes(length);
    final OutputStream out = local.getOutputStream(false);
    IOUtils.write(content, out);
    out.close();
    final Checksum checksumPart1;
    final Checksum checksumPart2;
    final Path test = new Path(new IRODSHomeFinderService(session).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    {
        final TransferStatus status = new TransferStatus().length(content.length / 2);
        checksumPart1 = new IRODSUploadFeature(session).upload(test, local,
                new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), status,
                new DisabledConnectionCallback());
        assertEquals(content.length / 2, status.getOffset());
    }
    {
        final TransferStatus status = new TransferStatus().length(content.length / 2).skip(content.length / 2)
                .append(true);
        checksumPart2 = new IRODSUploadFeature(session).upload(test, local,
                new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), status,
                new DisabledConnectionCallback());
        assertEquals(content.length / 2, status.getOffset());
    }
    assertNotEquals(checksumPart1, checksumPart2);
    final byte[] buffer = new byte[content.length];
    final InputStream in = new IRODSReadFeature(session).read(test, new TransferStatus().length(content.length),
            new DisabledConnectionCallback());
    IOUtils.readFully(in, buffer);
    in.close();
    assertArrayEquals(content, buffer);
    new IRODSDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    local.delete();
    session.close();
}