Example usage for java.io StringWriter StringWriter

List of usage examples for java.io StringWriter StringWriter

Introduction

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

Prototype

public StringWriter() 

Source Link

Document

Create a new string writer using the default initial string-buffer size.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(new InputSource(
            new StringReader("<emp><empname><firstName></firstName><lastName></lastName></empname></emp>")));
    NodeList customerNodes = doc.getElementsByTagName("empname");
    for (int i = 0; i < customerNodes.getLength(); i++) {
        NodeList children = customerNodes.item(i).getChildNodes();
        for (int j = 0; j < children.getLength(); j++) {
            String childNode = children.item(j).getNodeName();
            if (childNode.equalsIgnoreCase("firstName")) {
                children.item(j).setTextContent(String.valueOf("John"));
            } else if (childNode.equalsIgnoreCase("lastName")) {
                children.item(j).setTextContent(String.valueOf("Doe"));
            }//from   w  ww .j a  v a2s  . c o m
        }
    }
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    System.out.println(writer.getBuffer().toString());
}

From source file:demoalchemy.DemoCloudantClient.java

/**
 * @param args the command line arguments
 *///from   w  w  w  .  j a  v  a 2 s  . c  om
public static void main(String[] args) {
    try {
        // TODO code application logic here
        CloudantClient client = ClientBuilder.account("2efca010-d783-48ff-8b09-a85b380b66a3-bluemix")
                .username("2efca010-d783-48ff-8b09-a85b380b66a3-bluemix")
                .password("2f040ce083e86c585ae5638a7cdba89951097a8b8a9480544d9a3d18de955533").build();
        // Show the server version
        System.out.println("NICOOL ES LOCA - Server Version: " + client.serverVersion());
        // Get a List of all the databases this Cloudant account
        List<String> databases = client.getAllDbs();
        System.out.println("All my databases : ");
        for (String db : databases) {
            System.out.println(db);
        }

        Database db = client.database("becario", false);
        InputStream is = db.find("650cb18385ff988b236611625fcc3a3e");
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        String theString = writer.toString();

        System.out.println(theString);
    } catch (IOException ex) {
        Logger.getLogger(DemoCloudantClient.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from   w  w w  . j av  a  2s . co  m*/
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    Element root = doc.createElementNS(null, "person"); // Create Root Element
    Element item = doc.createElementNS(null, "name"); // Create element
    item.appendChild(doc.createTextNode("Jeff"));
    root.appendChild(item); // Attach element to Root element
    item = doc.createElementNS(null, "age"); // Create another Element
    item.appendChild(doc.createTextNode("28"));
    root.appendChild(item); // Attach Element to previous element down tree
    item = doc.createElementNS(null, "height");
    item.appendChild(doc.createTextNode("1.80"));
    root.appendChild(item); // Attach another Element - grandaugther
    doc.appendChild(root); // Add Root to Document

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplLS = (DOMImplementationLS) registry.getDOMImplementation("LS");

    LSSerializer ser = domImplLS.createLSSerializer(); // Create a serializer
                                                       // for the DOM
    LSOutput out = domImplLS.createLSOutput();
    StringWriter stringOut = new StringWriter(); // Writer will be a String
    out.setCharacterStream(stringOut);
    ser.write(doc, out); // Serialize the DOM

    System.out.println("STRXML = " + stringOut.toString()); // DOM as a String
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "yourName", "mypwd");

    Statement stmt = conn.createStatement();

    createBlobClobTables(stmt);/* w  w w  . jav a  2  s. c  om*/

    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobClob VALUES(40,?,?)");

    File file = new File("blob.txt");
    FileInputStream fis = new FileInputStream(file);
    pstmt.setBinaryStream(1, fis, (int) file.length());

    file = new File("clob.txt");
    fis = new FileInputStream(file);
    pstmt.setAsciiStream(2, fis, (int) file.length());
    fis.close();

    pstmt.execute();

    ResultSet rs = stmt.executeQuery("SELECT * FROM BlobClob WHERE id = 40");
    rs.next();

    java.sql.Blob blob = rs.getBlob(2);
    java.sql.Clob clob = rs.getClob(3);

    byte blobVal[] = new byte[(int) blob.length()];
    InputStream blobIs = blob.getBinaryStream();
    blobIs.read(blobVal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bos.write(blobVal);
    blobIs.close();

    char clobVal[] = new char[(int) clob.length()];
    Reader r = clob.getCharacterStream();
    r.read(clobVal);
    StringWriter sw = new StringWriter();
    sw.write(clobVal);

    r.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "yourName", "mypwd");

    Statement stmt = conn.createStatement();

    createBlobClobTables(stmt);//from   w  w w. java  2s.  c om

    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobClob VALUES(40,?,?)");

    File file = new File("blob.txt");
    FileInputStream fis = new FileInputStream(file);
    pstmt.setBinaryStream(1, fis, (int) file.length());

    file = new File("clob.txt");
    fis = new FileInputStream(file);
    pstmt.setAsciiStream(2, fis, (int) file.length());
    fis.close();

    pstmt.execute();

    ResultSet rs = stmt.executeQuery("SELECT * FROM BlobClob WHERE id = 40");
    rs.next();

    java.sql.Blob blob = rs.getBlob(2);
    java.sql.Clob clob = rs.getClob("myClobColumn");

    byte blobVal[] = new byte[(int) blob.length()];
    InputStream blobIs = blob.getBinaryStream();
    blobIs.read(blobVal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bos.write(blobVal);
    blobIs.close();

    char clobVal[] = new char[(int) clob.length()];
    Reader r = clob.getCharacterStream();
    r.read(clobVal);
    StringWriter sw = new StringWriter();
    sw.write(clobVal);

    r.close();
    conn.close();
}

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  ava 2s .c  om
    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 JAXBException {
    HumansList list = new HumansList();
    Person parent1 = new Person("parent1");
    list.addHuman(parent1);/*  w  w  w.jav a2  s.c om*/
    Person child11 = new Person("child11");
    list.addHuman(child11);
    Person child12 = new Person("child12");
    list.addHuman(child12);

    Person parent2 = new Person("parent2");
    list.addHuman(parent2);
    Person child21 = new Person("child21");
    list.addHuman(child21);
    Person child22 = new Person("child22");
    list.addHuman(child22);

    JAXBContext context = JAXBContext.newInstance(HumansList.class);
    Marshaller m = context.createMarshaller();
    StringWriter xml = new StringWriter();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

    m.marshal(list, xml);
    System.out.println(xml);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader("<root>\r\n" + //
            "<Users>\r\n" + //
            "   <App id=\"test\">\r\n" + //
            "      <Username>ADMIN</Username>\r\n" + //
            "      <Password>ADMIN</Password>\r\n" + //
            "   </App>\r\n" + //
            "</Users>\r\n" + //
            "<Users>\r\n" + //
            "   <App id=\"test2\">\r\n" + //
            "      <Username>ADMIN2</Username>\r\n" + //
            "      <Password>ADMIN2</Password>\r\n" + //
            "   </App>\r\n" + //
            "</Users>\r\n" + //
            "</root>")));
    String inputId = "test2";
    String xpathStr = "//Users/App[@id='" + inputId + "']";
    // retrieve elements and change their content
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile(xpathStr + "/Username");
    Node username = (Node) expr.evaluate(doc, XPathConstants.NODE);
    username.setTextContent("test-username");
    expr = xpath.compile(xpathStr + "/Password");
    Node password = (Node) expr.evaluate(doc, XPathConstants.NODE);
    password.setTextContent("test-password");
    // output the document
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    System.out.println(writer.toString());

}

From source file:com.sonarsource.cobol.ebcdic.FileConverterTest.java

public static void main(String[] args) {
    FileConverter converter = new FileConverter(Charset.forName("UTF-8"), Charset.forName("UTF-8"));
    StringWriter writer = new StringWriter();
    try {//from w w  w.  j  av a 2 s .  c o  m
        converter.convert("This is a " + (char) 0x15 + " new line", writer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);//from   w w w.j a v  a 2  s  .c  om

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager
            .getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/access.mdb");

    ResultSet rs = con.createStatement().executeQuery("select * from product");

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);

    System.out.println(sw.toString());

    con.close();
    rs.close();
}