Example usage for java.io ByteArrayInputStream ByteArrayInputStream

List of usage examples for java.io ByteArrayInputStream ByteArrayInputStream

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream ByteArrayInputStream.

Prototype

public ByteArrayInputStream(byte buf[]) 

Source Link

Document

Creates a ByteArrayInputStream so that it uses buf as its buffer array.

Usage

From source file:com.glaf.core.xml.XmlBuilder.java

public static void main(String[] args) throws Exception {
    long start = System.currentTimeMillis();
    String systemName = "default";

    XmlBuilder builder = new XmlBuilder();
    InputStream in = new FileInputStream("./template/user.template.xml");
    String filename = "user.xml";
    byte[] bytes = FileUtils.getBytes(in);
    Map<String, Object> dataMap = new HashMap<String, Object>();
    dataMap.put("now", new Date());
    Document doc = builder.process(systemName, new ByteArrayInputStream(bytes), dataMap);
    FileUtils.save(filename, com.glaf.core.util.Dom4jUtils.getBytesFromPrettyDocument(doc, "GBK"));
    // net.sf.json.xml.XMLSerializer xmlSerializer = new
    // net.sf.json.xml.XMLSerializer();
    // net.sf.json.JSON json = xmlSerializer.read(doc.asXML());
    // System.out.println(json.toString(1));

    long time = (System.currentTimeMillis() - start) / 1000;
    System.out.println("times:" + time + " seconds");
}

From source file:com.javacreed.examples.sql.Example3.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {
            @Override/*from  w  ww.java 2  s  . co m*/
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (InputStream in = new LZ4BlockInputStream(resultSet.getBinaryStream("compressed"))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new LZ4BlockOutputStream(baos)) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }
        };
        test.runTest();
    }
    Example3.LOGGER.debug("Done");
}

From source file:com.javacreed.examples.sql.Example4.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {

            @Override/*from w  w w .  ja  va2s .  c o m*/
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (InputStream in = new LZ4BlockInputStream(
                        CryptoUtils.wrapInToCipheredInputStream(resultSet.getBinaryStream("compressed")))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new LZ4BlockOutputStream(
                        CryptoUtils.wrapInToCipheredOutputStream(baos))) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }

        };
        test.runTest();
    }
    Example4.LOGGER.debug("Done");
}

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 w w  w. j a  v a 2s .c o m

    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:com.javacreed.examples.sql.Example2.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {
            @Override//www.j ava 2s  .  c  o m
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (GZIPInputStream in = new GZIPInputStream(resultSet.getBinaryStream("compressed"))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                // Compress the data before inserting it. We need to compress before inserting the data to make this process
                // as realistic as possible.
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new GZIPOutputStream(baos, data.length())) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }
        };
        test.runTest();
    }
    Example2.LOGGER.debug("Done");
}

From source file:com.cloudhopper.sxmp.demo.ParserMain.java

static public void main(String[] args) throws Exception {
    StringBuilder string0 = new StringBuilder(200).append("<?xml version='1.0' encoding='iso-8859-1'?>\n")
            .append("<!DOCTYPE malicious [\n").append("    <!ENTITY x0 \"\">\n")
            .append("    <!ENTITY x1 \"&x0;&x0;\">\n").append("    <!ENTITY x2 \"&x1;&x1;\">\n")
            .append("    <!ENTITY x3 \"&x2;&x2;\">\n").append("    <!ENTITY x4 \"&x3;&x3;\">\n")
            .append("    <!ENTITY x5 \"&x4;&x4;\">\n").append("    <!ENTITY x6 \"&x5;&x5;\">\n")
            .append("    <!ENTITY x7 \"&x6;&x6;\">\n").append("    <!ENTITY x8 \"&x7;&x7;\">\n")
            .append("    <!ENTITY x9 \"&x8;&x8;\">\n").append("    <!ENTITY x10 \"&x9;&x9;\">\n")
            .append("    <!ENTITY x11 \"&x10;&x10;\">\n").append("    <!ENTITY x12 \"&x11;&x11;\">\n")
            .append("    <!ENTITY x13 \"&x12;&x12;\">\n").append("    <!ENTITY x14 \"&x13;&x13;\">\n")
            .append("    <!ENTITY x15 \"&x14;&x14;\">\n").append("    <!ENTITY x16 \"&x15;&x15;\">\n")
            .append("    <!ENTITY x17 \"&x16;&x16;\">\n").append("    <!ENTITY x18 \"&x17;&x17;\">\n")
            .append("    <!ENTITY x19 \"&x18;&x18;\">\n").append("    <!ENTITY x20 \"&x19;&x19;\">\n")
            .append("]>\n").append("<operation type=\"deliver\">\n")
            .append("<account username=\"test\" password=\"test\"/>\n").append("<deliverRequest>\n")
            .append("<ticketId>&x20;</ticketId>\n").append("</deliverRequest>    \n").append("</operation >\n")
            .append("");

    ByteArrayInputStream is = new ByteArrayInputStream(string0.toString().getBytes());
    SxmpParser parser = new SxmpParser(SxmpParser.VERSION_1_0);

    //try {/*w  w  w.j a va 2 s  . c o  m*/
    Operation operation = parser.parse(is);
    //Assert.fail();
    //} catch (SxmpParsingException e) {
    // correct behavior
    //Assert.assertEquals(SxmpErrorCode.MISSING_REQUIRED_ATTRIBUTE, e.getErrorCode());
    //Assert.assertThat(e.getMessage(), JUnitMatchers.containsString("The attribute [username] is required with the [account] element"));
    //Assert.assertNotNull(e.getOperation());
    //   PartialOperation partial = (PartialOperation)e.getOperation();
    //Assert.assertEquals(Operation.Type.SUBMIT, partial.getType());
    //}

    logger.debug("done!");
}

From source file:ebay.Ebay.java

/**
 * @param args the command line arguments
 *//*from  w  w w .  j av  a2s  .c o  m*/
public static void main(String[] args) {
    HttpClient client = null;
    HttpResponse response = null;
    BufferedReader rd = null;
    Document doc = null;
    String xml = "";
    EbayDAO<Producto> db = new EbayDAO<>(Producto.class);
    String busqueda;

    while (true) {
        busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda");
        if (busqueda != null) {
            busqueda = busqueda.replaceAll(" ", "%20");
            try {
                client = new DefaultHttpClient();
                /*
                 peticion GET
                 */
                HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems"
                        + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords="
                        + busqueda + "&siteid=0" + "&responseencoding=XML");
                /*
                 se ejecuta la peticion GET
                 */
                response = client.execute(request);
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                /*
                 comienza la lectura de la respuesta a la peticion GET
                 */
                String line;
                while ((line = rd.readLine()) != null) {
                    xml += line + "\n";
                }
            } catch (IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            /*
             creamos nuestro documentBulder(documento constructor) y obtenemos 
             nuestro objeto documento apartir de documentBuilder
             */
            try {
                DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
            } catch (ParserConfigurationException | SAXException | IOException ex) {
                Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex);
            }

            Element raiz = doc.getDocumentElement();
            if (raiz == null) {
                System.exit(0);
            }
            if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) {
                NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes();
                for (int i = 0; i < array.getLength(); ++i) {
                    Node n = array.item(i);

                    if (n.getNodeType() != Node.TEXT_NODE) {
                        Producto p = new Producto();
                        if (((Element) n).getElementsByTagName("ItemID").item(0) != null)
                            p.setId(new Long(
                                    ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("EndTime").item(0) != null)
                            p.setEndtime(
                                    ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null)
                            p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ListingType").item(0) != null)
                            p.setListingtype(
                                    ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null)
                            p.setGalleryurl(
                                    ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null)
                            p.setPrimarycategoryid(new Integer(((Element) n)
                                    .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null)
                            p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName")
                                    .item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("BidCount").item(0) != null)
                            p.setBidcount(new Integer(
                                    ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null)
                            p.setConvertedcurrentprice(new Double(((Element) n)
                                    .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null)
                            p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null)
                            p.setTimeleft(
                                    ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("Title").item(0) != null)
                            p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent());
                        if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null)
                            p.setShippingservicecost(new Double(((Element) n)
                                    .getElementsByTagName("ShippingServiceCost").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ShippingType").item(0) != null)
                            p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0)
                                    .getTextContent());
                        if (((Element) n).getElementsByTagName("WatchCount").item(0) != null)
                            p.setWatchcount(new Integer(
                                    ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent()));
                        if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null)
                            p.setListedshippingservicecost(
                                    new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost")
                                            .item(0).getTextContent()));
                        try {
                            db.insert(p);
                        } catch (Exception e) {
                            db.update(p);
                        }
                    }
                }
            }
            Ventana.crear(xml);
        } else
            System.exit(0);

    }
}

From source file:net.itransformers.bgpPeeringMap.BgpPeeringMapFromFile.java

public static void main(String[] args) throws Exception {

    Map<String, String> params = CmdLineParser.parseCmdLine(args);
    logger.info("input params" + params.toString());
    final String settingsFile = params.get("-s");
    if (settingsFile == null) {
        printUsage("bgpPeeringMap.properties");
        return;//from  w ww . ja  v a  2 s  . com
    }

    Map<String, String> settings = loadProperties(new File(System.getProperty("base.dir"), settingsFile));
    logger.info("Settings" + settings.toString());

    File outputDir = new File(System.getProperty("base.dir"), settings.get("output.dir"));
    System.out.println(outputDir.getAbsolutePath());
    boolean result = outputDir.mkdir();
    //        if (!result) {
    //            System.out.println("result:"+result);
    //            System.out.println("Unable to create dir: "+outputDir);
    //            return;
    //        }

    File graphmlDir = new File(outputDir, settings.get("output.dir.graphml"));
    result = outputDir.mkdir();
    //        if (!result) {
    //            System.out.println("Unable to create dir: "+graphmlDir);
    //            return;
    //        }

    XsltTransformer transformer = new XsltTransformer();
    byte[] rawData = readRawDataFile(settings.get("raw-data-file"));
    logger.info("First-transformation has started with xsltTransformator " + settings.get("xsltFileName1"));

    ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
    File xsltFileName1 = new File(System.getProperty("base.dir"), settings.get("xsltFileName1"));
    ByteArrayInputStream inputStream1 = new ByteArrayInputStream(rawData);
    // transformer.transformXML(inputStream1, xsltFileName1, outputStream1, settings);
    logger.info("First transformation finished");
    File outputFile1 = new File(graphmlDir, "bgpPeeringMap-intermediate.xml");

    FileUtils.writeStringToFile(outputFile1, new String(outputStream1.toByteArray()));

    logger.info("Second transformation started with xsltTransformator " + settings.get("xsltFileName2"));

    ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
    File xsltFileName2 = new File(System.getProperty("base.dir"), settings.get("xsltFileName2"));
    ByteArrayInputStream inputStream2 = new ByteArrayInputStream(outputStream1.toByteArray());
    // transformer.transformXML(inputStream2, xsltFileName2, outputStream2, settings);
    logger.info("Second transformation finished");
    File outputFile = new File(graphmlDir, "bgpPeeringMap.graphml");
    File nodesFileListFile = new File(graphmlDir, "nodes-file-list.txt");
    FileUtils.writeStringToFile(outputFile, new String(outputStream2.toByteArray()));
    logger.info("Output Graphml saved in a file in" + graphmlDir);

    FileUtils.writeStringToFile(nodesFileListFile, "bgpPeeringMap.graphml");

    ByteArrayInputStream inputStream3 = new ByteArrayInputStream(outputStream2.toByteArray());
    ByteArrayOutputStream outputStream3 = new ByteArrayOutputStream();
    File xsltFileName3 = new File(System.getProperty("base.dir"), settings.get("xsltFileName3"));
    // transformer.transformXML(inputStream3, xsltFileName3, outputStream3);

}

From source file:de.serverfrog.pw.crypt.SerpentUtil.java

/**
 * Print all Security providers and their algos
 *
 * @param args args//  w ww .  ja v a 2  s  . c  om
 * @throws Exception Exception
 */
public static void main(String[] args) throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    SecretKeySpec keySpec = new SecretKeySpec("test".getBytes("UTF-8"), "AES");
    try (CipherOutputStream outputStream = SerpentUtil.getOutputStream(byteArrayOutputStream, keySpec)) {
        IOUtils.write("TEST", outputStream);
    }
    System.out.println(Arrays.toString(byteArrayOutputStream.toByteArray()));
    System.out.println(byteArrayOutputStream.toString("UTF-8"));
    byte[] toByteArray = byteArrayOutputStream.toByteArray();
    ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(toByteArray);
    CipherInputStream inputStream = SerpentUtil.getInputStream(arrayInputStream,
            new SecretKeySpec("test".getBytes("UTF-8"), "AES"));
    byte[] bytes = new byte[1048576];

    IOUtils.read(inputStream, bytes);

    System.out.println(new String(bytes, "UTF-8").trim());

    //
    //        for (Provider provider : Security.getProviders()) {
    //            System.out.println("");
    //            System.out.println("");
    //            System.out.println("");
    //            System.out.println("-------------------------------");
    //            System.out.println("Name: " + provider.getName());
    //            System.out.println("Info: " + provider.getInfo());
    //            for (Map.Entry<Object, Object> entry : provider.entrySet()) {
    //                System.out.println("Key: Class:" + entry.getKey().getClass() + " String: " + entry.getKey());
    //                System.out.println("Value: Class:" + entry.getValue().getClass() + " String: " + entry.getValue());
    //            }
    //            for (Provider.Service service : provider.getServices()) {
    //                System.out.println("Service: Algorithm:" + service.getAlgorithm()
    //                        + " ClassName:" + service.getClassName()
    //                        + " Type:" + service.getType() + " toString:" + service.toString());
    //            }
    //            for (Object object : provider.values()) {
    //                System.out.println("Value: " + object.getClass() + " toString:" + object.toString());
    //
    //            }
    //            System.out.println("-------------------------------");
    //        }
}

From source file:ObfuscatingStream.java

/**
 * Obfuscates or unobfuscates the second command-line argument, depending on
 * whether the first argument starts with "o" or "u"
 * /*from  w  ww. ja  va2 s.  c  o m*/
 * @param args
 *            Command-line arguments
 * @throws IOException
 *             If an error occurs obfuscating or unobfuscating
 */
public static void main(String[] args) throws IOException {
    InputStream input = new ByteArrayInputStream(args[1].getBytes());
    StringBuilder toPrint = new StringBuilder();
    if (args[0].startsWith("o")) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        OutputStream out = obfuscate(bytes);
        int read = input.read();
        while (read >= 0) {
            out.write(read);
            read = input.read();
        }
        byte[] receiptBytes = bytes.toByteArray();
        for (int b = 0; b < receiptBytes.length; b++) {
            int chr = (receiptBytes[b] + 256) % 256;
            toPrint.append(HEX_CHARS[chr >>> 4]);
            toPrint.append(HEX_CHARS[chr & 0xf]);
        }
    } else if (args[0].startsWith("u")) {
        input = unobfuscate(input);
        InputStreamReader reader = new InputStreamReader(input);

        int read = reader.read();
        while (read >= 0) {
            toPrint.append((char) read);
            read = reader.read();
        }
    } else
        throw new IllegalArgumentException("First argument must start with o or u");
    System.out.println(toPrint.toString());
}