Example usage for org.apache.commons.io.output NullOutputStream nullOutputStream

List of usage examples for org.apache.commons.io.output NullOutputStream nullOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.output NullOutputStream nullOutputStream.

Prototype

public static OutputStream nullOutputStream() 

Source Link

Document

Returns a new OutputStream which discards all bytes.

Usage

From source file:org.openestate.io.examples.OpenImmoWritingExample.java

/**
 * Start the example application.//from  w w  w .  j  ava  2 s  . c  o m
 *
 * @param args
 * command line arguments
 */
public static void main(String[] args) {
    // init logging
    PropertyConfigurator.configure(OpenImmoWritingExample.class.getResource(PACKAGE + "/log4j.properties"));

    // create an Openimmo object with some example data
    // this object corresponds to the <openimmo> root element in XML
    Openimmo openimmo = FACTORY.createOpenimmo();
    openimmo.setUebertragung(createUebertragung());
    openimmo.getAnbieter().add(createAnbieter());

    // convert the Openimmo object into a XML document
    OpenImmoTransferDocument doc = null;
    try {
        doc = OpenImmoTransferDocument.newDocument(openimmo);
    } catch (Exception ex) {
        LOGGER.error("Can't create XML document!");
        LOGGER.error("> " + ex.getLocalizedMessage(), ex);
        System.exit(1);
    }

    // write XML document into a java.io.File
    try {
        write(doc, File.createTempFile("output-", ".xml"));
    } catch (IOException ex) {
        LOGGER.error("Can't create temporary file!");
        LOGGER.error("> " + ex.getLocalizedMessage(), ex);
        System.exit(1);
    }

    // write XML document into a java.io.OutputStream
    write(doc, new NullOutputStream());

    // write XML document into a java.io.Writer
    write(doc, new NullWriter());

    // write XML document into a string and send it to the console
    writeToConsole(doc);

    // downgrade XML document to an earlier version
    // and write it to the console
    doc.downgrade(OpenImmoVersion.V1_2_3);
    writeToConsole(doc);

    // downgrade XML document to the first version
    // and write it to the console
    doc.downgrade(OpenImmoVersion.V1_1);
    writeToConsole(doc);
}

From source file:org.openestate.io.examples.TrovitWritingExample.java

/**
 * Start the example application./*from ww  w  . j a  v a  2 s. c o m*/
 *
 * @param args
 * command line arguments
 */
public static void main(String[] args) {
    // init logging
    PropertyConfigurator.configure(TrovitWritingExample.class.getResource(PACKAGE + "/log4j.properties"));

    // create a Trovit object with some example data
    // this object corresponds to the <trovit> element in XML
    Trovit trovit = FACTORY.createTrovit();

    // append some example ads to the transfer
    trovit.getAd().add(createAd());
    trovit.getAd().add(createAd());
    trovit.getAd().add(createAd());

    // convert the Trovit object into a XML document
    TrovitDocument doc = null;
    try {
        doc = TrovitDocument.newDocument(trovit);
    } catch (Exception ex) {
        LOGGER.error("Can't create XML document!");
        LOGGER.error("> " + ex.getLocalizedMessage(), ex);
        System.exit(1);
    }

    // write XML document into a java.io.File
    try {
        write(doc, File.createTempFile("output-", ".xml"));
    } catch (IOException ex) {
        LOGGER.error("Can't create temporary file!");
        LOGGER.error("> " + ex.getLocalizedMessage(), ex);
        System.exit(1);
    }

    // write XML document into a java.io.OutputStream
    write(doc, new NullOutputStream());

    // write XML document into a java.io.Writer
    write(doc, new NullWriter());

    // write XML document into a string and send it to the console
    writeToConsole(doc);
}

From source file:org.openestate.io.examples.WisItWritingExample.java

/**
 * Start the example application./*from  w  w w  .java 2s.  c  o m*/
 *
 * @param args
 * command line arguments
 */
public static void main(String[] args) {
    // init logging
    PropertyConfigurator.configure(WisItWritingExample.class.getResource(PACKAGE + "/log4j.properties"));

    // create a WIS object with some example data
    // this object corresponds to the <WIS> element in XML
    WIS wis = FACTORY.createWIS();
    wis.setBENUTZER(FACTORY.createWISBENUTZER());
    wis.setOBJEKTE(FACTORY.createWISOBJEKTE());

    // append some example ads to the transfer
    wis.getOBJEKTE().getOBJEKT().add(createOBJEKT());
    wis.getOBJEKTE().getOBJEKT().add(createOBJEKT());
    wis.getOBJEKTE().getOBJEKT().add(createOBJEKT());
    wis.getOBJEKTE().setANZAHL(BigInteger.valueOf(wis.getOBJEKTE().getOBJEKT().size()));

    // convert the WIS object into a XML document
    WisItDocument doc = null;
    try {
        doc = WisItDocument.newDocument(wis);
    } catch (Exception ex) {
        LOGGER.error("Can't create XML document!");
        LOGGER.error("> " + ex.getLocalizedMessage(), ex);
        System.exit(1);
    }

    // write XML document into a java.io.File
    try {
        write(doc, File.createTempFile("output-", ".xml"));
    } catch (IOException ex) {
        LOGGER.error("Can't create temporary file!");
        LOGGER.error("> " + ex.getLocalizedMessage(), ex);
        System.exit(1);
    }

    // write XML document into a java.io.OutputStream
    write(doc, new NullOutputStream());

    // write XML document into a java.io.Writer
    write(doc, new NullWriter());

    // write XML document into a string and send it to the console
    writeToConsole(doc);
}

From source file:org.ovirt.api.metamodel.tests.JsonWriterTest.java

/**
 * Checks that one million of VMs can be serialized in a reasonable time and without exhausting the memory of the
 * virtual machine. Note that the test is currently disabled because if it fails it will block other tests, but it
 * is still useful to run it manually, so please don't remove it.
 *//*from   w w  w.java 2s.  c  om*/
@Test
@Ignore
public void testOneMillion() throws IOException {
    // Create a iterator that generates the objects:
    Iterator<V4Vm> infinite = new Iterator<V4Vm>() {
        private int count;

        @Override
        public boolean hasNext() {
            return count < 1_000_000;
        }

        @Override
        public V4Vm next() {
            // Note that these are extremely simple objects, they should probably be more complicated for this
            // test to be realistic:
            V4Vm object = vm().id(String.valueOf(count)).name("vm" + count)
                    .disks(disk().id("123").alias("disk1")).disks(disk().id("456").alias("disk2")).build();
            count++;
            return object;
        }
    };

    // Write the objects generated by the iterator to a null stream, so that the only work performed is creating
    // the objects and converting them to XML:
    long before = System.currentTimeMillis();
    try (JsonWriter writer = new JsonWriter(new NullOutputStream(), false)) {
        V4JsonVmWriter.writeMany(infinite, writer);
    }
    long after = System.currentTimeMillis();
    long elapsed = after - before;

    // Check if it took less than a minute (it should take much more less, approx 2s, but lets be
    // conservative:
    assertTrue(elapsed < 60_000_000);
}

From source file:org.ovirt.api.metamodel.tests.XmlWriterTest.java

/**
 * Checks that one million of VMs can be serialized in a reasonable time and without exhausting the memory of the
 * virtual machine. Note that the test is currently disabled because if it fails it will block other tests, but it
 * is still useful to run it manually, so please don't remove it.
 *///from  ww w  .java  2s  .co  m
@Test
@Ignore
public void testOneMillion() throws IOException {
    // Create a iterator that generates the objects:
    Iterator<V4Vm> infinite = new Iterator<V4Vm>() {
        private int count;

        @Override
        public boolean hasNext() {
            return count < 1_000_000;
        }

        @Override
        public V4Vm next() {
            // Note that these are extremely simple objects, they should probably be more complicated for this
            // test to be realistic:
            V4Vm object = vm().id(String.valueOf(count)).name("vm" + count)
                    .disks(disk().id("123").alias("disk1")).disks(disk().id("456").alias("disk2")).build();
            count++;
            return object;
        }
    };

    // Write the objects generated by the iterator to a null stream, so that the only work performed is creating
    // the objects and converting them to XML:
    long before = System.currentTimeMillis();
    try (XmlWriter writer = new XmlWriter(new NullOutputStream(), false)) {
        V4XmlVmWriter.writeMany(infinite, writer);
    }
    long after = System.currentTimeMillis();
    long elapsed = after - before;

    // Check if it took less than a minute (it should take much more less, approx 2s, but lets be
    // conservative:
    assertTrue(elapsed < 60_000_000);
}

From source file:org.paxle.crawler.LimitedRateCopierTest.java

public void testThreadedCopy() throws Exception {
    // FIXME if size is in the order of magnitude of limitKBps, this test works, but ...
    final int size = 1024 * 4; // ... try to increase this value ...
    final int threadNum = 4;
    final int limitKBps = 8; // ... and this one proportionally, and watch how it explodes :)

    final int expectedTime = size / 1024 * 1000 / limitKBps * threadNum;
    final ILimitedRateCopier lrc = null; // new LimitedRateCopier(limitKBps); 

    // System.out.println("expected time: " + expectedTime + " ms");

    final ArrayList<Thread> threads = new ArrayList<Thread>();
    final Object sync = new Object();
    for (int i = 0; i < threadNum; i++) {
        final int num = i;
        final InputStream zis = new NullInputStream(size);
        final OutputStream nos = new NullOutputStream();
        threads.add(new Thread() {
            {/*www  .j  a  v  a2s .com*/
                this.setName("Test-thread " + num);
            }

            @Override
            public void run() {
                try {
                    //   System.out.println("thread " + num + " syncing");
                    synchronized (sync) {
                        sync.wait();
                    }
                    //   System.out.println("thread " + num + " starts copying");

                    final long start = System.currentTimeMillis();
                    // lrc.copy(zis, nos, size);
                    final long end = System.currentTimeMillis();
                    /* XXX this is wrong, because every new thread gets less bandwidth One would have to pre-set the
                     * number of expected threads in the lrc for this to be correct
                    assertTrue(
                          String.format("%d: Threaded copying took %d ms but should have taken %d ms.", num, end - start, expectedTime),
                          expectedTime <= end - start);
                     */
                    //   System.out.println("thread " + num + " finished in " + (end - start) + " ms");
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
    }

    for (final Thread t : threads)
        t.start();
    Thread.sleep(10); // wait until all have started and are waiting on sync

    // System.out.println("notifying all");

    final long start = System.currentTimeMillis();
    synchronized (sync) {
        sync.notifyAll();
    }
    for (final Thread t : threads)
        t.join();
    final long end = System.currentTimeMillis();

    // System.out.println(String.format("Finished in %d ms", end - start));
    //      assertTrue(String.format("All %d threads took %d ms but should have taken %d ms.", threadNum, end - start, expectedTime),
    //            expectedTime <= end - start);
}

From source file:org.pentaho.reporting.platform.plugin.async.TestInterruptionInterceptionTest.java

@Test
public void testInterruptFlagProblem2() throws Exception {
    PentahoAsyncExecutionInterruptTest t1 = new PentahoAsyncExecutionInterruptTest();

    t1.before();//w  w w .  ja va  2s  . com
    t1.testInterrupt();
    t1.after();

    PdfReportUtil.createPDF(new MasterReport(), new NullOutputStream());
}

From source file:org.rhq.storage.installer.StorageInstaller.java

private String exec(File workingDir, org.apache.commons.exec.CommandLine cmdLine) throws Exception {
    Executor executor = new DefaultExecutor();
    org.apache.commons.io.output.ByteArrayOutputStream buffer = new org.apache.commons.io.output.ByteArrayOutputStream();
    NullOutputStream nullOs = new NullOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(nullOs, buffer);
    executor.setWorkingDirectory(workingDir);
    executor.setStreamHandler(streamHandler);
    String result = "";

    try {/*from   w  w w.j  a va 2 s.  com*/
        exec(executor, cmdLine);
        result = buffer.toString();

    } finally {
        try {
            buffer.close();
            nullOs.close();
        } catch (Exception e) {
            // best effort
        }
    }

    return result;
}

From source file:org.robovm.eclipse.RoboVMPlugin.java

private static byte[] md5(InputStream in) throws IOException {
    MessageDigest digest;/* www .jav a 2s  .  c  om*/
    try {
        digest = MessageDigest.getInstance("md5");
    } catch (NoSuchAlgorithmException e) {
        throw new Error(e);
    }
    DigestInputStream dis = new DigestInputStream(in, digest);
    IOUtils.copy(dis, new NullOutputStream());
    return digest.digest();
}

From source file:org.roda_project.commons_ip.model.impl.eark.EARKAIP.java

private void writeFileToPath(final ZipEntryInfo zipEntryInfo, final Path outputPath, final boolean onlyMets)
        throws IOException, NoSuchAlgorithmException {
    InputStream is = null;/*from  ww  w .jav  a  2 s  .  c  o  m*/
    OutputStream os = null;
    try {

        is = Files.newInputStream(zipEntryInfo.getFilePath());

        if (!onlyMets || zipEntryInfo instanceof METSZipEntryInfo) {
            Files.createDirectories(outputPath.getParent());
            os = Files.newOutputStream(outputPath);
        } else {
            os = new NullOutputStream();
        }

        final byte[] buffer = new byte[4096];
        final MessageDigest complete = MessageDigest.getInstance(IPConstants.CHECKSUM_ALGORITHM);
        int numRead;
        do {
            numRead = is.read(buffer);
            if (numRead > 0) {
                complete.update(buffer, 0, numRead);
                if (!onlyMets || zipEntryInfo instanceof METSZipEntryInfo) {
                    os.write(buffer, 0, numRead);
                }
            }
        } while (numRead != -1);

        setChecksum(zipEntryInfo, DatatypeConverter.printHexBinary(complete.digest()),
                IPConstants.CHECKSUM_ALGORITHM);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}