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:org.beangle.emsapp.security.action.MenuAction.java

License:Open Source License

public String saveImportXML() {
    File file = getImportFile();/*from   w w w  . j  a  v  a2 s.com*/
    String text = FileUtil.readFile(file);
    try {
        Document doc = DocumentHelper.parseText(text);
        Element root = doc.getRootElement();
        List<Resource> resources = resourceService.findAll();
        Map<String, Resource> rmap = new HashMap<String, Resource>();
        for (Resource r : resources) {
            rmap.put(r.getName(), r);
        }
        for (Element emenu : (List<Element>) root.elements()) {
            addMenu(emenu, rmap);
        }
    } catch (DocumentException e) {
        logger.error("importXML error", e);
    }
    return redirect("search");
}

From source file:org.bedework.appcommon.NotifyResource.java

License:Apache License

/**
 * @return formatted xml without the header
 *//*from  ww w  .  jav a  2s.  co m*/
public String getXmlFragment() {
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setTrimText(false);
        format.setSuppressDeclaration(true);

        StringWriter sw = new StringWriter();
        XMLWriter writer = new XMLWriter(sw, format);
        writer.write(DocumentHelper.parseText(content));

        return sw.toString();
    } catch (Throwable t) {
        return "<error>" + t.getLocalizedMessage() + "</error>";
    }
}

From source file:org.bigmouth.nvwa.utils.xml.Dom4jDecoder.java

License:Apache License

/**
 * <p>XML???</p>//from  www . ja  v  a 2 s .  c o  m
 * ?
 * appId?
 * ?XMLappId?appid?APPID?app_id?APP_ID
 * @param <T>
 * @param xml
 * @param xpath
 * @param cls
 * @return
 */
public static <T> T decode(String xml, String xpath, Class<T> cls) throws Exception {
    if (StringUtils.isBlank(xml))
        return null;
    T t = cls.newInstance();
    Document doc = DocumentHelper.parseText(xml);
    Node itemNode = doc.selectSingleNode(xpath);

    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
        // if the field name is 'appId'
        String name = field.getName();
        String nodename = name;
        if (field.isAnnotationPresent(Argument.class)) {
            nodename = field.getAnnotation(Argument.class).name();
        }
        // select appId node
        Node current = itemNode.selectSingleNode(nodename);
        if (null == current) {
            // select appid node
            current = itemNode.selectSingleNode(nodename.toLowerCase());
        }
        if (null == current) {
            // select APPID node
            current = itemNode.selectSingleNode(nodename.toUpperCase());
        }
        if (null == current) {
            // select app_id node
            nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(nodename), "_").toLowerCase();
            current = itemNode.selectSingleNode(nodename);
        }
        if (null == current) {
            // select APP_ID node
            nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(nodename), "_").toUpperCase();
            current = itemNode.selectSingleNode(nodename);
        }
        if (null != current) {
            String invokeName = StringUtils.join(new String[] { "set", StringUtils.capitalize(name) });
            try {
                MethodUtils.invokeMethod(t, invokeName, current.getText());
            } catch (NoSuchMethodException e) {
                LOGGER.warn("NoSuchMethod-" + invokeName);
            } catch (IllegalAccessException e) {
                LOGGER.warn("IllegalAccess-" + invokeName);
            } catch (InvocationTargetException e) {
                LOGGER.warn("InvocationTarget-" + invokeName);
            }
        }
    }
    return t;
}

From source file:org.cleverbus.admin.web.msg.MessageController.java

License:Apache License

/**
 * Converts input XML to "nice" XML./*from   w  w  w .  j a v  a2  s .  c o  m*/
 *
 * @param original the original XML
 * @return pretty XML
 */
static String prettyPrintXML(String original) {
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        Document document = DocumentHelper.parseText(original);
        StringWriter sw = new StringWriter();
        XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
        return sw.toString();
    } catch (Exception exc) {
        Log.debug("Error pretty-printing XML: ", exc);
        return original;
    }
}

From source file:org.client.one.service.OAuthAuthenticationService.java

License:Apache License

public boolean registerUserWSSoap(String token, Profile profile) throws DocumentException {
    String msg = "";
    msg += "<registerUserRequest xmlns=\"http://aktios.com/appthree/webservice/model\">";
    msg += "   <token>" + token + "</token>";
    msg += "   <user>";
    msg += "   <username>" + profile.getUsername() + "</username>";
    msg += "   <password>" + profile.getPassword() + "</password>";
    msg += "   <firstName>" + profile.getFirstName() + "</firstName>";
    msg += "   <lastName>" + profile.getLastName() + "</lastName>";
    msg += "   <phoneNumber>" + profile.getPhoneNumber() + "</phoneNumber>";
    msg += "   </user>";
    msg += "</registerUserRequest>";

    StreamSource source = new StreamSource(new StringReader(msg));
    StringResult xmlResult = new StringResult();
    webServiceTemplate.sendSourceAndReceiveToResult(appThreeWebServices, source, xmlResult);
    String res = xmlResult.toString();
    Document doc = DocumentHelper.parseText(res);
    Node nId = doc.selectSingleNode("//ns2:registerUserResponse/ns2:id");
    Integer id = Integer.valueOf(nId.getText());
    // If the ID == -1 an error ocurred
    return (id != -1);
}

From source file:org.codehaus.aspectwerkz.definition.XmlParser.java

License:Open Source License

/**
 * Creates a DOM document./*from w w  w . ja v  a2s  .com*/
 *
 * @param string the string containing the XML
 * @return the DOM document
 * @throws DocumentException
 */
public static Document createDocument(final String string) throws DocumentException {
    return DocumentHelper.parseText(string);
}

From source file:org.codehaus.cargo.util.Dom4JUtil.java

License:Apache License

/**
 * parse the passed string into an {@link Element Element} object.
 * //  w ww.j a  v a2 s  .c  o m
 * @param elementToParse string to parse
 * @return result of parsing
 */
public Element parseIntoElement(String elementToParse) {
    try {
        Document parsed = DocumentHelper.parseText(elementToParse);
        return parsed.getRootElement();
    } catch (DocumentException e) {
        throw new CargoException("Could not parse element: " + elementToParse);
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument.java

License:Educational Community License

public void setResponse(HttpMethod method, int status) throws Exception {
    setStatus(status);//  w  ww. j  a  v  a2s .  com
    InputStream stream = method.getResponseBodyAsStream();
    SAXReader reader = new SAXReader();
    if (isErrorStatus()) {
        log.info("Got error : " + IOUtils.toString(stream));
    }
    // TODO errorhandling
    Document doc = null;
    Header content_type = method.getResponseHeader("Content-Type");
    if (content_type != null && "application/xml".equals(content_type.getValue())) {

        if (log.isDebugEnabled()) {
            ByteArrayOutputStream dump = new ByteArrayOutputStream();
            doc = reader.read(new TeeInputStream(stream, dump));
            log.debug(dump.toString("UTF-8"));
        } else {
            doc = reader.read(stream, "UTF-8");
        }
        //split up document
        Element root = doc.getRootElement();
        // iterate through child elements of root
        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();
            addDocument(element.getName(), DocumentHelper.parseText(element.asXML()));
        }
    }
    stream.close();
}

From source file:org.craftercms.studio.impl.v1.service.site.SiteServiceImpl.java

License:Open Source License

private Map<String, Object> convertNodesFromXml(String xml) {
    try {// ww w  .j a v  a2 s .  c  o m
        InputStream is = new ByteArrayInputStream(xml.getBytes());

        Document document = DocumentHelper.parseText(xml);
        return createMap(document.getRootElement());

    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.dentaku.gentaku.tools.cgen.plugin.GenGenPlugin.java

License:Apache License

public void start() {
    System.out.println("Running " + getClass().getName());
    Collection metadata = mp.getJMIMetadata();
    for (Iterator it = metadata.iterator(); it.hasNext();) {
        Object o = (Object) it.next();
        if (o instanceof ModelElementImpl
                && ((ModelElementImpl) o).getStereotypeNames().contains("GenGenPackage")) {
            ModelElementImpl pkg = (ModelElementImpl) o;
            try {
                // get the two documents out of the model
                Document mappingDoc = DocumentHelper.parseText(
                        (String) pkg.getTaggedValue("gengen.mapping").getDataValue().iterator().next());
                final Document xsdDoc = DocumentHelper
                        .parseText((String) pkg.getTaggedValue("gengen.XSD").getDataValue().iterator().next());

                Collection generators = mappingDoc.selectNodes("/mapping/generator");
                final Map generatorMap = new HashMap();
                for (Iterator getIterator = generators.iterator(); getIterator.hasNext();) {
                    Element element = (Element) getIterator.next();
                    try {
                        Generator g = (Generator) Class.forName(element.attributeValue("canonicalName"))
                                .newInstance();
                        generatorMap.put(element.attributeValue("name"), g);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }/* www .j a  v  a  2  s  . com*/

                }

                // annotate XSD with mapping document
                mappingDoc.accept(new VisitorSupport() {
                    public void visit(Element node) {
                        String path = node.attributeValue("path");
                        if (path != null) {
                            LocalDefaultElement xsdVisit = (LocalDefaultElement) Util.selectSingleNode(xsdDoc,
                                    path);
                            xsdVisit.setAnnotation((LocalDefaultElement) node);
                        }
                        String key = node.attributeValue("ref");
                        if (node.getName().equals("generator") && key != null) {
                            if (generatorMap.keySet().contains(key)) {
                                ((LocalDefaultElement) node).setGenerator((Generator) generatorMap.get(key));
                            } else {
                                throw new RuntimeException(
                                        "generator key '" + key + "' not created or not found");
                            }
                        }
                    }
                });

                // create a new output document
                Document outputDocument = DocumentHelper.createDocument();

                // find element root of mapping document
                Element rootElementCandidate = (Element) Util.selectSingleNode(mappingDoc,
                        "/mapping/element[@location='root']");
                if (rootElementCandidate == null) {
                    throw new RuntimeException("could not find root element of XSD");
                }
                String rootPath = rootElementCandidate.attributeValue("path");
                LocalDefaultElement rootElement = (LocalDefaultElement) Util.selectSingleNode(xsdDoc, rootPath);

                // get the model root (there can be only one...)
                ModelImpl m = Utils.getModelRoot(mp.getModel());

                // pregenerate
                for (Iterator genIterator = generatorMap.values().iterator(); genIterator.hasNext();) {
                    Generator generator = (Generator) genIterator.next();
                    generator.preProcessModel(m);
                }

                // create a visitor and visit the document
                PluginOutputVisitor visitor = new PluginOutputVisitor(xsdDoc, mp.getModel());
                rootElement.accept(visitor, outputDocument, null, null);

                // postegenerate
                for (Iterator genIterator = generatorMap.values().iterator(); genIterator.hasNext();) {
                    Generator generator = (Generator) genIterator.next();
                    generator.postProcessModel(m);
                }

                // generate the output document
                File outputFile;
                Writer destination;
                if (getDestdir() != null) {
                    String dirPath = getDestdir();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                    outputFile = new File(dir, getDestinationfilename());
                    destination = new FileWriter(outputFile);
                } else {
                    outputFile = File.createTempFile("GenGen", ".xml");
                    outputFile.deleteOnExit();
                    destination = new OutputStreamWriter(System.out);
                }

                if (outputDocument.getRootElement() != null) {
                    generateOutput(outputFile, outputDocument, xsdDoc, destination, generatorMap);
                } else {
                    System.out.println("WARNING: no output generated, do you have root tags defined?");
                }

            } catch (DocumentException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (SAXException e) {
                throw new RuntimeException(e);
            } catch (RepositoryException e) {
                throw new RuntimeException(e);
            } catch (GenerationException e) {
                throw new RuntimeException(e);
            }
        }
    }
}