Example usage for org.dom4j Element addText

List of usage examples for org.dom4j Element addText

Introduction

In this page you can find the example usage for org.dom4j Element addText.

Prototype

Element addText(String text);

Source Link

Document

Adds a new Text node with the given text to this element.

Usage

From source file:org.collectionspace.services.id.IDResource.java

License:Educational Community License

/**
 * Appends summary information to an element representing
 * an ID generator instance.// w  w  w  . j a v a  2 s  .  co m
 *
 * @param   instanceElement  An XML element representing an
 *                           ID generator instance.
 *
 * @param   csid             A CollectionSpace ID (CISD) associated with
 *                           the resource representing that instance.
 *
 * @return  The XML element representing an ID generator instance,
 *          with summary information appended.
 */
private Element appendSummaryIDGeneratorInformation(Element instanceElement, String csidValue) {

    Element uri = instanceElement.addElement("uri");
    uri.addText(getRelativePath(csidValue));
    Element csid = instanceElement.addElement("csid");
    csid.addText(csidValue);

    return instanceElement;
}

From source file:org.collectionspace.services.id.IDResource.java

License:Educational Community License

/**
 * Appends detailed information about an ID generator instance,
 * to an element representing that ID generator instance.
 *
 * @param   instanceElement    An XML element representing an
 *                             ID generator instance.
 *
 * @param   generatorInstance  An instance of an ID generator.
 *
 * @return  The XML element representing an ID generator instance,
 *          with detailed information appended.
 */// ww  w .  j  a  v a2 s  .  co m
private Element appendDetailedIDGeneratorInformation(Element instanceElement,
        IDGeneratorInstance generatorInstance) {

    // Append description information.
    Element description = instanceElement.addElement("description");
    description.addText(generatorInstance.getDescription());

    // Append a representative, or sample, ID - of a type that
    // can be generated by this ID generator instance - for display.
    Element displayid = instanceElement.addElement("displayid");
    // Return the last generated ID as a representative ID.
    // If no ID has ever been generated by this ID generator instance,
    // return the current ID instead.
    //
    // @TODO This is a short-term kludge.  We may wish to instead
    // generate a static, sample ID, at system initialization
    // or launch time; or generate or load this value once, at the
    // time that an ID generator instance is created.
    String lastgenerated = generatorInstance.getLastGeneratedID();
    if (lastgenerated != null & !lastgenerated.trim().isEmpty()) {
        displayid.addText(lastgenerated);
    } else {
        SettableIDGenerator gen;
        try {
            gen = IDGeneratorSerializer.deserialize(generatorInstance.getGeneratorState());
            String current = gen.getCurrentID();
            if (current != null & !current.trim().isEmpty()) {
                displayid.addText(current);
            }
        } catch (Exception e) {
            // Do nothing here.
            // @TODO
            // Could potentially return an error message, akin to:
            // displayid.addText("No ID available for display");
        }
    }

    // Append components information.
    Element generator = instanceElement.addElement(ID_GENERATOR_COMPONENTS_NAME);
    // Get an XML string representation of the ID generator's components.
    String generatorStr = generatorInstance.getGeneratorState();
    // Convert the XML string representation of the ID generator's
    // components to a new XML document, copy its root element, and
    // append it to the relevant location within the current element.
    try {
        Document generatorDoc = XmlTools.textToXMLDocument(generatorStr);
        Element generatorRoot = generatorDoc.getRootElement();
        generator.add(generatorRoot.createCopy());
        // If an error occurs parsing the XML string representation,
        // the text of the components element will remain empty.
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Error parsing XML text: " + generatorStr);
        }
    }

    return instanceElement;
}

From source file:org.craftercms.cstudio.impl.repository.alfresco.AlfrescoContentRepository.java

License:Open Source License

@Override
public InputStream getMetadataStream(String site, String path) {
    PersistenceManagerService persistenceManagerService = _servicesManager
            .getService(PersistenceManagerService.class);
    NodeRef nodeRef = persistenceManagerService
            .getNodeRef(SITE_REPO_ROOT_PATTERN.replaceAll(SITE_REPLACEMENT_PATTERN, site), path);
    Map<QName, Serializable> contentProperties = persistenceManagerService.getProperties(nodeRef);
    Document metadataDoc = DocumentHelper.createDocument();
    Element root = metadataDoc.addElement("metadata");
    for (Map.Entry<QName, Serializable> property : contentProperties.entrySet()) {
        Element elem = root.addElement(property.getKey().getLocalName());
        elem.addText(String.valueOf(property.getValue()));
    }/* w ww  .j  a v a 2 s .c  om*/

    return IOUtils.toInputStream(metadataDoc.asXML());
}

From source file:org.dentaku.services.persistence.XMLUtil.java

License:Apache License

public static void addChild(Element el, String name, Object prop) throws XMLBeanException {
    org.dom4j.Element child = el.addElement(name);

    if (prop instanceof XMLBean) {
        ((XMLBean) prop).getXML(child);// ww w .j  a v  a 2s. c  o m
    } else if (prop instanceof java.util.Date) {
        child.addText(dateFormat.format(prop));
    } else {
        child.addText(prop.toString());
    }
}

From source file:org.dom4j.samples.CreateXMLDemo.java

License:Open Source License

protected Document createDocument() throws Exception {
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("system");

    Properties properties = System.getProperties();
    for (Enumeration elements = properties.propertyNames(); elements.hasMoreElements();) {
        String name = (String) elements.nextElement();
        String value = properties.getProperty(name);
        Element element = root.addElement("property");
        element.addAttribute("name", name);
        element.addText(value);
    }//from  www .  j a v a2s  . c o  m
    return document;
}

From source file:org.eclipse.ecr.core.io.impl.ExportedDocumentImpl.java

License:Open Source License

protected void readProperty(Element parent, Namespace targetNs, Field field, Object value, boolean inlineBlobs)
        throws IOException {
    Type type = field.getType();//from  ww  w. ja va  2  s . co  m
    QName name = QName.get(field.getName().getLocalName(), targetNs.prefix, targetNs.uri);
    Element element = parent.addElement(name);
    if (value == null) {
        return; // have no content
    }

    // extract the element content
    if (type.isSimpleType()) {
        element.addText(type.encode(value));
    } else if (type.isComplexType()) {
        ComplexType ctype = (ComplexType) type;
        if (TypeConstants.isContentType(ctype)) {
            readBlob(element, ctype, (Blob) value, inlineBlobs);
        } else {
            readComplex(element, ctype, (Map) value, inlineBlobs);
        }
    } else if (type.isListType()) {
        if (value instanceof List) {
            readList(element, (ListType) type, (List) value, inlineBlobs);
        } else if (value.getClass().getComponentType() != null) {
            readList(element, (ListType) type, PrimitiveArrays.toList(value), inlineBlobs);
        } else {
            throw new IllegalArgumentException("A value of list type is neither list neither array: " + value);
        }
    }
}

From source file:org.eclipse.ecr.core.io.impl.TypedExportedDocumentImpl.java

License:Open Source License

/**
 * Here we do what super does but add the "type" attribute to the XML
 * elements.//from  w w  w . java2 s. c  o m
 */
@Override
@SuppressWarnings("rawtypes")
protected void readProperty(Element parent, Namespace targetNs, Field field, Object value, boolean inlineBlobs)
        throws IOException {
    Type type = field.getType();
    QName name = QName.get(field.getName().getLocalName(), targetNs.prefix, targetNs.uri);
    Element element = parent.addElement(name);

    // extract the element content
    if (type.isSimpleType()) {
        element.addAttribute(TYPE_ATTRIBUTE, getSimpleTypeId(type));
        if (value != null) {
            element.addText(type.encode(value));
        }
    } else if (type.isComplexType()) {
        ComplexType ctype = (ComplexType) type;
        if (TypeConstants.isContentType(ctype)) {
            element.addAttribute(TYPE_ATTRIBUTE, TypeConstants.CONTENT);
            if (value != null) {
                readBlob(element, ctype, (Blob) value, inlineBlobs);
            }
        } else {
            element.addAttribute(TYPE_ATTRIBUTE, COMPLEX_TYPE_ID);
            if (value != null) {
                readComplex(element, ctype, (Map) value, inlineBlobs);
            }
        }
    } else if (type.isListType()) {
        element.addAttribute(TYPE_ATTRIBUTE,
                ((ListType) type).isScalarList() ? SCALAR_LIST_TYPE_ID : COMPLEX_LIST_TYPE_ID);
        if (value != null) {
            if (value instanceof List) {
                readList(element, (ListType) type, (List) value, inlineBlobs);
            } else if (value.getClass().getComponentType() != null) {
                readList(element, (ListType) type, PrimitiveArrays.toList(value), inlineBlobs);
            } else {
                throw new IllegalArgumentException(
                        "A value of list type is neither list neither array: " + value);
            }
        }
    }
}

From source file:org.eclipse.jubula.client.core.businessprocess.AbstractXMLReportGenerator.java

License:Open Source License

/**
 * Builds and returns a test report element. Subclasses can create an entire
 * test result hierarchy by recursively calling this method, using the 
 * returned element as an argument for the next method call.
 * /*from   ww w  . jav a  2s.  c  o  m*/
 * @param resultNode
 *      <code>TestResultNode</code> to translate to an XML element.
 * @param element
 *      The XML element to which the result for node will be added.
 *      This can be considered the parent of the returned element.
 * @return The <code>Element</code> created.
 */
protected Element buildElement(Element element, TestResultNode resultNode) {
    Element insertInto = element;
    Object node = resultNode.getNode();
    if (node instanceof ITestSuitePO) {
        ITestSuitePO ts = (ITestSuitePO) node;
        Element suite = element.addElement("testsuite"); //$NON-NLS-1$
        insertInto = suite;
        addGeneralElements(resultNode, insertInto);
        IAUTMainPO aut = ts.getAut();
        Element autEl = suite.addElement("aut"); //$NON-NLS-1$
        autEl.addElement("name").addText(aut.getName()); //$NON-NLS-1$
        autEl.addElement("config").addText(getTestResult().getAutConfigName()); //$NON-NLS-1$
        autEl.addElement("server").addText(getTestResult().getAutAgentHostName()); //$NON-NLS-1$
        autEl.addElement("cmdline-parameter").setText(getTestResult().getAutArguments()); //$NON-NLS-1$
        insertInto = suite.addElement("test-run"); //$NON-NLS-1$
    } else if (node instanceof IEventExecTestCasePO) {
        insertInto = element.addElement("eventhandler"); //$NON-NLS-1$
        addGeneralElements(resultNode, insertInto);
        Element typeEl = insertInto.addElement("type"); //$NON-NLS-1$
        typeEl.addText(I18n.getString(((IEventExecTestCasePO) node).getEventType()));
        Element reentryEl = insertInto.addElement("reentry-property"); //$NON-NLS-1$
        reentryEl.addText(((IEventExecTestCasePO) node).getReentryProp().toString());
    } else if (node instanceof ITestCasePO) {
        insertInto = element.addElement("testcase"); //$NON-NLS-1$
        addGeneralElements(resultNode, insertInto);
    } else if (node instanceof ICapPO) {
        insertInto = element.addElement("step"); //$NON-NLS-1$
        addGeneralElements(resultNode, insertInto);
        addCapElements(resultNode, insertInto, (ICapPO) node);
    } else if (node instanceof ICommentPO) {
        insertInto = element.addElement("comment"); //$NON-NLS-1$
        Element nameElement = insertInto.addElement("name"); //$NON-NLS-1$
        nameElement.addCDATA(((ICommentPO) node).getName());
    } else if (node instanceof IConditionalStatementPO) {
        insertInto = element.addElement("ifthenelse"); //$NON-NLS-1$
        addGeneralElements(resultNode, insertInto);
    } else if (node instanceof IAbstractContainerPO) {
        insertInto = element.addElement("container"); //$NON-NLS-1$
        addGeneralElements(resultNode, insertInto);
    } else if (node instanceof IWhileDoPO) {
        insertInto = element.addElement("whiledo"); //$NON-NLS-1$
        addGeneralElements(resultNode, insertInto);
    } else if (node instanceof IDoWhilePO) {
        insertInto = element.addElement("dowhile"); //$NON-NLS-1$
        addGeneralElements(resultNode, insertInto);
    } else if (node instanceof IIteratePO) {
        insertInto = element.addElement("repeat"); //$NON-NLS-1$
        addGeneralElements(resultNode, insertInto);
    }

    addParamNodeElements(resultNode, insertInto);

    return insertInto;
}

From source file:org.eclipse.jubula.client.core.businessprocess.AbstractXMLReportGenerator.java

License:Open Source License

/**
 * Adds Parameter elements to the given element based on the given 
 * Test Result Node.//from w  w  w .  j  av  a 2 s. c  om
 * 
 * @param resultNode The source for Parameter data.
 * @param insertInto The target for the Parameter data.
 */
protected void addParamNodeElements(TestResultNode resultNode, Element insertInto) {

    for (TestResultParameter parameter : resultNode.getParameters()) {
        String name = parameter.getName();
        String type = parameter.getType();
        String value = parameter.getValue();

        Element paramEl = insertInto.addElement("parameter"); //$NON-NLS-1$

        if (name != null) {
            Element paramNameEl = paramEl.addElement("parameter-name"); //$NON-NLS-1$
            paramNameEl.addText(name);
        }

        if (type != null) {
            Element paramTypeEl = paramEl.addElement("parameter-type"); //$NON-NLS-1$
            paramTypeEl.addText(type);
        }

        if (value != null) {
            Element paramValueEl = paramEl.addElement("parameter-value"); //$NON-NLS-1$
            paramValueEl.addText(value);
        }

        if (!paramEl.hasContent()) {
            insertInto.remove(paramEl);
        }
    }
}

From source file:org.eclipse.jubula.client.core.businessprocess.AbstractXMLReportGenerator.java

License:Open Source License

/**
 * adds information for a Cap to the XML file
 * //from   ww  w. j  a v a  2s .  com
 * @param resultNode
 *      the actual node
 * @param insertInto
 *      where to insert elements in xml
 * @param node
 *      NodePO
 */
protected void addCapElements(TestResultNode resultNode, Element insertInto, ICapPO node) {
    ICapPO cap = node;
    getTimestampFromResultNode(resultNode, insertInto);
    Element compEl = insertInto.addElement("component-name"); //$NON-NLS-1$
    compEl.addText(StringUtils.defaultString(resultNode.getComponentName()));
    Element compTypeEl = insertInto.addElement("component-type"); //$NON-NLS-1$
    compTypeEl.addText(CompSystemI18n.getString(cap.getComponentType(), true));

    double heuristicMatch = resultNode.getOmHeuristicEquivalence();
    if (heuristicMatch >= 0) {
        Element heuristicMatchElement = insertInto.addElement("component-heuristic-match"); //$NON-NLS-1$
        heuristicMatchElement.addText(String.valueOf(heuristicMatch));
    }
    Element actionEl = insertInto.addElement("action-type"); //$NON-NLS-1$
    actionEl.addText(CompSystemI18n.getString(cap.getActionName(), true));
    if (StringUtils.isNotBlank(resultNode.getCommandLog())) {
        Element commandEl = insertInto.addElement("command-log"); //$NON-NLS-1$
        commandEl.addCDATA(resultNode.getCommandLog());
    }
    if (resultNode.getStatus() == TestResultNode.ERROR || resultNode.getStatus() == TestResultNode.RETRYING) {

        Element error = insertInto.addElement("error"); //$NON-NLS-1$
        Element errorType = error.addElement("type"); //$NON-NLS-1$
        TestErrorEvent event = resultNode.getEvent();
        if (event != null) {
            errorType.addText(I18n.getString(event.getId(), true));
            Map<String, Object> eventProps = event.getProps();
            if (eventProps.containsKey(TestErrorEvent.Property.DESCRIPTION_KEY)) {
                String key = (String) eventProps.get(TestErrorEvent.Property.DESCRIPTION_KEY);
                Object[] args = (Object[]) eventProps.get(TestErrorEvent.Property.PARAMETER_KEY);
                args = args != null ? args : new Object[0];
                Element mapEntry = error.addElement("description"); //$NON-NLS-1$
                if (mapEntry != null && key != null) {
                    mapEntry.addText(
                            resultNode.hasBackingNode() ? String.valueOf(I18n.getString(key, args)) : key);
                }
            } else {
                for (Map.Entry<String, Object> entry : eventProps.entrySet()) {
                    if (!TestErrorEvent.Property.DESCRIPTION_KEY.equals(entry.getKey())) {
                        Element mapEntry = error.addElement(entry.getKey());
                        mapEntry.addText(String.valueOf(entry.getValue()));
                    }
                }
            }
        }

        if (ClientTest.instance().isScreenshotForXML()) {
            final byte[] screenshotData = resultNode.getScreenshot();
            if (screenshotData != null) {
                Element screenshotElement = error.addElement("screenshot"); //$NON-NLS-1$
                screenshotElement.addText(new String(Base64.encodeBase64(screenshotData, false)));
            }
        }
    }
}