Example usage for java.io StringReader StringReader

List of usage examples for java.io StringReader StringReader

Introduction

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

Prototype

public StringReader(String s) 

Source Link

Document

Creates a new string reader.

Usage

From source file:Main.java

/**
 * @param xmlString/*from   w w  w.  j  ava  2s . co m*/
 * @return
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public synchronized static Document parse(String xmlString)
        throws IOException, SAXException, ParserConfigurationException {
    StringReader reader = new StringReader(xmlString);
    InputSource inputSource = new InputSource(reader);
    return getDocumentBuilder().parse(inputSource);
}

From source file:Main.java

public static Document StringToXML(String xmlString) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    DocumentBuilder builder = null;
    Document document = null;//w w  w. j a  v  a2  s .  c o  m
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        document = builder.parse(new InputSource(new StringReader(xmlString)));
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return document;
}

From source file:Main.java

public static String prettyPrintXML(String source) {
    try {/* w w w .j  a va 2s . co  m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf;
        tf = tff.newTransformer();
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        StreamResult result = new StreamResult(baos);
        tf.transform(new StreamSource(new StringReader(source)), result);
        return new String(baos.toByteArray());
    } catch (Exception e) {
        return source;
    }
}

From source file:Utils.java

public static String toHtml(String string) {
    if (StringUtils.isNullOrEmpty(string))
        return "<html><body></body></html>";

    BufferedReader st = new BufferedReader(new StringReader(string));
    StringBuffer buf = new StringBuffer("<html><body>");

    try {//from  w  w  w. ja  v a  2 s. c  o m
        String str = st.readLine();

        while (str != null) {
            if (str.equalsIgnoreCase("<br/>")) {
                str = "<br>";
            }

            buf.append(str);

            if (!str.equalsIgnoreCase("<br>")) {
                buf.append("<br>");
            }

            str = st.readLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    buf.append("</body></html>");
    string = buf.toString();
    return string;
}

From source file:Main.java

/**
 * Pretty format a given XML document/*from   w  ww.  j  a v a2 s .  co m*/
 *
 * @param strInput
 *            Valid XML document (No validity check yet!)
 * @param nIndent
 *            Indent
 * @return Formatted XML document
 * @throws Exception
 *             in error case
 */
public static String prettyFormat(String strInput, int nIndent) throws Exception {
    try {
        Source xmlInput = new StreamSource(new StringReader(strInput));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", nIndent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(nIndent));
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Pretty formatting: " + e.getMessage(), LogLevel.Error);
        throw e;
    }
}

From source file:Main.java

public static Document doc(String xml) {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    try {//from  w  w w . j a  v a 2 s .  c  om
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Document doc = null;
    try {
        doc = documentBuilder.parse(new InputSource(new StringReader(xml)));
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return doc;
}

From source file:com.atomiton.watermanagement.ngo.util.WaterMgmtNGOUtility.java

public static String getXMLElementValue(String tagName, String xmlString) {
    try {/*from   w  ww  .  j  a v  a  2s  . c  o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xmlString)));
        Element rootElement = document.getDocumentElement();
        String rootElementTagName = rootElement.getTagName();
        if (rootElementTagName.equalsIgnoreCase(tagName)) {
            return rootElement.getTextContent();
        } else {
            NodeList list = rootElement.getElementsByTagName(tagName);
            if (list != null && list.getLength() > 0) {
                NodeList subList = list.item(0).getChildNodes();
                if (subList != null && subList.getLength() > 0) {
                    return subList.item(0).getNodeValue();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

/**
 * Helper program: Transforms a String to a XML Document.
 *
 * @param InputXMLString the input xml string
 * @return parsed document/* ww w .  j a v a  2  s .  co  m*/
 * @throws javax.xml.parsers.ParserConfigurationException the parser configuration exception
 * @throws java.io.IOException                            Signals that an I/O exception has occurred.
 */
public static Document String2Doc(String InputXMLString) {
    try {
        DocumentBuilder builder = getDocumentBuilder();
        InputSource is = new InputSource(new StringReader(InputXMLString));
        is.setEncoding("UTF-8");
        return builder.parse(is);
    } catch (Exception e) {
        System.out.println("cannot parse following content\\n\\n" + InputXMLString);
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static Document toDocument(String xml, boolean namespaceAware, boolean ignoreDtd) throws Exception {
    Reader input = new StringReader(xml);
    InputSource is = new InputSource(input);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(namespaceAware);

    // ignore dtd files
    if (ignoreDtd) {
        dbf.setValidating(false);//from w  w w. j a v a  2  s .  c  o m
        dbf.setFeature("http://xml.org/sax/features/namespaces", false);
        dbf.setFeature("http://xml.org/sax/features/validation", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    }

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException exception) throws SAXException {
            throw exception;

        }

        public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
        }

        public void error(SAXParseException exception) throws SAXException {
            throw exception;
        }
    });
    return db.parse(is);
}

From source file:Main.java

/**
 * Takes a single line command as a string and breaks it up in tokens
 * acceptable for the java.lang.ProcessBuilder.ProcessBuilder
 * @param command Complete command as a single string
 * @return Array of strings that are acceptable tokens for ProcessBuilder
 * @throws Exception //from  w  ww .  java 2 s .  com
 */
static public List<String> breakUpCommand(String command) throws Exception {
    try {
        List<String> commandTokens = new Vector<String>();

        StringBuilder currentToken = null;
        boolean isTokenQuoted = false;
        StringReader sr = new StringReader(command);
        int b = sr.read();
        while (b >= 0) {
            char c = (char) b;

            if (null == currentToken) {
                // At token is not in progress

                // Skipping spaces
                if (' ' == c || '\t' == c) {

                } else if ('"' == c) {
                    // Starting a quoted token
                    currentToken = new StringBuilder();
                    //currentToken.append(c);
                    isTokenQuoted = true;
                } else {
                    // Starting a non-quoted token
                    currentToken = new StringBuilder();
                    currentToken.append(c);
                    isTokenQuoted = false;
                }

            } else if (isTokenQuoted) {
                // A quoted token is in progress. It ends with a quote
                if ('"' == c) {
                    //currentToken.append(c);
                    String token = currentToken.toString();
                    currentToken = null;
                    commandTokens.add(token);

                } else {
                    // Continuation
                    currentToken.append(c);
                }

            } else {
                // A non-quoted token is in progress. It ends with a space
                if (' ' == c || '\t' == c) {
                    String token = currentToken.toString();
                    currentToken = null;
                    commandTokens.add(token);

                } else {
                    // Continuation
                    currentToken.append(c);
                }
            }

            b = sr.read();
        }

        if (null != currentToken) {
            String token = currentToken.toString();
            commandTokens.add(token);
        }

        return commandTokens;

    } catch (IOException e) {
        throw new Exception("Error while breaking up command into tokens: " + command, e);
    }
}