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:Main.java

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

    String xml = "<metadata><codes class = 'class1'>" + "<code code='ABC'>" + "<detail x='blah blah'/>"
            + "</code>" + "</codes>" + "<codes class = 'class2'>" + "<code code = '123'>"
            + "<detail x='blah blah'/></code></codes></metadata>";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new ByteArrayInputStream(xml.getBytes()));

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("//codes/code[@code ='ABC']");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength() > 0 ? "Yes" : "No");
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println("nodes: " + nodes.item(i).getNodeValue());
    }//from  www.  j  av a 2s .  com
}

From source file:Main.java

public static void main(final String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w w  w  .j av  a2s . com*/
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse(new ByteArrayInputStream(( //
    "<?xml version=\"1.0\"?>" + //
            "<people>" + //
            "<person><name>First Person Name</name></person>" + //
            "<person><name>Second Person Name</name></person>" + //
            "</people>" //
    ).getBytes()));

    String fragment = "<name>Changed Name</name>";
    Document fragmentDoc = builder.parse(new ByteArrayInputStream(fragment.getBytes()));

    Node injectedNode = doc.adoptNode(fragmentDoc.getFirstChild());

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("//people/person[2]/name");
    Element nodeFound = (Element) expr.evaluate(doc, XPathConstants.NODE);

    Node parentNode = nodeFound.getParentNode();
    parentNode.removeChild(nodeFound);
    parentNode.appendChild(injectedNode);

    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(domSource, result);
    System.out.println(result.getWriter().toString());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount", "2");
    Source xmlSource = new SAXSource(new InputSource(
            new ByteArrayInputStream("<a><b><c/><d>text D</d><e value='0'/></b></a>".getBytes())));
    StreamResult res = new StreamResult(new ByteArrayOutputStream());
    serializer.transform(xmlSource, res);
    System.out.println(new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray()));
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String xml = "<root>" + "<ctc:BasePrice>" + "<cgc:PriceAmount currencyID='EUR'>18.75</cgc:PriceAmount>"
            + "<cgc:BaseQuantity quantityUnitCode='EA'>1</cgc:BaseQuantity>" + "</ctc:BasePrice>"
            + "<ctc:BasePrice>" + "<cgc:PriceAmount currencyID='EUR'>18.25</cgc:PriceAmount>"
            + "<cgc:BaseQuantity quantityUnitCode='EA'>1</cgc:BaseQuantity>"
            + "<cgc:MinimumQuantity quantityUnitCode='EA'>3</cgc:MinimumQuantity>" + "</ctc:BasePrice>"
            + "</root>";

    InputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(xmlStream);
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "//*[local-name() = 'BasePrice' and not(descendant::*[local-name() = 'MinimumQuantity'])]/*[local-name()='PriceAmount']";
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
    }//from  ww w  . ja  v a 2 s  . com
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String URL = "jdbc:odbc:dbname";
    Connection dbConn = DriverManager.getConnection(URL, "user", "passw");
    Employee employee = new Employee(42, "AA", 9);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(employee);/* w  w  w . j  a v a 2s . co  m*/
    byte[] employeeAsBytes = baos.toByteArray();
    PreparedStatement pstmt = dbConn.prepareStatement("INSERT INTO EMPLOYEE (emp) VALUES(?)");
    ByteArrayInputStream bais = new ByteArrayInputStream(employeeAsBytes);
    pstmt.setBinaryStream(1, bais, employeeAsBytes.length);
    pstmt.executeUpdate();
    pstmt.close();
    Statement stmt = dbConn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT emp FROM Employee");
    while (rs.next()) {
        byte[] st = (byte[]) rs.getObject(1);
        ByteArrayInputStream baip = new ByteArrayInputStream(st);
        ObjectInputStream ois = new ObjectInputStream(baip);
        Employee emp = (Employee) ois.readObject();
    }
    stmt.close();
    rs.close();
    dbConn.close();
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPair pair = generateRSAKeyPair();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    bOut.write(generateV1Certificate(pair).getEncoded());
    bOut.close();//www .  j  a v a  2 s  .c om
    InputStream in = new ByteArrayInputStream(bOut.toByteArray());
    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate x509Cert = (X509Certificate) fact.generateCertificate(in);
    System.out.println("issuer: " + x509Cert.getIssuerX500Principal());
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPair pair = generateRSAKeyPair();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    bOut.write(generateV1Certificate(pair).getEncoded());
    bOut.close();/*ww  w .  jav  a 2 s . c o m*/

    InputStream in = new ByteArrayInputStream(bOut.toByteArray());

    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

    X509Certificate x509Cert;
    Collection collection = new ArrayList();

    while ((x509Cert = (X509Certificate) fact.generateCertificate(in)) != null) {
        collection.add(x509Cert);
    }

    Iterator it = collection.iterator();
    while (it.hasNext()) {
        System.out.println("version: " + ((X509Certificate) it.next()).getVersion());
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String xml = "<Services><service name='qwerty' id=''><File rootProfile='abcd' extension='acd'><Columns>"
            + "<name id='0' profileName='DATE' type='java'></name><name id='1' profileName='DATE' type='java'></name>"
            + "</Columns></File><File rootProfile='efg' extension='ghi'><Columns><name id='a' profileName='DATE' type='java'></name>"
            + "<name id='b' profileName='DATE' type='java'></name></Columns></File></service></Services>";
    DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;

    documentBuilder = documentFactory.newDocumentBuilder();

    org.w3c.dom.Document doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes())));

    doc.getDocumentElement().normalize();
    NodeList nodeList0 = doc.getElementsByTagName("service");
    NodeList nodeList1 = null;// ww  w  . j av  a  2 s.  com
    NodeList nodeList2 = null;
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

    for (int temp0 = 0; temp0 < nodeList0.getLength(); temp0++) {
        Node node0 = nodeList0.item(temp0);

        System.out.println("\nElement type :" + node0.getNodeName());
        Element Service = (Element) node0;

        if (node0.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        System.out.println("name : " + Service.getAttribute("name"));
        System.out.println("id : " + Service.getAttribute("id"));
        nodeList1 = Service.getChildNodes();
        for (int temp = 0; temp < nodeList1.getLength(); temp++) {
            Node node1 = nodeList1.item(temp);

            System.out.println("\nElement type :" + node1.getNodeName());

            Element File = (Element) node1;

            if (node1.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            System.out.println("rootProfile:" + File.getAttribute("rootProfile"));
            System.out.println("extension  : " + File.getAttribute("extension"));

            nodeList2 = File.getChildNodes();// colums
            for (int temp1 = 0; temp1 < nodeList2.getLength(); temp1++) {
                Element column = (Element) nodeList2.item(temp1);
                NodeList nodeList4 = column.getChildNodes();
                for (int temp3 = 0; temp3 < nodeList4.getLength(); temp3++) {
                    Element name = (Element) nodeList4.item(temp3);
                    if (name.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    System.out.println("id:" + name.getAttribute("id"));
                    System.out.println("profileName  : " + name.getAttribute("profileName"));
                    System.out.println("type  : " + name.getAttribute("type"));
                }
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new ByteArrayInputStream(
                    ("<foo><foo1>Foo Test 1</foo1><foo2><another1><test1>Foo Test 2</test1></another1></foo2><foo3>Foo Test 3</foo3><foo4>Foo Test 4</foo4></foo>")
                            .getBytes()));
    String xpath = "/" + getXPath(document, "test1");
    Node node1 = (Node) XPathFactory.newInstance().newXPath().compile(xpath).evaluate(document,
            XPathConstants.NODE);
    Node node2 = (Node) XPathFactory.newInstance().newXPath().compile("//test1").evaluate(document,
            XPathConstants.NODE);
    System.out.println(node1.equals(node2));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    byte[] input = "www.java2s.com".getBytes();
    byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
            0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
    byte[] ivBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x01 };//ww w .j  av a2 s.  com

    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    System.out.println("input : " + new String(input));

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    ByteArrayInputStream bIn = new ByteArrayInputStream(input);
    CipherInputStream cIn = new CipherInputStream(bIn, cipher);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    int ch;
    while ((ch = cIn.read()) >= 0) {
        bOut.write(ch);
    }

    byte[] cipherText = bOut.toByteArray();

    System.out.println("cipher: " + new String(cipherText));

    // decryption pass
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    bOut = new ByteArrayOutputStream();
    CipherOutputStream cOut = new CipherOutputStream(bOut, cipher);
    cOut.write(cipherText);
    cOut.close();
    System.out.println("plain : " + new String(bOut.toByteArray()));
}