Example usage for org.dom4j Element elements

List of usage examples for org.dom4j Element elements

Introduction

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

Prototype

List<Element> elements(QName qName);

Source Link

Document

Returns the elements contained in this element with the given fully qualified name.

Usage

From source file:architecture.common.license.License.java

License:Apache License

public static License fromXML(String xml) {
    try {//from w ww. j a  v  a2 s  . c  o m
        Document d = DocumentHelper.parseText(xml);
        Element root = d.getRootElement();
        License l = new License();
        String id = root.attributeValue("id");
        if (id == null)
            throw new LicenseException(L10NUtils.format("002105"));
        l.setID(Long.parseLong(id));
        String name0 = root.attributeValue("name");
        if (name0 == null)
            throw new LicenseException(L10NUtils.format("002106"));
        l.setName(name0);
        String edition = root.attributeValue("edition");
        if (edition != null)
            l.setEdition(edition);
        String dateString = root.attributeValue("creationDate");
        if (dateString == null)
            throw new LicenseException(L10NUtils.format("002107"));
        try {
            Date date = parseDate(dateString);
            l.setCreationDate(date);
        } catch (Exception e) {
            throw new LicenseException(L10NUtils.format("002108"));
        }
        String license = root.attributeValue("version");
        if (license == null)
            throw new LicenseException(L10NUtils.format("002109"));
        l.setVersion(Version.parseVersion(license));
        try {
            l.setType(Type.valueOf(root.attributeValue("type")));
        } catch (IllegalArgumentException e) {
            throw new LicenseException(L10NUtils.format("002110"));
        }
        Element clientElement = root.element("client");
        Client client = new Client();
        client.setName(clientElement.attributeValue("name"));
        client.setCompany(clientElement.attributeValue("company"));
        l.setClient(client);

        for (Element e : (List<Element>) root.elements("module")) {
            Module m = new Module();
            m.setName(e.attributeValue("name"));
            l.getModules().add(m);
        }

        Map<String, String> properties = new HashMap<String, String>();
        for (Element e : (List<Element>) root.elements("property")) {
            String name = e.attributeValue("name");
            String value = e.getTextTrim();
            properties.put(name, value);
        }

        l.setProperties(properties);
        Element sig = root.element("signature");
        l.setSignature(sig.getTextTrim());
        return l;
    } catch (DocumentException e) {
        log.fatal(e.getMessage(), e);
        throw new LicenseException(L10NUtils.format("002111"), e);
    }
}

From source file:batch.performance.visualizer.om.Result.java

License:Open Source License

public void parse(Document dom) throws IOException {
    List runs = dom.getRootElement().elements("run");
    for (Iterator itr = runs.iterator(); itr.hasNext();) {
        Element run = (Element) itr.next();
        final String date = run.attributeValue("date");

        List groups = run.elements("group");
        for (Iterator jtr = groups.iterator(); jtr.hasNext();) {
            Element group = (Element) jtr.next();
            final URL testSpec = new URL(group.attributeValue("name"));

            List results = group.elements("result");
            for (Iterator ktr = results.iterator(); ktr.hasNext();) {
                Element result = (Element) ktr.next();

                URL instance = null;
                if (result.attribute("instance") != null)
                    instance = new URL(result.attributeValue("instance"));

                DataSeries ds = createDataSeries(testSpec, result.attributeValue("scenario"),
                        result.attributeValue("mode").equals("speed") ? Profiler.SPEED : Profiler.MEMORY,
                        instance);/*from  www. jav a  2  s  .co m*/
                try {
                    ds.addDataPoint(date, new BigInteger(result.getTextTrim()));
                } catch (NumberFormatException e) {
                    ; // throw away this data point
                }
            }
        }
    }
}

From source file:ch.javasoft.metabolic.parse.ConfiguredParser.java

License:BSD License

/**
 * Parses:/* ww  w  . j  av  a 2 s . c  o m*/
 * 
 * <pre>
   <parse type="flux-analyzer">
 <input name="directory" type="file">                     
    <file name="{work-dir}/{-in[1]}"/>   <!-- directory, containing files "reactions", "macromolecules", "macromolecule_synthesis" -->
 </input>
   </parse>
   <parse type="flux-analyzer">
 <input name="reactions-file" type="file">                     
    <file name="{work-dir}/{-in[1]}"/>   <!-- reactions -->
 </input>
 <input name="macromolecules-file" type="file">                     
    <file name="{work-dir}/{-in[2]}"/>   <!-- macromolecules -->
 </input>
 <input name="macromolecule-synthesis-file" type="file">                     
    <file name="{work-dir}/{-in[3]}"/>   <!-- macromolecule_synthesis -->
 </input>
   </parse>
 * </pre>
 * @throws IOException 
 */
@SuppressWarnings("unchecked")
private static MetabolicNetwork parseFluxAnalyzer(Element parseElement) throws XmlConfigException, IOException {
    List<Element> inputs = parseElement.elements(XmlElements.input.getXmlName());
    if (inputs.size() == 1) {
        Element input = inputs.get(0);
        XmlUtil.checkExpectedAttributeValue(input, XmlAttributes.name,
                FluxAnalyzerFileType.directory.getXmlName());
        Element fileEl = XmlUtil.getRequiredSingleChildElement(input, XmlElements.file);
        File file = FileConfigParser.parseFile(fileEl);
        return FluxAnalyserParser.parse(file);
    } else if (inputs.size() == 3) {
        Element inReactions = XmlUtil.getChildElementByAttributeValue(parseElement, XmlElements.input,
                XmlAttributes.name, FluxAnalyzerFileType.reactions_file.getXmlName(),
                true /*throwExceptionIfNull*/);
        Element inMacromolecules = XmlUtil.getChildElementByAttributeValue(parseElement, XmlElements.input,
                XmlAttributes.name, FluxAnalyzerFileType.macromolecules_file.getXmlName(),
                true /*throwExceptionIfNull*/);
        Element inMacromolSynth = XmlUtil.getChildElementByAttributeValue(parseElement, XmlElements.input,
                XmlAttributes.name, FluxAnalyzerFileType.macromolecule_synthesis_file.getXmlName(),
                true /*throwExceptionIfNull*/);
        InputStream stReactions = StreamConfigParser.parseInputStream(inReactions);
        InputStream stMacromolecules = StreamConfigParser.parseInputStream(inMacromolecules);
        InputStream stMacromolSynth = StreamConfigParser.parseInputStream(inMacromolSynth);
        return FluxAnalyserParser.parse(stReactions, stMacromolecules, stMacromolSynth);
    } else {
        throw new XmlConfigException("expected input directory or 3 input files for flux analyzer parse config",
                parseElement);
    }
}

From source file:ch.javasoft.metabolic.parse.SbmlParser.java

License:BSD License

@SuppressWarnings("unchecked")
private CompartmentMetabolicNetwork createNetwork(Element model, Map<String, CompartmentMetabolite> metas,
        Set<CompartmentReaction> reactions, Map<Annotateable, Map<String, String>> annotations)
        throws DocumentException {
    final CompartmentMetabolicNetwork net;
    if (compartmentOnly) {
        //only a network for the desired compartment, everything else is external
        Set<CompartmentMetabolite> cMetas = new LinkedHashSet<CompartmentMetabolite>();
        Set<CompartmentReaction> cReacts = new LinkedHashSet<CompartmentReaction>();
        for (CompartmentMetabolite meta : metas.values()) {
            if (compartmentName.equals(meta.getCompartment())) {
                if (!cMetas.add(meta)) {
                    throw new DocumentException("duplicate metabolite: " + meta.getName());
                }//from   w w w.ja v  a  2s . c o  m
            }
        }
        for (CompartmentReaction react : reactions) {
            ArrayIterable<? extends CompartmentMetaboliteRatio> ratios = react
                    .getMetabolieRatiosForCompartment(compartmentName);
            if (!ratios.isEmpty()) {
                List<CompartmentMetaboliteRatio> newRatios = new ArrayList<CompartmentMetaboliteRatio>(
                        ratios.toGenericArray(false));
                if (!react.getEductRatiosExcludeCompartment(compartmentName).isEmpty()) {
                    //we have also educts from other compartments, which makes this
                    //reaction being an external one                  
                    CompartmentMetabolite cMeta = new CompartmentMetabolite(
                            getExchangeMetaboliteName(react, false /*product*/), compartmentName);
                    CompartmentMetaboliteRatio ratio = new CompartmentMetaboliteRatio(cMeta, -1d);
                    CompartmentReaction xReact = createExchangeReaction(cMeta, true /*uptake*/,
                            react.getConstraints().isReversible());
                    newRatios.add(ratio);
                    if (!cMetas.add(cMeta)) {
                        throw new DocumentException("duplicate metabolite: " + cMeta.getName());
                    }
                    if (!cReacts.add(xReact)) {
                        throw new DocumentException("duplicate reaction: " + xReact.getName());
                    }
                }
                if (!react.getProductRatiosExcludeCompartment(compartmentName).isEmpty()) {
                    CompartmentMetabolite cMeta = new CompartmentMetabolite(
                            getExchangeMetaboliteName(react, true /*product*/), compartmentName);
                    CompartmentMetaboliteRatio ratio = new CompartmentMetaboliteRatio(cMeta, +1d);
                    CompartmentReaction xReact = createExchangeReaction(cMeta, false /*uptake*/,
                            react.getConstraints().isReversible());
                    newRatios.add(ratio);
                    if (!cMetas.add(cMeta)) {
                        throw new DocumentException("duplicate metabolite: " + cMeta.getName());
                    }
                    if (!cReacts.add(xReact)) {
                        throw new DocumentException("duplicate reaction: " + xReact.getName());
                    }
                }
                CompartmentReaction cReact = new CompartmentReaction(react.getName(), react.getFullName(),
                        newRatios, react.getConstraints().isReversible());
                if (!cReacts.add(cReact)) {
                    throw new DocumentException("duplicate reaction: " + cReact.getName());
                }
            }
        }
        net = new CompartmentMetabolicNetwork(cMetas, cReacts);
    } else {
        //add the exchange reactions for the external compartment metabolites
        for (CompartmentMetabolite meta : metas.values()) {
            if (compartmentName.equals(meta.getCompartment())) {
                CompartmentReaction react = createExchangeReaction(meta, false /*uptake*/, true /*reversible*/);
                if (!reactions.add(react)) {
                    throw new DocumentException("duplicate reaction: " + react.getName());
                }
            }
        }
        net = new CompartmentMetabolicNetwork(metas.values(), reactions);
    }

    //set compartment full names
    final Element elCmps = model.element(ELEMENT_COMPARTMENTS);
    for (Element elCmp : (List<Element>) elCmps.elements(ELEMENT_COMPARTMENT)) {
        final String cmpName = elCmp.attributeValue(ATTRIBUTE_ID);
        final String cmpFullName = elCmp.attributeValue(ATTRIBUTE_NAME);
        if (cmpFullName != null && !cmpFullName.equals(cmpName)) {
            net.setCompartmentFullName(cmpName, cmpFullName);
        }
    }

    //add the annotations
    //a) for the network
    parseAnnotations(model, net, annotations);
    //b) for the elements
    for (Annotateable elem : annotations.keySet()) {
        for (Map.Entry<String, String> annot : annotations.get(elem).entrySet()) {
            net.addAnnotation(elem, annot.getKey(), annot.getValue());
        }
    }
    return net;
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

/**
 * Returns the logging properties read from the <tt>logging</tt> element, or
 * <code>null</code> if no logging properties found in the xml config.
 * <p>//from w ww .ja  v  a2  s  .c o  m
 * The logging element is expected to look like this:
 * <pre>
   <logging>
  <prop name=".level"    value="INFO"/>   
  <prop name="handlers"    value="ch.javasoft.util.logging.StandardOutHandler,ch.javasoft.util.logging.StandardErrHandler"/>
  ...
    </logging>
 * </pre>
 * 
 * @param config            the config element to use
 * @throws XmlConfigException   if an xml configuration error occurs
 */
@SuppressWarnings("unchecked")
private Properties getLoggingProperties(Element config) throws XmlConfigException {
    final Element logging = XmlUtil.getOptionalSingleChildElement(config, XmlElement.logging);
    final List<Element> props = (List<Element>) logging.elements(XmlElement.property.getXmlName());

    if (props != null) {
        final Properties loggingProps = new Properties();
        for (final Element property : props) {
            String path = XmlUtil.getElementPath(property, true /*recurseParents*/);

            final Attribute attRef = property.attribute(XmlAttribute.ref.getXmlName());
            final Iterable<Element> resolved;
            if (attRef != null) {
                resolved = resolve(property, path);
            } else {
                resolved = Collections.singleton(property);
            }
            for (Element prop : resolved) {
                final Attribute attName = prop.attribute(XmlAttribute.name.getXmlName());
                final Attribute attValue = prop.attribute(XmlAttribute.value.getXmlName());
                if (attName == null) {
                    throw new XmlConfigException("name attribute missing", path);
                }
                resolveAttributeValue(attName, path);
                final String name = XmlUtil.getRequiredAttributeValue(prop, XmlAttribute.name);
                path += "[name=" + name + "]";
                resolveAttributeValue(attValue, path);
                final String value = XmlUtil.getRequiredAttributeValue(prop, XmlAttribute.value);
                loggingProps.put(name, value);
            }
        }
        return loggingProps;
    }
    return null;
}

From source file:ch.javasoft.xml.config.XmlUtil.java

License:BSD License

/**
 * Returns the desired single child element, or throws an exception if none
 * or multiple are found.//from  w  w w.j  a  v a 2 s  . c  om
 * 
 * @param element            the parent of the desired child
 * @param child               specifies the desired child element name
 * @return                  the child element
 * @throws XmlConfigException   if no or multiple children match the 
 *                         criteria
 */
public static Element getOptionalSingleChildElement(Element element, XmlNode child) throws XmlConfigException {
    @SuppressWarnings("unchecked")
    List<Element> list = element.elements(child.getXmlName());
    if (list.isEmpty()) {
        return null;
    } else if (list.size() > 1) {
        throw new XmlConfigException(
                "expected single " + child.getXmlName() + " child, but found " + list.size(), element);
    }
    return list.get(0);
}

From source file:cn.com.sinosoft.ebusiness.xmltransfer.PolicyDetailCreater.java

@Override
public Map<String, Object> Xml2Object(Document doc) {
    log.info("PolicyDetailCreaterXml2Object....");

    Map<String, Object> result = new HashMap<String, Object>();
    try {//from  w  ww .  j  ava2 s. c  o m
        result.put("flag", doc.selectSingleNode(sTranResponse + "/Flag").getText());
        Element desc = (Element) doc.selectSingleNode(sTranResponse + "/Desc");
        result.put("desc", desc.getText());
        // 
        Policy policy = new Policy();
        if (doc.selectSingleNode(sTranResponse + "/Flag").getText().equals("1")) {

            Element tLccont = (Element) doc.selectSingleNode(sTranResponse + "/LCCont");

            // 
            String policyNo = tLccont.element("ContNo").getText();
            policy.setPolicyNo(policyNo);
            //  NETS
            String souseFlag = tLccont.element("SouseFlag").getText();
            policy.setSource(souseFlag);
            // 
            policy.setRiskAccount(getRiskAccount(tLccont));
            // 
            getPolicyInfo(tLccont, policy);

            // 
            Element tLCAppnt = (Element) doc.selectSingleNode(sTranResponse + "/LCCont/LCAppnt");
            policy.setAppnt(getAppntByPolicyNo(tLCAppnt));
            // 
            Element tLCInsureds = (Element) doc.selectSingleNode(sTranResponse + "/LCCont/LCInsureds");
            // 
            Element tLCInsured = (Element) tLCInsureds.elements("LCInsured").get(0);
            policy.setInsured(getInsuredByPolicyNo(tLCInsured, policy));
            result.put("policy", policy);
        }

    } catch (Exception e) {
        log.info("" + e.getMessage());
        result.put("flag", "0");
        result.put("desc", "....");
        e.printStackTrace();
    }
    return result;
}

From source file:cn.com.sinosoft.ebusiness.xmltransfer.PolicyDetailCreater.java

/**
 * /*from  ww w.  ja  v a 2 s .c o m*/
 * 
 * @param tRisks
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
private List<Risk> getRisksByPolicyNo(Element tRisks, Policy policy) throws Exception {

    DecimalFormat df = new DecimalFormat();
    df = new DecimalFormat("0.00");
    List<Element> eRisks = tRisks.elements("Risk");
    // 
    List<Risk> risks = new ArrayList<Risk>();
    for (Element eRisk : eRisks) {
        Risk risk = new Risk();
        risk.setRiskCode(eRisk.element("RiskCode").getText());
        risk.setPolNo(eRisk.element("PolNo").getText());
        risk.setCvaliDate(eRisk.element("CValiDate").getText());
        risk.setRiskName(eRisk.element("RiskName").getText());
        risk.setPrem(df.format(df.parse(eRisk.element("Prem").getText())));
        risk.setAmnt(df.format(df.parse(eRisk.element("Amnt").getText())));
        risk.setInsuYear(eRisk.element("InsuYear").getText());
        risk.setInsuYearFlag(eRisk.element("InsuYearFlag").getText());
        risk.setState(eRisk.element("State").getText());
        // 
        String mainRiskCode = eRisk.element("MainRiskCode").getText();
        if (risk.getRiskCode().equals(mainRiskCode)) {
            risk.setSubRiskFlag("M");
            // 
            policy.setBnfs(getBnfsByPolicy(eRisk));
            // 
            policy.setmRisk(risk);
        } else {
            risk.setSubRiskFlag("S");
        }

        risk.setPolicyNo(policy.getPolicyNo());
        risks.add(risk);
    }
    // 
    Collections.sort(risks);
    return risks;
}

From source file:cn.com.sinosoft.ebusiness.xmltransfer.PolicyDetailCreater.java

/**
 * /*w w w  .j  ava 2s .  com*/
 * 
 * @param tLCAppnt
 * @return
 */
@SuppressWarnings("unchecked")
private List<Beneficiary> getBnfsByPolicy(Element eRisk) {
    NumberFormat nt = NumberFormat.getPercentInstance();
    nt = NumberFormat.getPercentInstance();
    nt.setMaximumIntegerDigits(3);
    nt.setMaximumFractionDigits(2);
    List<Beneficiary> beneficiarys = new ArrayList<Beneficiary>();
    Element eLCBnfs = eRisk.element("LCBnfs");
    Element tLCBnfCount = eLCBnfs.element("LCBnfCount");
    if (Integer.parseInt(tLCBnfCount.getText()) > 0) {
        List<Element> tLCBnfs = eLCBnfs.elements("LCBnf");
        for (Element tLCBnf : tLCBnfs) {
            Beneficiary beneficiary = new Beneficiary();
            // 
            beneficiary.setBeneficiaryOrder(
                    IntegerToChinese.ConvertToChinese(Integer.parseInt(tLCBnf.element("BnfGrade").getText())));
            beneficiary.setName(tLCBnf.element("Name").getText());
            double bnfPercent = Double.parseDouble(tLCBnf.element("BnfLot").getText());
            beneficiary.setInterestPercent(nt.format(bnfPercent));
            beneficiarys.add(beneficiary);
        }
    }

    return beneficiarys;
}

From source file:cn.com.sunjiesh.wechat.service.AbstractWechatMessageReceiveService.java

/**
 * ??/*  www.  j a  v  a  2  s  .c o m*/
 *
 * @param doc4j ??Dom
 * @param toUserName ??
 * @param fromUserName ????OpenID
 * @param eventKey KEY???
 * @param event event
 * @return ?
 */
protected WechatReceiveEventPicCommonMessage getWechatReceiveEventPicCommonMessage(Document doc4j,
        String toUserName, String fromUserName, String eventKey, String event) {
    Element sendPicsInfoEle = (Element) doc4j.selectSingleNode("/xml/SendPicsInfo");
    Element countNode = sendPicsInfoEle.element("Count");
    List<Element> picListNodeList = sendPicsInfoEle.elements("PicList");

    Integer count = Integer.parseInt(countNode.getText());
    WechatReceiveEventPicCommonMessage wechatMessage = new WechatReceiveEventPicCommonMessage(toUserName,
            fromUserName, event, eventKey);
    wechatMessage.setCount(count);
    picListNodeList.forEach(node -> {
        Element itemEle = node.element("item");
        Element picMd5SumEle = itemEle.element("PicMd5Sum");
        String picMd5Sum = picMd5SumEle.getTextTrim();
        wechatMessage.getPicsInfoList().add(wechatMessage.new SendPicsInfo(picMd5Sum));
    });
    return wechatMessage;
}