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.nuxeo.ecm.platform.template.XMLSerializer.java

License:Open Source License

public static List<TemplateInput> readFromXml(String xml) throws Exception {

    List<TemplateInput> result = new ArrayList<TemplateInput>();

    Document xmlDoc = DocumentHelper.parseText(xml);

    List nodes = xmlDoc.getRootElement().elements(fieldTag);

    for (Object node : nodes) {

        DefaultElement elem = (DefaultElement) node;
        Attribute name = elem.attribute("name");
        TemplateInput param = new TemplateInput(name.getValue());

        InputType type = InputType.StringValue;

        if (elem.attribute("type") != null) {
            type = InputType.getByValue(elem.attribute("type").getValue());
            param.setType(type);/*from ww  w . j  ava2 s . c  om*/
        }

        String strValue = elem.attributeValue("value");
        if (InputType.StringValue.equals(type)) {
            param.setStringValue(strValue);
        } else if (InputType.DateValue.equals(type)) {
            param.setDateValue(dateFormat.parse(strValue));
        } else if (InputType.BooleanValue.equals(type)) {
            param.setBooleanValue(new Boolean(strValue));
        } else {
            param.setSource(elem.attributeValue("source"));
        }

        if (elem.attribute("readonly") != null) {
            param.setReadOnly(Boolean.parseBoolean(elem.attributeValue("readonly")));
        }

        if (elem.attribute("autoloop") != null) {
            param.setAutoLoop(Boolean.parseBoolean(elem.attributeValue("autoloop")));
        }

        param.setDesciption(elem.getText());

        result.add(param);
    }

    return result;
}

From source file:org.nuxeo.template.processors.docx.WordXMLRawTemplateProcessor.java

License:Open Source License

@SuppressWarnings("rawtypes")
public Blob renderTemplate(TemplateBasedDocument templateDocument, String templateName) throws Exception {

    File workingDir = getWorkingDir();

    Blob blob = templateDocument.getTemplateBlob(templateName);
    String fileName = blob.getFilename();
    List<TemplateInput> params = templateDocument.getParams(templateName);
    File sourceZipFile = File.createTempFile("WordXMLTemplate", ".zip");
    blob.transferTo(sourceZipFile);/*from  www  .j  a va 2 s  . c  o m*/

    ZipUtils.unzip(sourceZipFile, workingDir);

    File xmlCustomFile = new File(workingDir.getAbsolutePath() + "/docProps/custom.xml");

    String xmlContent = FileUtils.readFile(xmlCustomFile);

    Document xmlDoc = DocumentHelper.parseText(xmlContent);

    List nodes = xmlDoc.getRootElement().elements();

    for (Object node : nodes) {
        DefaultElement elem = (DefaultElement) node;
        if ("property".equals(elem.getName())) {
            String name = elem.attributeValue("name");
            TemplateInput param = getParamByName(name, params);
            DefaultElement valueElem = (DefaultElement) elem.elements().get(0);
            String strValue = "";
            if (param.isSourceValue()) {
                Property property = templateDocument.getAdaptedDoc().getProperty(param.getSource());
                if (property != null) {
                    Serializable value = templateDocument.getAdaptedDoc().getPropertyValue(param.getSource());
                    if (value != null) {
                        if (value instanceof Date) {
                            strValue = wordXMLDateFormat.format((Date) value);
                        } else {
                            strValue = value.toString();
                        }
                    }
                }
            } else {
                if (InputType.StringValue.equals(param.getType())) {
                    strValue = param.getStringValue();
                } else if (InputType.BooleanValue.equals(param.getType())) {
                    strValue = param.getBooleanValue().toString();
                } else if (InputType.DateValue.equals(param.getType())) {
                    strValue = wordXMLDateFormat.format(param.getDateValue());
                }
            }
            valueElem.setText(strValue);
        }
    }

    String newXMLContent = xmlDoc.asXML();

    File newZipFile = File.createTempFile("newWordXMLTemplate", ".docx");
    xmlCustomFile.delete();
    File newXMLFile = new File(xmlCustomFile.getAbsolutePath());
    FileUtils.writeFile(newXMLFile, newXMLContent);

    File[] files = workingDir.listFiles();
    ZipUtils.zip(files, newZipFile);

    // clean up
    FileUtils.deleteTree(workingDir);
    sourceZipFile.delete();
    newZipFile.deleteOnExit();

    Blob newBlob = new FileBlob(newZipFile);
    newBlob.setFilename(fileName);

    return newBlob;
}

From source file:org.nuxeo.template.processors.docx.WordXMLRawTemplateProcessor.java

License:Open Source License

@SuppressWarnings("rawtypes")
public DocumentModel updateDocumentFromBlob(TemplateBasedDocument templateDocument, String templateName)
        throws Exception {

    Blob blob = templateDocument.getTemplateBlob(templateName);

    String xmlContent = readPropertyFile(blob.getStream());

    if (xmlContent == null) {
        return templateDocument.getAdaptedDoc();
    }//from  w w w  . j  a va2  s  .c  o m

    Document xmlDoc = DocumentHelper.parseText(xmlContent);

    List nodes = xmlDoc.getRootElement().elements();

    DocumentModel adaptedDoc = templateDocument.getAdaptedDoc();
    List<TemplateInput> params = templateDocument.getParams(templateName);

    for (Object node : nodes) {
        DefaultElement elem = (DefaultElement) node;
        if ("property".equals(elem.getName())) {
            String name = elem.attributeValue("name");
            TemplateInput param = getParamByName(name, params);
            DefaultElement valueElem = (DefaultElement) elem.elements().get(0);
            String xmlValue = valueElem.getTextTrim();
            if (param.isSourceValue()) {
                // XXX this needs to be rewritten

                if (String.class.getSimpleName().equals(param.getType())) {
                    adaptedDoc.setPropertyValue(param.getSource(), xmlValue);
                } else if (InputType.BooleanValue.equals(param.getType())) {
                    adaptedDoc.setPropertyValue(param.getSource(), new Boolean(xmlValue));
                } else if (Date.class.getSimpleName().equals(param.getType())) {
                    adaptedDoc.setPropertyValue(param.getSource(), wordXMLDateFormat.parse(xmlValue));
                }
            } else {
                if (InputType.StringValue.equals(param.getType())) {
                    param.setStringValue(xmlValue);
                } else if (InputType.BooleanValue.equals(param.getType())) {
                    param.setBooleanValue(new Boolean(xmlValue));
                } else if (InputType.DateValue.equals(param.getType())) {
                    param.setDateValue(wordXMLDateFormat.parse(xmlValue));
                }
            }
        }
    }
    adaptedDoc = templateDocument.saveParams(templateName, params, false);
    return adaptedDoc;
}

From source file:org.nuxeo.template.XMLSerializer.java

License:Open Source License

public static List<TemplateInput> readFromXml(String xml) throws Exception {

    List<TemplateInput> result = new ArrayList<TemplateInput>();

    Document xmlDoc = DocumentHelper.parseText(xml);

    @SuppressWarnings("rawtypes")
    List nodes = xmlDoc.getRootElement().elements(fieldTag);

    for (Object node : nodes) {

        DefaultElement elem = (DefaultElement) node;
        Attribute name = elem.attribute("name");
        TemplateInput param = new TemplateInput(name.getValue());

        InputType type = InputType.StringValue;

        if (elem.attribute("type") != null) {
            type = InputType.getByValue(elem.attribute("type").getValue());
            param.setType(type);//from   w w w  .j ava 2 s .  c om
        }

        String strValue = elem.attributeValue("value");
        if (InputType.StringValue.equals(type)) {
            param.setStringValue(strValue);
        } else if (InputType.DateValue.equals(type)) {
            param.setDateValue(dateFormat.parse(strValue));
        } else if (InputType.BooleanValue.equals(type)) {
            param.setBooleanValue(new Boolean(strValue));
        } else {
            param.setSource(elem.attributeValue("source"));
        }

        if (elem.attribute("readonly") != null) {
            param.setReadOnly(Boolean.parseBoolean(elem.attributeValue("readonly")));
        }

        if (elem.attribute("autoloop") != null) {
            param.setAutoLoop(Boolean.parseBoolean(elem.attributeValue("autoloop")));
        }

        param.setDesciption(elem.getText());

        result.add(param);
    }

    return result;
}

From source file:org.onosproject.drivers.huawei.HuaweiXmlParser.java

License:Apache License

/**
 * Parses system info xml reply.//from  www .  j a v a 2  s  .  c  o m
 */
void parseSysInfo() {
    Document doc;
    try {
        doc = DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        throw new IllegalArgumentException(DEV_PARSE_ERR);
    }

    Element root = doc.getRootElement();
    Element parent = root.element(DATA).element(SYS).element(SYS_INFO);
    info[0] = parent.element(SYS_NAME).getText();
    info[1] = parent.element(PDT_VER).getText();
    info[2] = parent.element(PLATFORM_VER).getText();
    info[3] = parent.element(SYS_ID).getText();
}

From source file:org.onosproject.drivers.huawei.HuaweiXmlParser.java

License:Apache License

private Iterator getInterfaceIterator() {
    Document doc;//from w w  w  . ja v  a 2 s .  co  m
    try {
        doc = DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        throw new IllegalArgumentException(INT_PARSE_ERR);
    }
    Element root = doc.getRootElement();
    Element parent = root.element(DATA).element(IFM).element(IFS);
    return parent.elementIterator(IF);
}

From source file:org.onosproject.yang.serializers.xml.XmlSerializer.java

License:Apache License

@Override
public CompositeData decode(CompositeStream external, YangSerializerContext context) {

    try {/*from   w  ww.j  av  a  2 s . c  om*/
        //parse XML input
        String xmlInput = addRootElementWithAnnotation(external.resourceData(),
                context.getProtocolAnnotations());
        Document document = DocumentHelper.parseText(xmlInput);

        // initialize all the required builders
        CompositeData.Builder cBuilder = DefaultCompositeData.builder();
        ResourceData.Builder rdBuilder = DefaultResourceData.builder();
        XmlWalker walker = new DefaultXmlWalker();
        XmlSerializerListener listener = new XmlSerializerListener();
        listener.cBuilder(cBuilder);

        String uri = external.resourceId();
        if (uri == null) {
            listener.dnBuilder(initializeDataNode(context));
            walker.walk(listener, document.getRootElement(), document.getRootElement());
            rdBuilder = rdBuilder.addDataNode(listener.dnBuilder().build());
        } else {
            /*
             * If URI is not null, then each first level elements is
             * converted to data node and added to list of data nodes in
             * resource data
             */
            ResourceId.Builder rIdBuilder = convertUriToRid(uri, context);
            Element rootElement = document.getRootElement();
            if (rootElement.hasContent() && !rootElement.isTextOnly()) {
                Iterator i = rootElement.elementIterator();
                while (i.hasNext()) {
                    Element childElement = (Element) i.next();
                    listener.dnBuilder(initializeDataNode(rIdBuilder));
                    walker.walk(listener, childElement, rootElement);
                    rdBuilder = rdBuilder.addDataNode(listener.dnBuilder().build());
                }
            }
            rdBuilder.resourceId(rIdBuilder.build());
        }
        return cBuilder.resourceData(rdBuilder.build()).build();
    } catch (DocumentException e) {
        throw new XmlSerializerException(e.getMessage());
    } catch (IOException e) {
        throw new XmlSerializerException(e.getMessage());
    }
}

From source file:org.onosproject.yms.app.ych.defaultcodecs.xml.DefaultXmlCodec.java

License:Apache License

@Override
public YdtBuilder decodeCompositeProtocolDataToYdt(YangCompositeEncoding protoData, Object schemaReg,
        YmsOperationType opType) {/*from www  .  j  a v  a 2  s. co  m*/

    YdtExtendedBuilder extBuilder = new YangRequestWorkBench(E_RESTCONF_ROOT, null, opType,
            (YangSchemaRegistry) schemaReg, false);

    DefaultCodecUtils.convertUriToYdt(protoData.getResourceIdentifier(), extBuilder, CREATE);
    Document document;

    try {
        document = DocumentHelper.parseText(protoData.getResourceInformation());
    } catch (DocumentException e) {
        throw new YchException(E_ROOT_ELEMENT);
    }

    XmlCodecListener listener = new XmlCodecListener();
    listener.setYdtExtBuilder(extBuilder);

    // Walk through xml and build the yang data tree.
    XmlWalker walker = new DefaultXmlCodecWalker();
    walker.walk(listener, document.getRootElement(), document.getRootElement());
    return extBuilder;
}

From source file:org.onosproject.yms.app.ych.defaultcodecs.xml.DefaultXmlCodec.java

License:Apache License

@Override
public YdtBuilder decodeProtocolDataToYdt(String protoData, Object schemaReg, YmsOperationType opType) {
    Document document;//  ww  w  .j  a  v a2s  . c  o m

    try {
        document = DocumentHelper.parseText(protoData);
    } catch (DocumentException e) {
        throw new YchException(E_ROOT_ELEMENT);
    }

    NetconfCodec codec = new NetconfCodec();
    // Find the root element in xml string
    Element rootElement = codec.getDataRootElement(document.getRootElement(), opType);

    if (rootElement == null) {
        throw new YchException(E_ROOT_KEY_ELEMENT);
    }

    // Get the YDT builder for the logical root name.
    YdtExtendedBuilder extBuilder = new YangRequestWorkBench(rootElement.getName(),
            rootElement.getNamespaceURI(), opType, (YangSchemaRegistry) schemaReg, false);

    XmlCodecListener listener = new XmlCodecListener();
    listener.setYdtExtBuilder(extBuilder);
    // Walk through xml and build the yang data tree.
    XmlWalker walker = new DefaultXmlCodecWalker();
    walker.walk(listener, rootElement, rootElement);
    return extBuilder;
}

From source file:org.openadaptor.auxil.connector.jms.JMSPropertiesMessageGenerator.java

License:Open Source License

public Message createMessage(Object messageRecord, Session session) throws JMSException {
    String key = null;//w  ww. ja  va  2s  . c o m
    String value = null;
    String path = null;

    try {
        Document document = null;
        String mr;

        if (getIsXml()) { // Will cope with either a string with valid xml or a Dom4j Document.
            if (messageRecord instanceof Document) {
                document = (Document) messageRecord;
                mr = document.asXML();
            } else if ((messageRecord instanceof String)) {
                mr = (String) messageRecord;
                document = DocumentHelper.parseText(mr);
            } else { // Since we are creating a TextMessage
                throw new RecordFormatException("Unsupported record type [" + messageRecord.getClass().getName()
                        + "]. Must be either XML or a Dom4j Document.");
            }
        } else {
            try {
                mr = (String) messageRecord;
            } catch (ClassCastException cce) {
                throw new RecordFormatException("Unsupported record type [" + messageRecord.getClass().getName()
                        + "]. With isXML false this must be a String as we wish to create a TextMessage.");
            }

        }

        // Now convert to TextMessage and return
        TextMessage tm = session.createTextMessage();

        for (Iterator keys = _properties.keySet().iterator(); keys.hasNext();) {
            key = (String) keys.next();
            path = (String) _properties.get(key);
            if (path.startsWith("//") && this.getIsXml() && document != null) { // we have an XPath
                // use xpath to get the value from the message
                Node node = document.selectSingleNode(path);
                if (node != null) {
                    value = node.getText();
                    tm.setStringProperty(key, value);
                } else {
                    throw new ProcessingException("XPATH with value [" + path + "] does not exist in XML");
                }
            } else { // we have a literal
                tm.setStringProperty(key, path);
            }
        }

        tm.setText(mr);

        return tm;
    } catch (DocumentException e) {
        throw new RecordFormatException("Unable to generate Document from record [" + messageRecord + "]");
    }
}