Example usage for org.dom4j Node getText

List of usage examples for org.dom4j Node getText

Introduction

In this page you can find the example usage for org.dom4j Node getText.

Prototype

String getText();

Source Link

Document

Returns the text of this node.

Usage

From source file:org.mskcc.cbio.portal.scripts.ImportCaisesClinicalXML.java

License:Open Source License

private static List<ClinicalData> parseClinicalDataFromSpecimen(Node patientNode, int cancerStudyId,
        Map<String, String> mapSu2cSampleIdSampleId) {
    List<ClinicalData> clinicalData = new ArrayList<ClinicalData>();
    List<Node> specimenAccessionNodes = patientNode.selectNodes("SpecimenAccessions/SpecimenAccession");
    for (Node specimenAccessionNode : specimenAccessionNodes) {
        String site = null, instrument = null;
        Node node = specimenAccessionNode.selectSingleNode("AccessionAnatomicSite");
        if (node != null) {
            site = node.getText();
        }//w w  w  . j  a v  a2s  . c  o  m
        node = specimenAccessionNode.selectSingleNode("AccessionProcInstrument");
        if (node != null) {
            instrument = node.getText();
        }

        List<Node> specimenNodes = specimenAccessionNode.selectNodes("Specimens/Specimen");
        for (Node specimenNode : specimenNodes) {
            node = specimenNode.selectSingleNode("SpecimenReferenceNumber");
            if (node == null) {
                continue;
            }
            String su2cSampleId = node.getText();
            String sampleId = mapSu2cSampleIdSampleId.get(su2cSampleId);
            if (sampleId == null) {
                continue;
            }

            if (site != null) {
                ClinicalData clinicalDatum = new ClinicalData(cancerStudyId, sampleId, "TUMOR_SITE", site);
                clinicalData.add(clinicalDatum);
            }

            if (instrument != null) {
                ClinicalData clinicalDatum = new ClinicalData(cancerStudyId, sampleId, "PROC_INSTRUMENT",
                        instrument);
                clinicalData.add(clinicalDatum);
            }
        }
    }
    return clinicalData;
}

From source file:org.mskcc.cbio.portal.scripts.ImportCaisesClinicalXML.java

License:Open Source License

private static long parseStatusesAndReturnDiagnosisDate(List<ClinicalEvent> clinicalEvents, Node patientNode,
        String patientId, int cancerStudyId) {
    List<Node> statusNodes = patientNode.selectNodes("Statuses/Status");
    long diagnosisDate = 0;
    for (Node statusNode : statusNodes) {
        Patient patient = DaoPatient.getPatientByCancerStudyAndPatientId(cancerStudyId, patientId);
        ClinicalEvent clinicalEvent = new ClinicalEvent();
        clinicalEvent.setPatientId(patient.getInternalId());
        clinicalEvent.setEventType("STATUS");

        Node node = statusNode.selectSingleNode("StatusDate");
        if (node == null) {
            System.err.println("no date");
            continue;
        }//ww w.  j a v  a2s .c om
        long statusDate = Long.parseLong(node.getText());
        clinicalEvent.setStartDate(statusDate);

        node = statusNode.selectSingleNode("Status");
        if (node == null) {
            System.err.println("no status");
            continue;
        }
        clinicalEvent.addEventDatum("STATUS", node.getText());
        if (node.getText().equalsIgnoreCase("Diagnosis Date")) {
            diagnosisDate = statusDate;
        }

        clinicalEvents.add(clinicalEvent);
    }
    return diagnosisDate;
}

From source file:org.olat.ims.qti.editor.beecom.objects.ChoiceQuestion.java

License:Apache License

/**
 * Called by ItemParser to fetch question/answers.
 * //from   w w  w . j a va  2s . c  o  m
 * @param item
 * @return
 */
public static ChoiceQuestion getInstance(final Element item) {
    final ChoiceQuestion instance = new ChoiceQuestion();
    try {
        final String item_ident = item.attributeValue("ident");
        if (item_ident.startsWith(ItemParser.ITEM_PREFIX_SCQ)) {
            instance.setType(TYPE_SC);
        } else if (item_ident.startsWith(ItemParser.ITEM_PREFIX_MCQ)) {
            instance.setType(TYPE_MC);
        } else if (item_ident.startsWith(ItemParser.ITEM_PREFIX_KPRIM)) {
            instance.setType(TYPE_KPRIM);
        } else {
            return null;
        }

        final Element presentationXML = item.element("presentation");
        Element material = presentationXML.element("material");
        final Element flow = presentationXML.element("flow");
        if (material == null && flow != null) {
            /*
             * This is a bugfix (see OLAT-4194). According to the qti specification, the presentation element can either have the elements material and response_lid
             * as children or they may be children of the flow element which itself is a child of presentation.
             */
            material = flow.element("material");
        }
        final Material matQuestion = (Material) parserManager.parse(material);
        if (matQuestion != null) {
            instance.setQuestion(matQuestion);
        }

        Element response_lid = presentationXML.element("response_lid");
        if (response_lid == null && flow != null) {
            response_lid = flow.element("response_lid");
        }
        final String identQuestion = response_lid.attribute("ident").getText();
        instance.setIdent(identQuestion);
        String shuffle = response_lid.element("render_choice").attributeValue("shuffle");
        if (shuffle == null) {
            shuffle = "Yes";
        }
        instance.setShuffle(shuffle.equals("Yes"));

        // Set first flow_label class that is found for entire question. This
        // editor uses the same flow_label on every response
        final Element flow_label = (Element) response_lid.selectSingleNode(".//flow_label");
        if (flow_label != null) {
            instance.setFlowLabelClass(flow_label.attributeValue("class"));
        }

        final List response_lables = response_lid.selectNodes(".//response_label");
        final List choices = QTIEditHelper.fetchChoices(response_lables);
        instance.setResponses(choices);

        final Element resprocessingXML = item.element("resprocessing");
        if (resprocessingXML != null) {

            final List respconditions = resprocessingXML.elements("respcondition");
            final HashMap points = QTIEditHelper.fetchPoints(respconditions, instance.getType());

            // postprocessing choices
            for (final Iterator i = choices.iterator(); i.hasNext();) {
                final ChoiceResponse choice = (ChoiceResponse) i.next();
                final Float fPoints = (Float) points.get(choice.getIdent());
                if (fPoints != null) {
                    choice.setPoints(fPoints.floatValue());
                    choice.setCorrect(true);
                }
            }

            // get type of multiple choice
            if (instance.getType() == TYPE_MC) {
                // if does not contain any ANDs, assume only one combination
                // of answers is possible (which sets points by a setvar action="Set")
                if (resprocessingXML.selectNodes(".//setvar[@action='Add']").size() == 0) {
                    instance.setSingleCorrect(true);
                    final Collection values = points.values();
                    if (values.size() > 0) {
                        instance.setSingleCorrectScore(((Float) (values.iterator().next())).floatValue());
                    }
                } else {
                    instance.setSingleCorrect(false);
                }
            } else if (instance.getType() == TYPE_SC) {
                instance.setSingleCorrect(true);
                final Collection values = points.values();
                if (values.size() > 0) {
                    instance.setSingleCorrectScore(((Float) (values.iterator().next())).floatValue());
                } else {
                    instance.setSingleCorrect(false);
                }
            } else if (instance.getType() == TYPE_KPRIM) {
                instance.setSingleCorrect(false);
                float maxValue = 0;
                try {
                    final Node score = resprocessingXML
                            .selectSingleNode(".//decvar[@varname='SCORE']/@maxvalue");
                    if (score != null) {
                        maxValue = Float.parseFloat(score.getText());
                    }

                } catch (final NumberFormatException e) {
                    // set maxValue 0
                }
                for (int i = 0; i < choices.size(); i++) {
                    final ChoiceResponse choice = (ChoiceResponse) choices.get(i);
                    if (resprocessingXML
                            .selectNodes("./respcondition[@title='Mastery']/conditionvar/varequal[text()='"
                                    + choice.getIdent() + ":correct']")
                            .size() > 0) {
                        choice.setCorrect(true);
                        choice.setPoints(maxValue / 4);
                    } else {
                        choice.setCorrect(false);
                        choice.setPoints(maxValue / 4);
                    }
                }
            }

            // set min/max score
            QTIEditHelper.configureMinMaxScore(instance,
                    (Element) resprocessingXML.selectSingleNode(".//decvar"));
        }
    } catch (final NullPointerException e) {
        /*
         * A null pointer exeption may occur (and has occured) due to incomplete implementation of the qti specification within OLAT. Since the QTI xml validation at
         * this point already passed, it's hard to still output user information. At this point, definitely log error.
         */
        log.error("Reading choice question failed. Might be due to incomplete qti implementation.", e);
    }
    return instance;
}

From source file:org.onecmdb.core.utils.transform.xml.XPathAttributeSelector.java

License:Open Source License

public IAttributeValue getAttribute(IInstance row) {
    if (row instanceof XMLRow) {
        Node node = ((XMLRow) row).getNode();
        Node selectedNode = null;
        try {// ww w. j a v  a  2  s. c o  m
            selectedNode = node.selectSingleNode(getXpath());
        } catch (InvalidXPathException e) {
            throw new IllegalArgumentException(
                    "Invalid XPath '" + getXpath() + "' in attribute '" + getName() + "'", e);
        }
        if (selectedNode == null) {
            return (new EmptyAttributeValue(this));
            //throw new IllegalArgumentException("Column '" + getXPath() + "' not found in row '" + node.getPath() +"'");
        }
        TextAttributeValue col = new TextAttributeValue(this, selectedNode.getText());
        return (col);
    }
    return (null);
}

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  w w .  j  av  a  2 s . co 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 + "]");
    }
}

From source file:org.openadaptor.auxil.convertor.map.DocumentMapFacade.java

License:Open Source License

/**
 * Retrieve a named value from the underlying Dom4j <code>Document</code>.
 * <p>/*from w w w  .  ja v  a  2s.  c  o m*/
 * The key should have the form of a simplified XPath path.
 * Note that array subscripts are <em>not</em> currently supported.
 * </p>
 * The returned value will be the text of the element identified
 * by the supplied path, unless the <code>valueTypeAttributeName</code> property
 * is set, and the selected element has this attribute. Then
 * the type of the returned value is governed by the value of the
 * type attribute - currently one of <code>Double</code>,<code>Long</code>,<code>Date</code> or <code>String</code>.
 * If <code>valueTypeAttributeName</code> attribute is not set it defaults to <code>String</code>.
 *
 * @param key a simplified XPath path
 * @return The object associated with the supplied key
 * @throws RecordException if the operation cannot be completed.
 */
public Object oldGet(Object key) throws RecordException {
    Object value = null;
    if (document != null) {
        Node node = document.selectSingleNode(key.toString());
        if (node instanceof Element) {
            Element element = (Element) node;
            //If the element is a leaf, use element.getText(), otherwise use element.getName()
            value = Dom4jUtils.getTypedValue(element, valueTypeAttributeName, !element.elements().isEmpty());
        } else {
            if (valueTypeAttributeName != null) {
                log.warn("Cannot get type attribute of non-element node");
                value = node.getText();
            }
        }
    }
    return (value);
}

From source file:org.openadaptor.auxil.convertor.map.Dom4JDocumentMapFacade.java

License:Open Source License

/** 
 * Extract value from a single node// w  ww. j av a 2 s  . c o m
 * <br>
 * <UL>
 *  <LI>If an Element return the element reference.
 *  <LI>If an Attribute return the attribute value
 *  <LI>If text (or CDATA) return it.
 *  <LI>If null return null.
 * @param node Node from which to extract a value
 * @return Reference to Element, or String representation of value.
 */
private Object getSingleValuedResult(Node node) {
    Object result = null;
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        result = (Element) node;
        break;
    case Node.ATTRIBUTE_NODE:
        result = ((Attribute) node).getValue();
        break;
    case Node.TEXT_NODE:
    case Node.CDATA_SECTION_NODE: //Not sure about this one!
        result = node.getText();
        break;
    }
    return result;
}

From source file:org.openadaptor.auxil.convertor.map.Dom4JDocumentMapFacade.java

License:Open Source License

private Object modify(Node node, String value) {
    Object old = null;/*  ww w  .ja v a  2 s .  c  o m*/
    if (node instanceof Element) { //Set the text of the element
        Element element = (Element) node;
        old = element.getText();
        element.setText(value);
    } else if (node instanceof Attribute) {//Test the value of the attribute
        Attribute attribute = (Attribute) node;
        old = attribute.getValue();
        attribute.setValue(value);
    } else if (node instanceof Text) {
        Text text = (Text) node;
        old = node.getText();
        text.setText(value);
    }
    return old;
}

From source file:org.openadaptor.thirdparty.dom4j.Dom4jSimpleRecordAccessor.java

License:Open Source License

/**
 * Retrieve a named value from the underlying Dom4j <code>Document</code>.
 * <p>// ww w.  jav  a2s. c om
 * The key should have the form of a simplified XPath path.
 * Note that array subscripts are <em>not</em> currently supported.
 * </p>
 * The returned value will be the text of the element identified
 * by the supplied path, unless the <code>valueTypeAttributeName</code> property
 * is set, and the selected element has this attribute. Then
 * the type of the returned value is governed by the value of the
 * type attribute - currently one of <code>Double</code>,<code>Long</code>,<code>Date</code> or <code>String</code>.
 * If <code>valueTypeAttributeName</code> attribute is not set it defaults to <code>String</code>.
 *
 * @param key a simplified XPath path
 * @return The object associated with the supplied key
 * @throws RecordException if the operation cannot be completed.
 */
public Object get(Object key) throws RecordException {
    Object value = null;
    if (document != null) {
        Node node = document.selectSingleNode(key.toString());
        if (node instanceof Element) {
            Element element = (Element) node;
            //If the element is a leaf, use element.getText(), otherwise use element.getName()
            value = Dom4jUtils.getTypedValue(element, valueTypeAttributeName, !element.elements().isEmpty());
        } else if (node instanceof Attribute) {
            if (valueTypeAttributeName != null) {
                log.warn("Cannot get type attribute of non-element node");
            }
            value = node.getText();
        }
    }
    return (value);
}

From source file:org.opencms.importexport.CmsImportVersion2.java

License:Open Source License

/**
 * Merges a single page.<p>/*ww w .  j av a 2s. c o  m*/
 * 
 * @param resourcename the resource name of the page
 * @throws CmsImportExportException if something goes wrong
 * @throws CmsXmlException if the page file could not be unmarshalled 
 */
private void mergePageFile(String resourcename) throws CmsXmlException, CmsImportExportException {

    try {

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_START_MERGING_1, resourcename));
        }

        // in OpenCms versions <5 node names have not been case sensitive. thus, nodes are read both in upper
        // and lower case letters, or have to be tested for equality ignoring upper/lower case...

        // get the header file
        CmsFile pagefile = m_cms.readFile(resourcename, CmsResourceFilter.ALL);
        Document contentXml = CmsXmlUtils.unmarshalHelper(pagefile.getContents(), null);

        // get the <masterTemplate> node to check the content. this node contains the name of the template file.
        String masterTemplateNodeName = "//masterTemplate";
        Node masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName);
        if (masterTemplateNode == null) {
            masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName.toLowerCase());
        }
        if (masterTemplateNode == null) {
            masterTemplateNode = contentXml.selectSingleNode(masterTemplateNodeName.toUpperCase());
        }

        // there is only one <masterTemplate> allowed
        String mastertemplate = null;
        if (masterTemplateNode != null) {
            // get the name of the mastertemplate
            mastertemplate = masterTemplateNode.getText().trim();
        }

        // get the <ELEMENTDEF> nodes to check the content.
        // this node contains the information for the body element.
        String elementDefNodeName = "//ELEMENTDEF";
        Node bodyNode = contentXml.selectSingleNode(elementDefNodeName);
        if (bodyNode == null) {
            bodyNode = contentXml.selectSingleNode(elementDefNodeName.toLowerCase());
        }

        // there is only one <ELEMENTDEF> allowed
        if (bodyNode != null) {

            String bodyclass = null;
            String bodyname = null;
            Map bodyparams = null;

            List nodes = ((Element) bodyNode).elements();
            for (int i = 0, n = nodes.size(); i < n; i++) {

                Node node = (Node) nodes.get(i);

                if ("CLASS".equalsIgnoreCase(node.getName())) {
                    bodyclass = node.getText().trim();
                } else if ("TEMPLATE".equalsIgnoreCase(node.getName())) {
                    bodyname = node.getText().trim();
                    if (!bodyname.startsWith("/")) {
                        bodyname = CmsResource.getFolderPath(resourcename) + bodyname;
                    }
                } else if ("PARAMETER".equalsIgnoreCase(node.getName())) {
                    Element paramElement = (Element) node;
                    if (bodyparams == null) {
                        bodyparams = new HashMap();
                    }
                    bodyparams.put((paramElement.attribute("name")).getText(), paramElement.getTextTrim());
                }
            }

            if ((mastertemplate == null) || (bodyname == null)) {

                CmsMessageContainer message = Messages.get().container(
                        Messages.ERR_IMPORTEXPORT_ERROR_CANNOT_MERGE_PAGE_FILE_3, resourcename, mastertemplate,
                        bodyname);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(message.key());
                }

                throw new CmsImportExportException(message);
            }

            // lock the resource, so that it can be manipulated
            m_cms.lockResource(resourcename);

            // get all properties                               
            List properties = m_cms.readPropertyObjects(resourcename, false);

            // now get the content of the bodyfile and insert it into the control file                   
            CmsFile bodyfile = m_cms.readFile(bodyname, CmsResourceFilter.IGNORE_EXPIRATION);

            //get the encoding
            String encoding = CmsProperty.get(CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, properties)
                    .getValue();
            if (encoding == null) {
                encoding = OpenCms.getSystemInfo().getDefaultEncoding();
            }

            if (m_convertToXmlPage) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle()
                            .key(Messages.LOG_IMPORTEXPORT_START_CONVERTING_TO_XML_0));
                }

                CmsXmlPage xmlPage = CmsXmlPageConverter.convertToXmlPage(m_cms, bodyfile.getContents(),
                        getLocale(resourcename, properties), encoding);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(
                            Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_END_CONVERTING_TO_XML_0));
                }

                if (xmlPage != null) {
                    pagefile.setContents(xmlPage.marshal());

                    // set the type to xml page
                    pagefile.setType(CmsResourceTypeXmlPage.getStaticTypeId());
                }
            }

            // add the template and other required properties
            CmsProperty newProperty = new CmsProperty(CmsPropertyDefinition.PROPERTY_TEMPLATE, mastertemplate,
                    null);
            // property lists must not contain equal properties
            properties.remove(newProperty);
            properties.add(newProperty);

            // if set, add the bodyclass as property
            if (CmsStringUtil.isNotEmpty(bodyclass)) {
                newProperty = new CmsProperty(CmsPropertyDefinition.PROPERTY_TEMPLATE, mastertemplate, null);
                newProperty.setAutoCreatePropertyDefinition(true);
                properties.remove(newProperty);
                properties.add(newProperty);
            }
            // if set, add bodyparams as properties
            if (bodyparams != null) {
                for (Iterator p = bodyparams.entrySet().iterator(); p.hasNext();) {
                    Map.Entry entry = (Map.Entry) p.next();
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    newProperty = new CmsProperty(key, value, null);
                    newProperty.setAutoCreatePropertyDefinition(true);
                    properties.remove(newProperty);
                    properties.add(newProperty);
                }
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_START_IMPORTING_XML_PAGE_0));
            }

            // now import the resource
            m_cms.importResource(resourcename, pagefile, pagefile.getContents(), properties);

            // finally delete the old body file, it is not needed anymore
            m_cms.lockResource(bodyname);
            m_cms.deleteResource(bodyname, CmsResource.DELETE_PRESERVE_SIBLINGS);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_END_IMPORTING_XML_PAGE_0));
            }

            m_report.println(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                    I_CmsReport.FORMAT_OK);

        } else {

            // there are more than one template nodes in this control file
            // convert the resource into a plain text file
            // lock the resource, so that it can be manipulated
            m_cms.lockResource(resourcename);
            // set the type to plain
            pagefile.setType(CmsResourceTypePlain.getStaticTypeId());
            // write all changes                     
            m_cms.writeFile(pagefile);
            // done, unlock the resource                   
            m_cms.unlockResource(resourcename);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle()
                        .key(Messages.LOG_IMPORTEXPORT_CANNOT_CONVERT_XML_STRUCTURE_1, resourcename));
            }

            m_report.println(Messages.get().container(Messages.RPT_NOT_CONVERTED_0), I_CmsReport.FORMAT_OK);

        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_END_MERGING_1, resourcename));
        }
    } catch (CmsXmlException e) {

        throw e;
    } catch (CmsException e) {

        m_report.println(e);

        CmsMessageContainer message = Messages.get()
                .container(Messages.ERR_IMPORTEXPORT_ERROR_MERGING_PAGE_FILE_1, resourcename);
        if (LOG.isDebugEnabled()) {
            LOG.debug(message.key(), e);
        }

        throw new CmsImportExportException(message, e);
    }

}