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.publisher.remoting.marshaling.DefaultMarshaler.java

License:Open Source License

protected Object unMarshallResult(String data, CoreSession coreSession) throws PublishingMarshalingException {
    Document document;//  w  w  w . j  ava 2  s  .  c  o m
    try {
        document = DocumentHelper.parseText(data);
        org.dom4j.Element rootElem = document.getRootElement();

        if (rootElem.elements().size() == 0) {
            return rootElem.getText();
        } else {
            return unMarshalSingleObject(((org.dom4j.Element) rootElem.elements().get(0)).asXML(), coreSession);
        }
    } catch (DocumentException e) {
        throw new PublishingMarshalingException("Error during unmarshaling Result", e);
    }
}

From source file:org.nuxeo.ecm.platform.publisher.remoting.marshaling.DefaultMarshaler.java

License:Open Source License

protected Object unMarshalSingleObject(String xml, CoreSession coreSession)
        throws PublishingMarshalingException {
    Document document;//from w  ww  .j  av  a 2  s. c o m
    try {
        document = DocumentHelper.parseText(xml);
        org.dom4j.Element rootElem = document.getRootElement();

        QName qname = rootElem.getQName();
        String name = rootElem.getName();

        if (name.equals("publicationNode")) {
            return nodeMarshaler.unMarshalPublicationNode(xml);
        } else if (name.equals("publishedDocument")) {
            return publishedDocumentMarshaler.unMarshalPublishedDocument(xml);
        } else if (name.equals("document")) {
            return documentModelMarshaler.unMarshalDocument(xml, coreSession);
        } else if (name.equals("documentLocation")) {
            return docLocMarshaler.unMarshalDocumentLocation(xml);
        } else if (name.equals("list")) {
            List<Object> lst = new ArrayList<Object>();
            for (Iterator i = rootElem.elementIterator("listitem"); i.hasNext();) {
                org.dom4j.Element el = (org.dom4j.Element) i.next();
                if (el.elements().size() == 0) {
                    lst.add(el.getText());
                } else {
                    lst.add(unMarshalSingleObject(((org.dom4j.Element) el.elements().get(0)).asXML(),
                            coreSession));
                }
            }
            return lst;
        } else if (name.equals("map")) {
            Map map = new HashMap();
            for (Iterator i = rootElem.elementIterator("mapitem"); i.hasNext();) {
                org.dom4j.Element el = (org.dom4j.Element) i.next();

                Object value = null;
                if (el.elements().size() > 0) {
                    value = unMarshalSingleObject(((org.dom4j.Element) (el).elements().get(0)).asXML(),
                            coreSession);
                } else {
                    value = el.getText();
                }
                String key = el.attributeValue("name");
                map.put(key, value);
            }
            return map;
        }
    } catch (Throwable e) {
        throw new PublishingMarshalingException("Error during unmarshaling", e);
    }

    throw new PublishingMarshalingException("Unable to unmarshal data");

}

From source file:org.nuxeo.ecm.platform.publisher.remoting.marshaling.DefaultPublicationNodeMarshaler.java

License:Open Source License

public PublicationNode unMarshalPublicationNode(String data) throws PublishingMarshalingException {
    PublicationNode node = null;/*from   w ww .  ja  v a 2 s. co m*/

    try {
        Document document = DocumentHelper.parseText(data);
        org.dom4j.Element rootElem = document.getRootElement();

        String nodePath = rootElem.element(nodePathTag).getTextTrim();
        String nodeTitle = rootElem.element(nodeTitleTag).getTextTrim();
        String nodeType = rootElem.element(nodeTypeTag).getTextTrim();
        String treeName = rootElem.element(treeNameTag).getTextTrim();
        String sid = rootElem.element(sidTag).getTextTrim();
        node = new BasicPublicationNode(nodeType, nodePath, nodeTitle, treeName, sid);

    } catch (DocumentException e) {
        throw new PublishingMarshalingException("Unable to unmarshal Piublication Node", e);
    }
    return node;
}

From source file:org.nuxeo.ecm.platform.publisher.remoting.marshaling.DefaultPublishedDocumentMarshaler.java

License:Open Source License

public PublishedDocument unMarshalPublishedDocument(String data) throws PublishingMarshalingException {

    PublishedDocument pubDoc;//from w w  w  .  j  a v a 2s .  c  o m
    try {
        Document document = DocumentHelper.parseText(data);
        org.dom4j.Element rootElem = document.getRootElement();

        String strDocRef = rootElem.element(sourceRefTag).getTextTrim();
        DocumentRef docRef;
        if (strDocRef.startsWith("/"))
            docRef = new PathRef(strDocRef);
        else
            docRef = new IdRef(strDocRef);

        String repo = rootElem.element(repositoryNameTag).getTextTrim();
        String server = rootElem.element(serverNameTag).getTextTrim();
        String version = rootElem.element(versionLabelTag).getTextTrim();
        String path = rootElem.element(pathTag).getTextTrim();
        String parentPath = rootElem.element(parentPathTag).getTextTrim();
        boolean isPending = Boolean.parseBoolean(rootElem.element(isPendingTag).getTextTrim());

        pubDoc = new BasicPublishedDocument(docRef, repo, server, version, path, parentPath, isPending);
    } catch (DocumentException e) {
        throw new PublishingMarshalingException("Unable to unmarshal Published Document", e);
    }
    return pubDoc;
}

From source file:org.nuxeo.ecm.platform.publisher.remoting.marshaling.io.SingleXMlDocumentReader.java

License:Open Source License

public SingleXMlDocumentReader(String data) throws DocumentException {
    xmldoc = DocumentHelper.parseText(data);
}

From source file:org.nuxeo.ecm.platform.scanimporter.service.ScannedFileMapperComponent.java

License:Open Source License

@Override
public ScanFileBlobHolder parseMetaData(File xmlFile) throws Exception {

    Map<String, Serializable> data = new HashMap<String, Serializable>();

    if (mappingDesc == null) {
        return null;
    }//from   ww w. j a  v  a2  s .c o m

    String xmlData = FileUtils.readFile(xmlFile);

    Document xmlDoc = DocumentHelper.parseText(xmlData);

    for (ScanFileFieldMapping fieldMap : mappingDesc.getFieldMappings()) {

        XPath xpath = new Dom4jXPath(fieldMap.getSourceXPath());
        List<?> nodes = xpath.selectNodes(xmlDoc);
        if (nodes.size() == 1) {
            DefaultElement elem = (DefaultElement) nodes.get(0);
            String value = null;
            if ("TEXT".equals(fieldMap.getSourceAttribute())) {
                value = elem.getText();
            } else {
                value = elem.attribute(fieldMap.getSourceAttribute()).getValue();
            }

            String target = fieldMap.getTargetXPath();
            if ("string".equalsIgnoreCase(fieldMap.getTargetType())) {
                data.put(target, value);
                continue;
            } else if ("integer".equalsIgnoreCase(fieldMap.getTargetType())) {
                data.put(target, Integer.parseInt(value));
                continue;
            } else if ("double".equalsIgnoreCase(fieldMap.getTargetType())) {
                data.put(target, Double.parseDouble(value));
                continue;
            } else if ("date".equalsIgnoreCase(fieldMap.getTargetType())) {
                data.put(target, fieldMap.getDateFormat().parse(value));
                continue;
            } else if ("boolean".equalsIgnoreCase(fieldMap.getTargetType())) {
                data.put(target, Boolean.parseBoolean(value));
                continue;
            }
            log.error("Unknown target type, please look the scan importer configuration: "
                    + fieldMap.getTargetType());
        }
        log.error("Mulliple or no element(s) found for: " + fieldMap.sourceXPath + " for "
                + xmlFile.getAbsolutePath());

    }

    List<Blob> blobs = new ArrayList<Blob>();

    for (ScanFileBlobMapping blobMap : mappingDesc.getBlobMappings()) {
        XPath xpath = new Dom4jXPath(blobMap.getSourceXPath());
        List<?> nodes = xpath.selectNodes(xmlDoc);
        for (Object node : nodes) {
            DefaultElement elem = (DefaultElement) node;
            String filePath = elem.attributeValue(blobMap.getSourcePathAttribute());
            String fileName = elem.attributeValue(blobMap.getSourceFilenameAttribute());

            // Mainly for tests
            if (filePath.startsWith("$TMP")) {
                filePath = filePath.replace("$TMP", Framework.getProperty("nuxeo.import.tmpdir"));
            }

            File file = new File(filePath);
            if (file.exists()) {
                Blob blob = new FileBlob(file);
                if (fileName != null) {
                    blob.setFilename(fileName);
                } else {
                    blob.setFilename(file.getName());
                }
                String target = blobMap.getTargetXPath();
                if (target == null) {
                    blobs.add(blob);
                } else {
                    data.put(target, (Serializable) blob);
                }
            } else {
                log.error("File " + file.getAbsolutePath() + " is referenced by " + xmlFile.getAbsolutePath()
                        + " but was not found");
            }
        }
    }

    String targetType = getTargetLeafType();
    DocumentTypeMapper mapper = mappingDesc.getTargetLeafTypeMapper();
    if (mapper != null) {
        targetType = mapper.getTargetDocumentType(xmlDoc, xmlFile);
    }
    ScanFileBlobHolder bh = new ScanFileBlobHolder(blobs, data, targetType);
    return bh;
}

From source file:org.nuxeo.ecm.platform.sync.manager.VocabularySynchronizeManager.java

License:Open Source License

@SuppressWarnings("rawtypes")
protected List<Map<String, Object>> extractVocabulary(String directorySchema, String res)
        throws DocumentException {
    ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Document domDoc = DocumentHelper.parseText(res);
    List nodes = domDoc.selectNodes("//entries/entry");

    SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class);
    Schema vocSchema = schemaManager.getSchema(directorySchema);
    Collection<Field> vocSchemaField = vocSchema.getFields();
    for (Object object : nodes) {
        Node nodeEntry = ((Node) object);
        Map<String, Object> entryMap = new HashMap<String, Object>();
        for (Field field : vocSchemaField) {
            String fieldName = field.getName().getLocalName();
            Type type = field.getType();
            String entryValue = nodeEntry.valueOf("@" + fieldName);
            if (!entryValue.trim().isEmpty()) {
                if (type instanceof StringType) {
                    entryMap.put(fieldName, entryValue);
                } else if (type instanceof LongType) {
                    Long longEntry = Long.valueOf(entryValue);
                    entryMap.put(fieldName, longEntry);
                } else if (type instanceof IntegerType) {
                    Integer integerEntry = Integer.valueOf(entryValue);
                    entryMap.put(fieldName, integerEntry);
                } else {
                    log.warn("Vocabulary sychronizer only serialize int, long or string fields type. "
                            + fieldName + "(" + type.getName() + ") has been ignored");
                }/*w ww .  j a v  a2 s . co  m*/
            }
        }

        list.add(entryMap);
    }
    return list;
}

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

License:Open Source License

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

    File workingDir = getWorkingDir();

    Blob blob = templateDocument.getTemplateBlob();
    String fileName = blob.getFilename();
    List<TemplateInput> params = templateDocument.getParams();
    File sourceZipFile = File.createTempFile("WordXMLTemplate", ".zip");
    blob.transferTo(sourceZipFile);//from ww w.  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.ecm.platform.template.processors.docx.WordXMLRawTemplateProcessor.java

License:Open Source License

@SuppressWarnings("rawtypes")
public List<TemplateInput> getInitialParametersDefinition(Blob blob) throws Exception {
    List<TemplateInput> params = new ArrayList<TemplateInput>();

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

    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");
            DefaultElement valueElem = (DefaultElement) elem.elements().get(0);
            String wordType = valueElem.getName();
            InputType nxType = InputType.StringValue;
            if (wordType.contains("lpwstr")) {
                nxType = InputType.StringValue;
            } else if (wordType.contains("filetime")) {
                nxType = InputType.DateValue;
            } else if (wordType.contains("bool")) {
                nxType = InputType.BooleanValue;
            }/*from  w  ww  . j  av a 2  s.co m*/

            TemplateInput input = new TemplateInput(name);
            input.setType(nxType);
            params.add(input);
        }
    }
    return params;
}

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

License:Open Source License

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

    Blob blob = templateDocument.getTemplateBlob();

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

    if (xmlContent == null) {
        return templateDocument.getAdaptedDoc();
    }/*w w  w .  j a v a  2s.  c om*/

    Document xmlDoc = DocumentHelper.parseText(xmlContent);

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

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

    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(params, false);
    return adaptedDoc;
}