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

/**
 * Unmarshal XML data from XML file path using XSD string and return the resulting JAXB content tree
 * //from   w w w. j ava2  s  .c o m
 * @param dummyCtxObject
 *            Dummy contect object for creating related JAXB context
 * @param strXMLFilePath
 *            XML file path
 * @param strXSD
 *            XSD
 * @return resulting JAXB content tree
 * @throws Exception
 *             in error case
 */
public static Object doUnmarshallingFromXMLFile(Object dummyCtxObject, String strXMLFilePath, String strXSD)
        throws Exception {
    if (dummyCtxObject == null) {
        throw new RuntimeException("No dummy context object (null)!");
    }
    if (strXMLFilePath == null) {
        throw new RuntimeException("No XML file path (null)!");
    }
    if (strXSD == null) {
        throw new RuntimeException("No XSD (null)!");
    }

    Object unmarshalledObject = null;

    try {
        JAXBContext jaxbCtx = JAXBContext.newInstance(dummyCtxObject.getClass().getPackage().getName());
        Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
        // unmarshaller.setValidating(true);
        /*
        javax.xml.validation.Schema schema =
        javax.xml.validation.SchemaFactory.newInstance(
        javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
        new java.io.File(m_strXSDFilePath));
         */
        StringReader reader = null;
        FileInputStream fis = null;
        try {
            reader = new StringReader(strXSD);
            javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory
                    .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)
                    .newSchema(new StreamSource(reader));
            unmarshaller.setSchema(schema);

            fis = new FileInputStream(strXMLFilePath);
            unmarshalledObject = unmarshaller.unmarshal(fis);
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
            if (reader != null) {
                reader.close();
                reader = null;
            }
        }
        // } catch (JAXBException e) {
        // //m_logger.error(e);
        // throw new OrderException(e);
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error);
        throw e;
    }

    return unmarshalledObject;
}

From source file:Main.java

/**
 * /*from  www .j a  v a 2s.c  om*/
 * @param xml
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static Document loadXMLFromString(String xml)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

From source file:com.kbotpro.handlers.ScriptMetaDataManager.java

public static void loadScriptMetaData() {
    if (System.currentTimeMillis() - lastUpdated > 3600) { // One hour
        String xml = StaticStorage.serverCom.getScriptList();
        try {/*from  w  w w .j  ava2  s  .  c  om*/
            Document doc = new SAXBuilder().build(new StringReader(xml));
            List<ScriptMetaData> loadedScriptMetaData = new ArrayList<ScriptMetaData>();
            Element root = doc.getRootElement();
            for (Element script : (List<Element>) root.getChildren("script")) {
                if (script == null) {
                    continue;
                }
                List<Permission> permissionExceptions = new ArrayList<Permission>();
                final Element policyNode = script.getChild("spolicy");
                if (policyNode != null) {
                    for (Element permission : (List<Element>) policyNode.getChildren("permission")) {
                        String className = permission.getAttributeValue("classname");
                        try {
                            Class klass = ScriptMetaDataManager.class.forName(className);
                            final Constructor constructor = klass
                                    .getConstructor(new Class<?>[] { String.class, String.class });
                            final Permission perm = (Permission) constructor.newInstance(
                                    permission.getAttributeValue("name"),
                                    permission.getAttributeValue("actions"));
                            permissionExceptions.add(perm);
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        } catch (InvocationTargetException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        } catch (InstantiationException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        } catch (IllegalAccessException e) {
                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        }

                    }
                }
                ScriptMetaData scriptMetaData = new ScriptMetaData(
                        Integer.parseInt(script.getAttributeValue("ID")), script.getAttributeValue("name"),
                        script.getAttributeValue("author"),
                        Integer.parseInt(script.getAttributeValue("downloads")),
                        StringEscapeUtils.unescapeXml(script.getChildText("description")),
                        script.getAttributeValue("category"), script.getAttributeValue("type"),
                        script.getAttributeValue("version"), Integer.parseInt(script.getAttributeValue("rev")),
                        Integer.parseInt(script.getAttributeValue("modifier")), permissionExceptions);
                loadedScriptMetaData.add(scriptMetaData);
            }
            ScriptMetaDataManager.loadedScriptMetaData = loadedScriptMetaData;
        } catch (JDOMException e) {
            Logger.getRootLogger().error("Exception: ", e); //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            Logger.getRootLogger().error("Exception: ", e); //To change body of catch statement use File | Settings | File Templates.
        }
    }
}

From source file:Main.java

/**
 *
 *
 * @param obj .../*from w ww.j  ava  2s. co  m*/
 *
 * @return ...
 *
 * @throws SAXException ...
 * @throws IOException ...
 * @throws ParserConfigurationException ...
 */
public static Document parseXml(Object obj) throws SAXException, IOException, ParserConfigurationException {
    if (domBuilderFactory == null) {
        domBuilderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    }

    DocumentBuilder parser = domBuilderFactory.newDocumentBuilder();
    Document doc = null;

    if (obj instanceof String) {
        try {
            // first try to interpret string as URL
            new URL(obj.toString());

            doc = parser.parse(obj.toString());
        } catch (MalformedURLException nourl) {
            // if not a URL, maybe it is the XML itself
            doc = parser.parse(new InputSource(new StringReader(obj.toString())));
        }
    } else if (obj instanceof InputStream) {
        doc = parser.parse(new InputSource((InputStream) obj));
    } else if (obj instanceof Reader) {
        doc = parser.parse(new InputSource((Reader) obj));
    }

    doc.normalize();

    return doc;
}

From source file:me.smoe.adar.analyzer.luence.AnalyzerToy.java

public static Set<String> analyzerByStandard(String sentence) throws Exception {
    Analyzer analyzer = new StandardAnalyzer();
    try {/*from  w  w  w.  ja  v a2  s.c om*/
        TokenStream tokenStream = analyzer.tokenStream(StringUtils.EMPTY, new StringReader(sentence));
        tokenStream.addAttribute(CharTermAttribute.class);
        tokenStream.reset();

        Set<String> words = new HashSet<>();
        while (tokenStream.incrementToken()) {
            words.add(((CharTermAttribute) tokenStream.getAttribute(CharTermAttribute.class)).toString());
        }

        return words;
    } finally {
        analyzer.close();
    }
}

From source file:com.mac.holdempoker.socket.MessageDecoder.java

/**
 * Transform the input string into a Message
 * @param string//www. j ava 2s .co  m
 * @return 
 * @throws javax.websocket.DecodeException
 */
@Override
public Message decode(String string) throws DecodeException {
    System.out.println("Decoding...");
    JsonObject json = Json.createReader(new StringReader(string)).readObject();
    System.out.println(json);
    return new Message(json);
}

From source file:com.xpn.xwiki.doc.merge.MergeUtils.java

/**
 * Merge a String./*w  w w. j  a  v a2 s.c  om*/
 * 
 * @param previousStr previous version of the string
 * @param newStr new version of the string
 * @param currentStr current version of the string
 * @param mergeResult the merge report
 * @return the merged string
 */
// TODO: add support for line merge
public static String mergeString(String previousStr, String newStr, String currentStr,
        MergeResult mergeResult) {
    String result = currentStr;

    try {
        Patch patch = DiffUtils.diff(IOUtils.readLines(new StringReader(previousStr)),
                IOUtils.readLines(new StringReader(newStr)));
        if (patch.getDeltas().size() > 0) {
            result = StringUtils.join(patch.applyTo(IOUtils.readLines(new StringReader(currentStr))), '\n');

            mergeResult.setModified(true);
        }
    } catch (Exception e) {
        mergeResult.getErrors().add(e);
    }

    return result;
}

From source file:Main.java

public static Templates TrAXPath(String xpath) throws TransformerConfigurationException {
    StringBuffer sb = new StringBuffer();

    sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    sb.append("<xsl:stylesheet version=\"1.0\" ");
    sb.append(" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
    sb.append("<xsl:output method=\"xml\" indent=\"yes\"/>");
    sb.append("<xsl:template match=\"" + xpath + "\">");
    sb.append("<xsl:copy-of select=\".\"/>");
    sb.append("</xsl:template>");
    sb.append("<xsl:template match=\"*|@*|text()\">");
    sb.append("<xsl:apply-templates />");
    sb.append("</xsl:template>");
    sb.append("</xsl:stylesheet>");

    TransformerFactory tf = TransformerFactory.newInstance();
    String stylesheet = sb.toString();
    Reader r = new StringReader(stylesheet);
    StreamSource ssrc = new StreamSource(r);

    return tf.newTemplates(ssrc);
}

From source file:Main.java

public static Document getDocument(String str) {
    Document doc = null;/* w ww .  j  av  a 2 s  .com*/
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = null;

        builder = factory.newDocumentBuilder();

        StringReader userdataReader = new StringReader(str);

        InputSource inputSource = new InputSource(userdataReader);

        doc = builder.parse(inputSource);
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    return doc;
}