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.dom4j.samples.applets.SimpleAppletDemo.java

License:Open Source License

/**
 * Called after init. Demonstrates the simplicity of parsing in applets.
 *///from w  w w.  j a  v a2s.  c  om
public void start() {
    try {
        demoDocument = DocumentHelper.parseText(DEMO_XML);
        new XMLWriter(OutputFormat.createPrettyPrint()).write(demoDocument);
    } catch (DocumentException documentEx) {
        documentEx.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    demoXPath();
    repaint();
}

From source file:org.ednovo.gooru.application.util.ResourceInstanceFormatter.java

License:Open Source License

private Element getQuestionResource(Question question) {

    StringBuilder questionXML = new StringBuilder(getQuestionSet(question));

    Element resourceElm = DocumentHelper.createElement(RESOURCE);
    if (question.getGooruOid() != null) {
        resourceElm.addAttribute(ID, question.getGooruOid());
    } else {//from w w w  .  j a va 2s .  c  o m
        String resourceId = UUID.randomUUID().toString();
        resourceElm.addAttribute(ID, resourceId);
        question.setGooruOid(resourceId);
    }

    resourceElm.addAttribute(TYPE, ResourceType.Type.QUIZ.getType());

    Element nativeurl = resourceElm.addElement(NATIVE_URL);

    if (question.getUrl() != null) {
        nativeurl.addText(question.getUrl());
    } else {
        nativeurl.addText("");
    }

    Element folder = resourceElm.addElement(RESOURCE_FOLDER);

    if (question.getFolder() != null) {
        folder.addText(question.getFolder());
    } else {
        folder.addText("");
    }

    Element questionSet = null;
    try {
        questionSet = (Element) DocumentHelper.parseText(questionXML.toString()).getRootElement();
    } catch (Exception e) {
        throw new MethodFailureException("Error while converting to a document");
    }
    resourceElm.add(questionSet);

    return resourceElm;
}

From source file:org.ednovo.gooru.application.util.ResourceInstanceFormatter.java

License:Open Source License

public Document getLearnguideDocument(Learnguide learnguide, boolean retriveSkeletons) {
    Document document = null;//from  w  w  w .j  a  v  a  2s. c om
    try {
        String xml = getLearnguide(learnguide, retriveSkeletons).asXML();
        document = DocumentHelper.parseText(xml);
    } catch (Exception e) {
        throw new MethodFailureException("Error while converting xml to document", e);
    }
    return document;
}

From source file:org.efaps.webdav4vfs.data.DavResource.java

License:Apache License

/**
 * Add the value for a given property to the result document. If the value
 * is missing or can not be added for some reason it will return false to
 * indicate a missing property./*from   w  w  w. j  ava2  s .  c o  m*/
 *
 * @param _root         root element for the result document fragment
 * @param _propertyName property name to query
 * @param _ignoreValue  <i>true</i> if values must be ignored
 * @return true for successful addition and false for missing data
 */
@Override()
protected boolean getPropertyValue(final Element _root, final String _propertyName, final boolean ignoreValue) {
    LogFactory.getLog(getClass()).debug(String.format("[%s].get('%s')", object.getName(), _propertyName));
    if (PROP_CREATION_DATE.equals(_propertyName)) {
        return addCreationDateProperty(_root, ignoreValue);
    } else if (PROP_DISPLAY_NAME.equals(_propertyName)) {
        return addGetDisplayNameProperty(_root, ignoreValue);
    } else if (PROP_GET_CONTENT_LANGUAGE.equals(_propertyName)) {
        return addGetContentLanguageProperty(_root, ignoreValue);
    } else if (PROP_GET_CONTENT_LENGTH.equals(_propertyName)) {
        return addGetContentLengthProperty(_root, ignoreValue);
    } else if (PROP_GET_CONTENT_TYPE.equals(_propertyName)) {
        return addGetContentTypeProperty(_root, ignoreValue);
    } else if (PROP_GET_ETAG.equals(_propertyName)) {
        return addGetETagProperty(_root, ignoreValue);
    } else if (PROP_GET_LAST_MODIFIED.equals(_propertyName)) {
        return addGetLastModifiedProperty(_root, ignoreValue);
    } else if (PROP_LOCK_DISCOVERY.equals(_propertyName)) {
        return addLockDiscoveryProperty(_root, ignoreValue);
    } else if (PROP_RESOURCETYPE.equals(_propertyName)) {
        return addResourceTypeProperty(_root, ignoreValue);
    } else if (PROP_SOURCE.equals(_propertyName)) {
        return addSourceProperty(_root, ignoreValue);
    } else if (PROP_SUPPORTED_LOCK.equals(_propertyName)) {
        return addSupportedLockProperty(_root, ignoreValue);
    } else {
        // handle non-standard properties (keep a little separate)
        if (PROP_QUOTA.equals(_propertyName)) {
            return addQuotaProperty(_root, ignoreValue);
        } else if (PROP_QUOTA_USED.equals(_propertyName)) {
            return addQuotaUsedProperty(_root, ignoreValue);
        } else if (PROP_QUOTA_AVAILABLE_BYTES.equals(_propertyName)) {
            return addQuotaAvailableBytesProperty(_root, ignoreValue);
        } else if (PROP_QUOTA_USED_BYTES.equals(_propertyName)) {
            return addQuotaUsedBytesProperty(_root, ignoreValue);
        } else {
            try {
                Object propertyValue = object.getContent().getAttribute(_propertyName);
                if (null != propertyValue) {
                    if (((String) propertyValue).startsWith("<")) {
                        try {
                            Document property = DocumentHelper.parseText((String) propertyValue);
                            if (ignoreValue) {
                                property.clearContent();
                            }
                            _root.add(property.getRootElement().detach());
                            return true;
                        } catch (DocumentException e) {
                            LogFactory.getLog(getClass()).error("property value unparsable", e);
                            return false;
                        }
                    } else {
                        Element el = _root.addElement(_propertyName);
                        if (!ignoreValue) {
                            el.addText((String) propertyValue);
                        }
                        return true;
                    }

                }
            } catch (FileSystemException e) {
                LogFactory.getLog(this.getClass())
                        .error(String.format("property '%s' is not supported", _propertyName), e);
            }
        }
    }
    return false;
}

From source file:org.esupportail.lecture.domain.model.Source.java

/**
 * Make Items objects in fonction of itemXPath, xsltURL, xmlStream.
 * @throws ComputeItemsException /*from  w w w.j  a v a2 s . c  om*/
 */
@SuppressWarnings("unchecked")
synchronized private void computeItems() throws ComputeItemsException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("id=" + this.profileId + " - computeItems()");
    }
    if (!itemComputed) {
        try {
            //create dom4j document
            Document document = DocumentHelper.parseText(xmlStream);
            //   get encoding
            String encoding = document.getXMLEncoding();
            //lauch Xpath find
            String x = getItemXPath();
            XPath xpath = document.createXPath(x);
            xpath.setNamespaceURIs(getXPathNameSpaces());
            List<Node> list = xpath.selectNodes(document);
            //List<Node> list = document.selectNodes(getItemXPath());
            Iterator<Node> iter = list.iterator();
            while (iter.hasNext()) {
                Node node = iter.next();
                Item item = new Item(this);
                StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"");
                xml.append(encoding);
                xml.append("\" ?>");
                xml.append(node.asXML());
                String xmlAsString = xml.toString();
                String htmlContent = xml2html(xmlAsString, getXsltURL(), encoding);
                item.setHtmlContent(htmlContent);
                String MobileHtmlContent = xml2html(xmlAsString, getMobileXsltURL(), encoding);
                item.setMobileHtmlContent(MobileHtmlContent);
                //find MD5 of item content for his ID
                byte[] hash = MessageDigest.getInstance("MD5").digest(xmlAsString.getBytes());
                StringBuffer hashString = new StringBuffer();
                for (int i = 0; i < hash.length; ++i) {
                    String hex = Integer.toHexString(hash[i]);
                    if (hex.length() == 1) {
                        hashString.append('0');
                        hashString.append(hex.charAt(hex.length() - 1));
                    } else {
                        hashString.append(hex.substring(hex.length() - 2));
                    }
                }
                item.setId(hashString.toString());
                items.add(item);
            }
        } catch (DocumentException e) {
            String errorMsg = "Error parsing XML content of the source";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        } catch (NoSuchAlgorithmException e) {
            String errorMsg = "MD5 algorithm not supported";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        } catch (XPathException e) {
            String errorMsg = "Xpath with NameSpace not specified in mappings.xml";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        } catch (MappingNotFoundException e) {
            String errorMsg = "Impossible to get itemXPath,XPathNameSpaces and xsltURL";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        } catch (Xml2HtmlException e) {
            String errorMsg = "Impossible to make html content";
            LOG.error(errorMsg, e);
            throw new ComputeItemsException(errorMsg, e);
        }
        itemComputed = true;
    }
}

From source file:org.esupportail.lecture.domain.model.Source.java

/**
 * transform a xml String in a html String with an XSLT.
 * @param xml to transform/*from w  w  w.  j av  a 2 s.  com*/
 * @param xsltFileURL URL of XSLT file
 * @param encoding of xml to transform
 * @return html content
 * @throws Xml2HtmlException 
 */
private String xml2html(final String xml, final String xsltFileURL, final String encoding)
        throws Xml2HtmlException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("id=" + this.profileId + " - xml2html(xml,xsltFileURL)");
    }
    LOG.debug("voici le xsltFileUrl : " + xsltFileURL);
    String ret = null;
    try {
        //       1. Instantiate a TransformerFactory.
        TransformerFactory tFactory = TransformerFactory.newInstance();
        //      2. Use the TransformerFactory to process the stylesheet Source and
        //      generate a Transformer.
        Transformer transformer;
        String xsltFileContent = DomainTools.getXsltFile(xsltFileURL);
        //create dom4j document
        Document document = DocumentHelper.parseText(xsltFileContent);
        //   get encoding
        String xslEncoding = document.getXMLEncoding();
        if (xslEncoding == null) {
            xslEncoding = "UTF-8";
        }
        LOG.debug("voici le xsltFileContent : " + xsltFileContent);
        ByteArrayInputStream inputXsltFile = new ByteArrayInputStream(xsltFileContent.getBytes(xslEncoding));
        StreamSource sourceXsltFile = new StreamSource(inputXsltFile);
        transformer = tFactory.newTransformer(sourceXsltFile);
        //      3. Use the Transformer to transform an XML Source and send the
        //      output to a Result object.
        ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes(encoding));
        StreamSource source = new StreamSource(inputStream);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(outputStream);
        transformer.transform(source, result);
        ret = outputStream.toString("UTF-8");
    } catch (TransformerConfigurationException e) {
        String errorMsg = "Error in XSTL Transformation configuration";
        LOG.error(errorMsg);
        throw new Xml2HtmlException(errorMsg, e);
    } catch (TransformerException e) {
        String errorMsg = "Error in XSTL Transformation";
        LOG.error(errorMsg);
        throw new Xml2HtmlException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "IO Error in xml2html";
        LOG.error(errorMsg);
        throw new Xml2HtmlException(errorMsg, e);
    } catch (DocumentException e) {
        String errorMsg = "Error determining XSLT encoding";
        LOG.error(errorMsg);
        throw new Xml2HtmlException(errorMsg, e);
    }
    return ret;
}

From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java

License:Apache License

public void addSectiontoList(String sectionsSeqXML, String section_id) {
    try {//ww w  .j  a  v a  2  s  .co  m
        // if first section is added
        if (sectionsSeqXML == null || sectionsSeqXML.length() == 0) {
            addSection(section_id);
            return;
        }
        // add section to existing list
        subSection4jDOM = DocumentHelper.parseText(sectionsSeqXML);
        //The parseText call loses the internal DTD definition, so need to set it again
        setInternalDTD();
        Element thisElement = subSection4jDOM.elementByID(section_id);

        //This code checks to see if this section id already exists in the xml string
        if (thisElement == null)
            addSection(section_id);
        else
            logger.debug("Trying to insert duplicate section " + section_id);

    } catch (DocumentException de) {
        if (logger.isDebugEnabled()) {
            logger.debug("error reading subsections xml string" + de.toString());
            de.printStackTrace();
        }
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("some other error on reading subsections xml string" + ex.toString());
            ex.printStackTrace();
        }
    }
}

From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java

License:Apache License

public List getAllSections(String modSeqXml) throws Exception {
    List allsections = null;//from   www. j av  a  2  s  .co m
    subSection4jDOM = DocumentHelper.parseText(modSeqXml);
    setInternalDTD();
    Element root = subSection4jDOM.getRootElement();
    allsections = subSection4jDOM.selectNodes("//section");
    return allsections;
}

From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java

License:Apache License

public int noOfTopLevelSections(String modSeqXml) {
    try {//from   ww  w  .j  a va  2  s.  c om
        subSection4jDOM = DocumentHelper.parseText(modSeqXml);
        setInternalDTD();
        Element root = subSection4jDOM.getRootElement();
        return root.elements().size();
    } catch (Exception e) {
        return 0;
    }
}

From source file:org.exoplatform.services.xmpp.util.HistoryUtils.java

License:Open Source License

private static Date getDelayedDate(Message message) {
    Document document;//ww w.j  av a 2  s  . c o  m
    Date delayedDate = null;
    DateFormat delayedFormatter = new SimpleDateFormat(XMPP_DELAY_DATETIME_FORMAT);
    try {
        String xmlns = message.getExtension("jabber:x:delay").toXML();
        document = DocumentHelper.parseText(xmlns);
        Element delayInformation = document.getRootElement();
        delayedDate = delayedFormatter.parse(delayInformation.attributeValue("stamp"));
    } catch (Exception e) {
        return null;
    }
    return delayedDate;
}