Example usage for org.apache.commons.io.output ByteArrayOutputStream ByteArrayOutputStream

List of usage examples for org.apache.commons.io.output ByteArrayOutputStream ByteArrayOutputStream

Introduction

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

Prototype

public ByteArrayOutputStream() 

Source Link

Document

Creates a new byte array output stream.

Usage

From source file:com.offbynull.peernetic.debug.visualizer.App.java

public static void main(String[] args) throws Throwable {
    Random random = new Random();
    Visualizer<Integer> visualizer = new JGraphXVisualizer<>();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Recorder<Integer> recorder = new XStreamRecorder(baos);

    visualizer.visualize(recorder, null);

    visualizer.step("Adding nodes 1 and 2", new AddNodeCommand<>(1),
            new ChangeNodeCommand(1, null, new Point(random.nextInt(400), random.nextInt(400)), Color.RED),
            new AddNodeCommand<>(2),
            new ChangeNodeCommand(2, null, new Point(random.nextInt(400), random.nextInt(400)), Color.BLUE));
    Thread.sleep(500);//from   www  .  j  a  v a 2s.c  om

    visualizer.step("Adding nodes 3 and 4", new AddNodeCommand<>(3),
            new ChangeNodeCommand(3, null, new Point(random.nextInt(400), random.nextInt(400)), Color.ORANGE),
            new AddNodeCommand<>(4),
            new ChangeNodeCommand(4, null, new Point(random.nextInt(400), random.nextInt(400)), Color.PINK));
    Thread.sleep(500);

    visualizer.step("Connecting 1/2/3 to 4", new AddEdgeCommand<>(1, 4), new AddEdgeCommand<>(2, 4),
            new AddEdgeCommand<>(3, 4));
    Thread.sleep(500);

    visualizer.step("Adding trigger to 4 when no more edges",
            new TriggerOnLingeringNodeCommand(4, new RemoveNodeCommand<>(4)));
    Thread.sleep(500);

    visualizer.step("Removing connections from 1 and 2", new RemoveEdgeCommand<>(1, 4),
            new RemoveEdgeCommand<>(2, 4));
    Thread.sleep(500);

    visualizer.step("Removing connections from 3", new RemoveEdgeCommand<>(3, 4));
    Thread.sleep(500);

    recorder.close();

    Thread.sleep(2000);

    JGraphXVisualizer<Integer> visualizer2 = new JGraphXVisualizer<>();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    Player<Integer> player = new XStreamPlayer<>(bais);

    visualizer2.visualize();

    player.play(visualizer2);

}

From source file:net.sf.mcf2pdf.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option o = OptionBuilder.hasArg().isRequired()
            .withDescription("Installation location of My CEWE Photobook. REQUIRED.").create('i');
    options.addOption(o);//from   w  w  w  .ja  v  a2  s  .  co  m
    options.addOption("h", false, "Prints this help and exits.");
    options.addOption("t", true, "Location of MCF temporary files.");
    options.addOption("w", true, "Location for temporary images generated during conversion.");
    options.addOption("r", true, "Sets the resolution to use for page rendering, in DPI. Default is 150.");
    options.addOption("n", true, "Sets the page number to render up to. Default renders all pages.");
    options.addOption("b", false, "Prevents rendering of binding between double pages.");
    options.addOption("x", false, "Generates only XSL-FO content instead of PDF content.");
    options.addOption("q", false, "Quiet mode - only errors are logged.");
    options.addOption("d", false, "Enables debugging logging output.");

    CommandLine cl;
    try {
        CommandLineParser parser = new PosixParser();
        cl = parser.parse(options, args);
    } catch (ParseException pe) {
        printUsage(options, pe);
        System.exit(3);
        return;
    }

    if (cl.hasOption("h")) {
        printUsage(options, null);
        return;
    }

    if (cl.getArgs().length != 2) {
        printUsage(options,
                new ParseException("INFILE and OUTFILE must be specified. Arguments were: " + cl.getArgList()));
        System.exit(3);
        return;
    }

    File installDir = new File(cl.getOptionValue("i"));
    if (!installDir.isDirectory()) {
        printUsage(options, new ParseException("Specified installation directory does not exist."));
        System.exit(3);
        return;
    }

    File tempDir = null;
    String sTempDir = cl.getOptionValue("t");
    if (sTempDir == null) {
        tempDir = new File(new File(System.getProperty("user.home")), ".mcf");
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("MCF temporary location not specified and default location "
                    + tempDir + " does not exist."));
            System.exit(3);
            return;
        }
    } else {
        tempDir = new File(sTempDir);
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("Specified temporary location does not exist."));
            System.exit(3);
            return;
        }
    }

    File mcfFile = new File(cl.getArgs()[0]);
    if (!mcfFile.isFile()) {
        printUsage(options, new ParseException("MCF input file does not exist."));
        System.exit(3);
        return;
    }
    mcfFile = mcfFile.getAbsoluteFile();

    File tempImages = new File(new File(System.getProperty("user.home")), ".mcf2pdf");
    if (cl.hasOption("w")) {
        tempImages = new File(cl.getOptionValue("w"));
        if (!tempImages.mkdirs() && !tempImages.isDirectory()) {
            printUsage(options,
                    new ParseException("Specified working dir does not exist and could not be created."));
            System.exit(3);
            return;
        }
    }

    int dpi = 150;
    if (cl.hasOption("r")) {
        try {
            dpi = Integer.valueOf(cl.getOptionValue("r")).intValue();
            if (dpi < 30 || dpi > 600)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options,
                    new ParseException("Parameter for option -r must be an integer between 30 and 600."));
        }
    }

    int maxPageNo = -1;
    if (cl.hasOption("n")) {
        try {
            maxPageNo = Integer.valueOf(cl.getOptionValue("n")).intValue();
            if (maxPageNo < 0)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options, new ParseException("Parameter for option -n must be an integer >= 0."));
        }
    }

    boolean binding = true;
    if (cl.hasOption("b")) {
        binding = false;
    }

    OutputStream finalOut;
    if (cl.getArgs()[1].equals("-"))
        finalOut = System.out;
    else {
        try {
            finalOut = new FileOutputStream(cl.getArgs()[1]);
        } catch (IOException e) {
            printUsage(options, new ParseException("Output file could not be created."));
            System.exit(3);
            return;
        }
    }

    // configure logging, if no system property is present
    if (System.getProperty("log4j.configuration") == null) {
        PropertyConfigurator.configure(Main.class.getClassLoader().getResource("log4j.properties"));

        Logger.getRootLogger().setLevel(Level.INFO);
        if (cl.hasOption("q"))
            Logger.getRootLogger().setLevel(Level.ERROR);
        if (cl.hasOption("d"))
            Logger.getRootLogger().setLevel(Level.DEBUG);
    }

    // start conversion to XSL-FO
    // if -x is specified, this is the only thing we do
    OutputStream xslFoOut;
    if (cl.hasOption("x"))
        xslFoOut = finalOut;
    else
        xslFoOut = new ByteArrayOutputStream();

    Log log = LogFactory.getLog(Main.class);

    try {
        new Mcf2FoConverter(installDir, tempDir, tempImages).convert(mcfFile, xslFoOut, dpi, binding,
                maxPageNo);
        xslFoOut.flush();

        if (!cl.hasOption("x")) {
            // convert to PDF
            log.debug("Converting XSL-FO data to PDF");
            byte[] data = ((ByteArrayOutputStream) xslFoOut).toByteArray();
            PdfUtil.convertFO2PDF(new ByteArrayInputStream(data), finalOut, dpi);
            finalOut.flush();
        }
    } catch (Exception e) {
        log.error("An exception has occured", e);
        System.exit(1);
        return;
    } finally {
        if (finalOut instanceof FileOutputStream) {
            try {
                finalOut.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:gaffer.utils.WritableToStringConverter.java

public static String serialiseToString(Writable writable) throws IOException {
    // Serialise to a byte array
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    Text.writeString(out, writable.getClass().getName());
    writable.write(out);/*from  w ww . ja  v a 2  s.com*/

    // Convert the byte array to a base64 string
    return Base64.encodeBase64String(baos.toByteArray());
}

From source file:fr.dutra.confluence2wordpress.util.CodecUtils.java

public static String compressAndEncode(String text) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(new Base64OutputStream(baos));
    try {//from w  w  w . j  a v a 2  s  . c  o  m
        gzos.write(text.getBytes(UTF_8));
    } finally {
        baos.close();
        gzos.close();
    }
    return new String(baos.toByteArray(), UTF_8);
}

From source file:com.aestasit.markdown.BaseTest.java

protected static InputStream allTestData() throws IOException {
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    for (String fileName : allTestFiles()) {
        IOUtils.write(IOUtils.toString(testData(fileName)), data);
    }/*from   w  ww  .ja v  a 2  s  . c  o m*/
    IOUtils.closeQuietly(data);
    return new ByteArrayInputStream(data.toByteArray());
}

From source file:com.geocent.owf.openlayers.handler.KmzHandler.java

@Override
public String handleContent(HttpServletResponse response, InputStream responseStream) throws IOException {
    ZipInputStream zis = new ZipInputStream(responseStream);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];

    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        if (ze.getName().endsWith("kml")) {
            int len;
            while ((len = zis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }//from   w w w . j ava2  s  .  c  om

            response.setContentType(ContentTypes.KML.getContentType());
            return new String(baos.toByteArray(), Charset.defaultCharset());
        }

        ze = zis.getNextEntry();
    }

    throw new IOException("Missing KML file entry.");
}

From source file:lucee.runtime.functions.other.ObjectSave.java

public synchronized static Object call(PageContext pc, Object input, String filepath) throws PageException {
    if (!(input instanceof Serializable))
        throw new ApplicationException("can only serialize object from type Serializable");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//w w w .jav a  2s .  c  o  m
        JavaConverter.serialize((Serializable) input, baos);

        byte[] barr = baos.toByteArray();

        // store to file
        if (!StringUtil.isEmpty(filepath, true)) {
            Resource res = ResourceUtil.toResourceNotExisting(pc, filepath);
            pc.getConfig().getSecurityManager().checkFileLocation(res);
            IOUtil.copy(new ByteArrayInputStream(barr), res, true);
        }
        return barr;

    } catch (IOException e) {
        throw Caster.toPageException(e);
    }
}

From source file:com.diffplug.gradle.ConfigMisc.java

/** Creates an XML string from a groovy.util.Node. */
public static byte[] props(Map<String, String> map) {
    Properties properties = new Properties();
    map.forEach((key, value) -> properties.put(key, value));
    try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        Errors.rethrow().run(() -> properties.store(output, ""));
        return output.toByteArray();
    } catch (IOException e) {
        throw Errors.asRuntime(e);
    }/* ww w .  j a  va2  s .co  m*/
}

From source file:com.amalto.core.servlet.FileChunkLoaderTest.java

@Test
public void test() throws Exception {
    File test = getFile("com/amalto/core/servlet/test.log");

    FileChunkLoader loader = new FileChunkLoader(test);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long position = 0;
    FileChunkInfo chunkInfo = null;// w w  w.ja va  2 s .c o m

    //
    for (int i = 0; i < 11; i++) {
        chunkInfo = loader.loadChunkTo(baos, position, 2);
        if (position == 0) {
            String result = baos.toString();
            assertTrue(result.endsWith("Service (JTA version) - JBoss Inc.\r\n"));
            assertEquals(238, chunkInfo.nextPosition);
        }
        position = chunkInfo.nextPosition;
    }
    assertEquals(2406, chunkInfo.nextPosition);
    assertEquals(1, chunkInfo.lines); // last line does not contains '\n'
    String result = baos.toString();
    assertTrue(result.endsWith("startup in 34 ms"));

    //
    baos.reset();
    chunkInfo = loader.loadChunkTo(baos, 0, 0);
    assertEquals(0, chunkInfo.nextPosition);
    assertEquals(0, chunkInfo.lines);

    //
    baos.reset();
    chunkInfo = loader.loadChunkTo(baos, 0, 100);
    assertEquals(2406, chunkInfo.nextPosition);
    assertEquals(21, chunkInfo.lines);

    // tail
    baos.reset();
    chunkInfo = loader.loadChunkTo(baos, -1, 10);
    assertEquals(2406, chunkInfo.nextPosition);
    assertEquals(6, chunkInfo.lines);
    assertTrue(result.endsWith("startup in 34 ms"));

    // tail
    baos.reset();
    chunkInfo = loader.loadChunkTo(baos, -1, 100);
    assertEquals(2406, chunkInfo.nextPosition);
    assertEquals(21, chunkInfo.lines);
}

From source file:com.qcadoo.model.internal.utils.JdomUtils.java

public static byte[] documentToByteArray(final Document document) {
    try {/*from   w ww .ja  v a  2  s  .co m*/
        XMLOutputter outputter = new XMLOutputter();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        outputter.output(document, out);
        return out.toByteArray();
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}