Example usage for org.dom4j DocumentHelper parseText

List of usage examples for org.dom4j DocumentHelper parseText

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper parseText.

Prototype

public static Document parseText(String text) throws DocumentException 

Source Link

Document

parseText parses the given text as an XML document and returns the newly created Document.

Usage

From source file:com.mingsoft.weixin.util.XmlUtils.java

License:Open Source License

/**
 * ?xml??document??key?//w w  w  .  ja v a 2 s  . com
 * 
 * @param str
 *            
 * @param key
 *            ??
 * @return ??stringnull
 */
public static String getString(String str, String key) {
    try {
        Document document = DocumentHelper.parseText(str);
        Element root = document.getRootElement();
        return root.elementTextTrim(key);
    } catch (Exception e) {
        e.printStackTrace();
        LOG.debug("Exception?xml:" + str);
        LOG.debug("Exception?key:" + key);
    }
    return null;
}

From source file:com.mingsoft.weixin.util.XmlUtils.java

License:Open Source License

/**
 * ?xml??document??key?</br> xml?</br>
 * /*from  www  .ja  va  2s .  c  o  m*/
 * @param str
 *            
 * @param key
 *            ??
 * @param sonKey ???
 * @return ??stringnull
 */
public static String getString(String str, String key, String sonKey) {
    try {
        Document document = DocumentHelper.parseText(str);
        Element root = document.getRootElement();
        for (Iterator<?> i = root.elementIterator(key); i.hasNext();) {
            Element foo = (Element) i.next();
            return foo.elementText(sonKey);
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.debug("Exception?xml:" + str);
        LOG.debug("Exception?key:" + key);
    }
    return null;
}

From source file:com.mobileStore.sms.CCPRestSmsSDK.java

License:Open Source License

/**
 * @description xml??map// w  w w.  j  av  a  2 s.  co  m
 * @param xml
 * @return Map
 */
private static HashMap<String, Object> xmlToMap(String xml) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml); // XML
        Element rootElt = doc.getRootElement(); // ?
        HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
        for (Iterator i = rootElt.elementIterator(); i.hasNext();) {
            Element e = (Element) i.next();
            if ("statusCode".equals(e.getName()) || "statusMsg".equals(e.getName()))
                map.put(e.getName(), e.getText());
            else {
                if ("SubAccount".equals(e.getName()) || "totalCount".equals(e.getName())
                        || "token".equals(e.getName()) || "downUrl".equals(e.getName())) {
                    if (!"SubAccount".equals(e.getName())) {
                        hashMap2.put(e.getName(), e.getText());
                    } else {
                        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                            Element e2 = (Element) i2.next();
                            hashMap3.put(e2.getName(), e2.getText());
                            arrayList.add(hashMap3);
                        }
                        hashMap2.put("SubAccount", arrayList);
                    }
                    map.put("data", hashMap2);
                } else {

                    HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                    for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                        Element e2 = (Element) i2.next();
                        // hashMap2.put(e2.getName(),e2.getText());
                        hashMap3.put(e2.getName(), e2.getText());
                    }
                    if (hashMap3.size() != 0) {
                        hashMap2.put(e.getName(), hashMap3);
                    } else {
                        hashMap2.put(e.getName(), e.getText());
                    }
                    map.put("data", hashMap2);
                }
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
    } catch (Exception e) {
        LoggerUtil.error(e.getMessage());
        e.printStackTrace();
    }
    return map;
}

From source file:com.mor.test.XMLConsumingTestCase.java

License:Open Source License

public static Document getDefautDocument() {
    try {//from  w  w w  . ja va 2  s.  co  m
        return DocumentHelper.parseText("<root></root>");
    } catch (DocumentException ex) {
        Logger.getLogger(XMLConsumingTestCase.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.mor.test.XMLConsumingTestCase.java

License:Open Source License

public static Document getBlogDocument() {
    String docText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<!--Sample XML file generated by XMLSpy v2009 sp1 (http://www.altova.com)-->\n" + "\n"
            + "<Blog xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"blog.xsd\">\n"
            + "    <Entry date=\"2004-09-09\" ID=\"ID_152369776\" categoryID=\"ID_1222333\" allowComments=\"false\" >\n"
            + "       \n" + "        <Text>\n" + "            test entry !\n" + "        </Text>\n"
            + "        <Resume>\n" + "            feed\n" + "        </Resume>\n"
            + "        <Comment ID=\"ID_1476476016\" date=\"Mon Nov 23 00:00:00 EST 2009\" entryID=\"ID_152369776\" author=\"Mike\" webPage=\"no page\">\n"
            + "            <CommentText>Hi HI</CommentText>\n" + "        </Comment>\n" + "    </Entry>\n"
            + "    <Category name=\"test\" ID=\"ID_1222333\"/>\n" + "\n" + "\n"
            + "    <Category ID=\"ID_320524799\" name=\"added\" description=\"\"/>\n" + "\n"
            + "    <Category ID=\"ID_-492027613\" name=\"remove\" description=\"\"/>\n" + "\n" + "</Blog>";
    try {//from  w ww . jav  a  2  s .c o  m
        return DocumentHelper.parseText(docText);
    } catch (DocumentException ex) {
        Logger.getLogger(XMLConsumingTestCase.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.ms.commons.test.treedb.Objects2XmlFileUtil.java

License:Open Source License

private static String prettyPrint(final String xml) {

    if (StringUtils.isBlank(xml)) {
        throw new RuntimeException("xml was null or blank in prettyPrint()");
    }/*from   w  ww .  j a va  2 s.com*/

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
    } catch (Exception e) {
        throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
    }
    return sw.toString();
}

From source file:com.nokia.ant.Database.java

License:Open Source License

private void insertDocumentation(Element outNode, String commentText) throws IOException, DocumentException {
    if (commentText != null) {
        WikiModel wikiModel = new WikiModel("", "");
        if (!commentText.contains("</pre>")
                && (commentText.contains("**") || commentText.contains("==") || commentText.contains("- -"))) {
            commentText = commentText.replace("**", "").replace("==", "").replace("- -", "").trim();
            log("Warning: Comment code has invalid syntax: " + commentText, Project.MSG_WARN);
        }//from w ww .  j  a va2s  . co  m
        if (commentText.startsWith("-"))
            commentText = commentText.replace("-", "");
        commentText = commentText.trim();

        String commentTextCheck = commentText.replace("deprecated>", "").replace("tt>", "").replace("todo>",
                "");
        if (commentTextCheck.contains(">") && !commentTextCheck.contains("</pre>"))
            log("Warning: Comment code needs <pre> tags around it: " + commentText, Project.MSG_WARN);

        commentText = filterTextNewlines(commentText);
        commentText = wikiModel.render(commentText);

        // If <deprecated> tag exists in the comment, then parse the
        // deprecated message.
        if (commentText.indexOf("&#60;deprecated&#62;") != -1) {
            int deprecatedMsgStart = commentText.indexOf("&#60;deprecated&#62;") + 20;
            int deprecatedMsgEnd = commentText.indexOf("&#60;/deprecated&#62;");

            // Add deprecated element.
            String deprecatedMsg = commentText.substring(deprecatedMsgStart, deprecatedMsgEnd);
            addTextElement(outNode, "deprecated", deprecatedMsg);

            // remove <deprecated> part from description field.
            int commentTextLength = commentText.length();
            String documentationMsgStart = commentText.substring(1, deprecatedMsgStart - 20);
            String documentationMsgEnd = commentText.substring(deprecatedMsgEnd + 21, commentTextLength);
            String documentationMsg = documentationMsgStart.concat(documentationMsgEnd);
            commentText = documentationMsg.trim();
        }
    } else {
        commentText = "";
    }
    // Get the documentation element as a document
    String documentationText = "<documentation>" + commentText + "</documentation>";
    Document docDoc = DocumentHelper.parseText(documentationText);
    outNode.add(docDoc.getRootElement());
    log("HTML comment: " + commentText, Project.MSG_DEBUG);
}

From source file:com.nokia.helium.core.ant.filters.PrettyPrintXmlFilter.java

License:Open Source License

/**
 * Filter the input string./* w w w . j ava 2  s . c  o  m*/
 * 
 * @param string
 *            the string to filter
 * @return the modified string
 */
public String filter(String token) {
    String output = token;
    XMLWriter writer = null;
    if (token.length() > 0) {
        try {
            Document doc = DocumentHelper.parseText(token);
            StringWriter out = new StringWriter();
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setIndentSize(4);
            writer = new XMLWriter(out, format);
            writer.write(doc);

            output = out.toString();
        } catch (org.dom4j.DocumentException exc) {
            throw new BuildException(exc.getMessage(), exc);
        } catch (IOException exc) {
            throw new BuildException(exc.getMessage(), exc);
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException exc) {
                throw new BuildException(exc.getMessage(), exc);
            }
        }
    }
    return output;
}

From source file:com.noterik.bart.fs.action.CreatePresentationAction.java

License:Open Source License

@Override
public String run() {

    logger.debug("**************************** starting CreatePresentationAction ************************");

    String requestBody = event.getRequestData();
    logger.debug("request body: " + requestBody);

    String vidUri = "";

    try {/* w w w .j  a va2  s.  c  o  m*/
        Document doc = DocumentHelper.parseText(requestBody);
        Node vidNode = doc.selectSingleNode("//referid");

        if (vidNode != null) {
            vidUri = vidNode.getText();
        }
    } catch (Exception e) {
        logger.error("", e);
    }

    String vidId = vidUri.substring(vidUri.lastIndexOf("/") + 1);
    String userUri = vidUri.substring(0, vidUri.lastIndexOf("/video"));

    logger.debug("video uri: " + vidUri);
    logger.debug("video id: " + vidId);
    logger.debug("user uri: " + userUri);

    // check if presentation already exists
    String presUri = userUri + "/presentation/p" + vidId;
    logger.debug("presentation uri: " + presUri);

    Boolean has = FSXMLRequestHandler.instance().hasProperties(presUri);
    if (has) {
        logger.debug("presentation already exists, no need to create.");
        return null;
    }

    String title = "";
    // get video properties
    Document vidDoc = FSXMLRequestHandler.instance().getNodeProperties(vidUri, false);
    Node titleNode = vidDoc.selectSingleNode(".//title");

    if (titleNode != null) {
        title = titleNode.getText();
    }

    String presxml = buildPresXML(vidUri, title);
    logger.debug("xml to create presentation: " + presxml);

    // create the presentation
    String presPropsUri = presUri + "/properties";

    logger.debug("about to set xml for presentation: " + presxml + " into url: " + presPropsUri);
    FSXMLRequestHandler.instance().handlePUT(presPropsUri, presxml);

    // create link in collection
    List<String> uris = FSXMLRequestHandler.instance().getReferParents(vidUri);

    Iterator<String> i = uris.iterator();
    while (i.hasNext()) {
        String uri = i.next();

        if (uri.indexOf(userUri) != -1 && uri.indexOf("collection") != -1) {

            String colUri = uri.substring(0, uri.lastIndexOf("/video"));
            // insert presentation in collection
            String colxml = buildColXML(presUri);
            String colAttrUri = colUri + "/presentation/p" + vidId + "/attributes";

            logger.debug("about to set xml for collection: " + colxml + " into url: " + colAttrUri);
            FSXMLRequestHandler.instance().handlePUT(colAttrUri, colxml);

            return null;
        }
        logger.error("None of the uris was either a collection or belonged to this user.");
        return null;
    }
    logger.error("there was no uri refering to the requested video.");
    return null;

}

From source file:com.noterik.bart.fs.action.CreateRaw2Action.java

License:Open Source License

@Override
public String run() {
    logger.debug("\n\n ######### starting create momar raw action ######\n\n");
    String requestBody = event.getRequestData();
    logger.debug("\n\nRequest Data: " + requestBody);
    String mount = null, original = null, batchFile = null;
    Document doc = null;/*from  w  ww  .j a  v  a 2 s. c om*/

    try {
        if (requestBody != null) {
            doc = DocumentHelper.parseText(requestBody);
            Node node1 = doc.selectSingleNode("//properties/mount");
            Node node2 = doc.selectSingleNode("//properties/original");
            Node node3 = doc.selectSingleNode("//properties/transcoder");
            Node node4 = doc.selectSingleNode("//properties/batchfile");
            if (node3 != null && node3.getText() != null && node3.getText().equals("apu")) {
                logger.debug("The video was already transcoded by apu, skipping raw2 creation");
                return null;
            }
            if (node4 != null && node4.getText() != null) {
                //encoding using specified batchfile
                batchFile = node4.getText();
            }

            //Node useMomar = doc.selectSingleNode("//properties/momar");

            //if(useMomar != null && useMomar.getText().toLowerCase().equals("false")){
            //   logger.debug("\n\n Momar tag is false ! Will not create Momar Job !!\n");
            //   return null;
            //}

            if (node1 != null) {
                mount = node1.getText();
                logger.debug("\n\n\n\n\nFOUND MOUNT: " + mount);
            } else {
                logger.debug("\n\n\n\n\nNO MOUNT FOUND IN PROPERTIES");
            }

            if (node2 != null) {
                original = node2.getText();
                logger.debug("\n\n\n\n\nFOUND ORIGINAL: " + original);
            } else {
                logger.debug(
                        "\n\n\n\n\nNO ORIGINAL FOUND IN PROPERTIES, WHICH MEANS APU UPLOAD, CREATE ORIGINAL ANYWAYS ;)");
                createOriginalTagAfterApuUpload();
                return null;
            }
        }
    } catch (DocumentException e) {
        logger.error("", e);
    }
    String uri = event.getUri();
    logger.debug("CREATE RAW 2 ACTION:\nURI: " + uri);
    String raw2Uri = uri.substring(0, uri.lastIndexOf("/")) + "/2";
    if (!FSXMLRequestHandler.instance().hasProperties(raw2Uri) && mount != null) {
        createRaw2Properties(raw2Uri, mount, batchFile);
    }
    return null;
}