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();

Source Link

Document

Returns the elements contained in this element.

Usage

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ publishItemsToNode(PubSubService service, IQ iq, Element publishElement) {
    String nodeID = publishElement.attributeValue("node");

    if (nodeID == null) {
        // No node was specified. Return bad_request error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("nodeid-required", "http://jabber.org/protocol/pubsub#errors"));
        return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
    }/*  ww w  .ja v  a 2 s .  c  o  m*/

    // Look for the specified node
    Node node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error
        return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
    }

    JID from = iq.getFrom();
    // TODO Assuming that owner is the bare JID (as defined in the JEP). This can be replaced with an explicit owner specified in the packet
    JID owner = new JID(from.getNode(), from.getDomain(), null, true);
    if (!node.getPublisherModel().canPublish(node, owner) && !service.isServiceAdmin(owner)) {
        // Entity does not have sufficient privileges to publish to node
        return createErrorPacket(iq, PacketError.Condition.forbidden, null);
    }

    if (node.isCollectionNode()) {
        // Node is a collection node. Return feature-not-implemented error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", "publish");
        return createErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
    }

    LeafNode leafNode = (LeafNode) node;
    Iterator itemElements = publishElement.elementIterator("item");

    // Check that an item was included if node persist items or includes payload
    if (!itemElements.hasNext() && leafNode.isItemRequired()) {
        Element pubsubError = DocumentHelper
                .createElement(QName.get("item-required", "http://jabber.org/protocol/pubsub#errors"));
        return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
    }

    // Check that no item was included if node doesn't persist items and doesn't
    // includes payload
    if (itemElements.hasNext() && !leafNode.isItemRequired()) {
        Element pubsubError = DocumentHelper
                .createElement(QName.get("item-forbidden", "http://jabber.org/protocol/pubsub#errors"));
        return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
    }

    List<Element> items = new ArrayList<Element>();
    List entries;
    Element payload;
    while (itemElements.hasNext()) {
        Element item = (Element) itemElements.next();
        entries = item.elements();
        payload = entries.isEmpty() ? null : (Element) entries.get(0);
        // Check that a payload was included if node is configured to include payload
        // in notifications
        if (payload == null && leafNode.isPayloadDelivered()) {
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("payload-required", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
        }

        // Check that the payload (if any) contains only one child element
        if (entries.size() > 1) {
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("invalid-payload", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);

        }
        items.add(item);
    }

    // Publish item and send event notifications to subscribers
    leafNode.publishItems(from, items);
    // Return success operation
    return createSuccessPacket(iq);
}

From source file:com.ah.be.parameter.BeParaModuleDefImpl.java

private void changeOsVersionFile() {
    String fingerprints = ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME;
    String fingerprintsChg = ImportTextFileAction.OS_VERSION_FILE_PATH
            + ImportTextFileAction.OS_VERSION_FILE_NAME_CHG;
    FileWriter fWriter = null;//from   w w w. j a v a  2 s .c  o m
    try {
        if (new File(fingerprints).exists() && new File(fingerprintsChg).exists()) {
            List<String> lines = NmsUtil.readFileByLines(fingerprints);
            List<String> replaceOsName = new ArrayList<>();
            List<String> replaceOption55 = new ArrayList<>();
            String preHmVer = NmsUtil.getHiveOSVersion(NmsUtil
                    .getVersionInfo(BeAdminCentOSTools.ahBackupdir + File.separatorChar + "hivemanager.ver"));

            // parse os_dhcp_fingerprints_changes.xml
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(fingerprintsChg));
            Element root = document.getRootElement();
            List<?> fingerprintElems = root.elements();
            for (Object obj : fingerprintElems) {
                Element fingerprintElem = (Element) obj;
                String osName = fingerprintElem.attributeValue("osname");
                for (Iterator<?> iterator = fingerprintElem.elementIterator(); iterator.hasNext();) {
                    Element option55Elem = (Element) iterator.next();
                    String node_option55_text = option55Elem.getText();
                    Attribute version = option55Elem.attribute("version");
                    String version_text = version.getText();
                    if (NmsUtil.compareSoftwareVersion(preHmVer, version_text) <= 0) {
                        if (!replaceOption55.contains(node_option55_text)) {
                            replaceOsName.add(osName);
                            replaceOption55.add(node_option55_text);
                        }
                    }
                }
            }

            if (replaceOption55.isEmpty()) {
                log.debug("No need to modify os_dhcp_fingerprints.txt.");
                FileUtils.deleteQuietly(new File(fingerprintsChg));
                return;
            }

            for (String option55 : replaceOption55) {
                int size = lines.size();
                boolean remove = false;
                for (int i = size - 1; i >= 0; i--) {
                    if (remove) {
                        lines.remove(i);
                        remove = false;
                    } else {
                        if (option55.equals(lines.get(i))) {
                            if (i < size - 1 && i > 0
                                    && lines.get(i - 1).startsWith(ImportTextFileAction.OS_STR)
                                    && lines.get(i + 1).equals(ImportTextFileAction.END_STR)) {
                                lines.remove(i + 1);
                                lines.remove(i);
                                remove = true;
                            } else {
                                lines.remove(i);
                            }
                        }
                    }
                }
            }

            //insert
            for (int i = 0; i < replaceOption55.size(); i++) {
                String option55 = replaceOption55.get(i);
                String osName = ImportTextFileAction.OS_STR + replaceOsName.get(i);

                if (!lines.contains(option55)) {
                    if (lines.contains(osName)) {
                        List<String> temp = lines.subList(lines.indexOf(osName), lines.size());
                        int index = lines.indexOf(osName) + temp.indexOf(ImportTextFileAction.END_STR);
                        lines.add(index, option55);

                    } else {
                        lines.add(osName);
                        lines.add(option55);
                        lines.add(ImportTextFileAction.END_STR);
                    }
                }
            }

            fWriter = new FileWriter(fingerprints, false);
            for (String line : lines) {
                if (line != null && line.startsWith(ImportTextFileAction.VERSION_STR)) {
                    String version = line.substring(line.indexOf(ImportTextFileAction.VERSION_STR)
                            + ImportTextFileAction.VERSION_STR.length());
                    BigDecimal b1 = new BigDecimal(version);
                    BigDecimal b2 = new BigDecimal("0.1");
                    float fVer = b1.add(b2).floatValue();
                    String versionStr = ImportTextFileAction.VERSION_STR + String.valueOf(fVer) + "\r\n";
                    fWriter.write(versionStr);
                } else {
                    fWriter.write(line + "\r\n");
                }
            }
            fWriter.close();

            //compress file
            String strCmd = "";
            StringBuffer strCmdBuf = new StringBuffer();
            strCmdBuf.append("tar zcvf ");
            strCmdBuf.append(
                    ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME_TAR);
            strCmdBuf.append(" -C ");
            strCmdBuf.append(ImportTextFileAction.OS_VERSION_FILE_PATH);
            strCmdBuf.append(" " + ImportTextFileAction.OS_VERSION_FILE_NAME);
            strCmd = strCmdBuf.toString();
            boolean compressResult = BeAdminCentOSTools.exeSysCmd(strCmd);
            if (!compressResult) {
                log.error("compress os_dhcp_fingerprints.txt error.");
                return;
            }

            FileUtils.deleteQuietly(new File(fingerprintsChg));
        } else {
            if (new File(fingerprintsChg).exists()) {
                FileUtils.deleteQuietly(new File(fingerprintsChg));
            }
        }
    } catch (Exception e) {
        setDebugMessage("change OsVersionFile error: ", e);
    } finally {
        if (fWriter != null) {
            try {
                fWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:com.ah.be.parameter.BeParaModuleDefImpl.java

public void insertDefaultCustomReportField() {
    try {/*  w  w  w.  j  a v a2 s . c om*/
        long rowCount = QueryUtil.findRowCount(AhCustomReportField.class, null);

        if (rowCount > 0) {
            return;
        }

        List<AhCustomReportField> reportFields = new ArrayList<>();

        SAXReader reader = new SAXReader();
        String docName = AhDirTools.getHmRoot() + "resources" + File.separator + "customReport" + File.separator
                + "custom_report_table.xml";
        Document doc = reader.read(new File(docName));
        Element root = doc.getRootElement();
        List<?> rootLst = root.elements();

        for (Object obj : rootLst) {
            List<?> rowlst = ((Element) obj).elements();
            AhCustomReportField reportField = new AhCustomReportField();
            for (int j = 0; j < rowlst.size(); j++) {
                Element elm = (Element) rowlst.get(j);
                //               String name = elm.attributeValue("name");
                String value = elm.attributeValue("value");
                if (j == 0) {
                    reportField.setId(Long.parseLong(value));
                } else if (j == 1) {
                    reportField.setType(Integer.parseInt(value));
                } else if (j == 2) {
                    reportField.setDetailType(Integer.parseInt(value));
                } else if (j == 3) {
                    reportField.setTableName(value);
                } else if (j == 4) {
                    reportField.setTableField(value);
                } else if (j == 5) {
                    reportField.setFieldString(value);
                } else if (j == 6) {
                    reportField.setStrUnit(value);
                } else if (j == 7) {
                    reportField.setDescription(value);
                }
            }
            reportFields.add(reportField);
        }

        root.clearContent();
        doc.clearContent();

        QueryUtil.bulkCreateBos(reportFields);
    } catch (Exception e) {
        setDebugMessage("insert default custom report field: ", e);
    }
}

From source file:com.alibaba.citrus.dev.handler.util.DomUtil.java

License:Open Source License

private static Element copy(org.dom4j.Element dom4jElement, ElementFilter filter) throws Exception {
    dom4jElement = filter.filter(dom4jElement);

    if (dom4jElement == null) {
        return null;
    }/*  ww  w .jav  a 2 s . co m*/

    Element element = new Element(dom4jElement.getQualifiedName(), dom4jElement.getNamespaceURI());

    for (Object attr : dom4jElement.attributes()) {
        String name = ((Attribute) attr).getQualifiedName();
        String value = ((Attribute) attr).getValue();

        element.addAttribute(name, value);
    }

    for (Object ns : dom4jElement.declaredNamespaces()) {
        String name = ((Namespace) ns).getPrefix();
        String value = ((Namespace) ns).getURI();

        if (isEmpty(name)) {
            name = "xmlns";
        } else {
            name = "xmlns:" + name;
        }

        element.addAttribute(name, value);
    }

    for (Object e : dom4jElement.elements()) {
        Element subElement = copy((org.dom4j.Element) e, filter);

        if (subElement != null) {
            element.addSubElement(subElement);
        }
    }

    if (dom4jElement.elements().isEmpty()) {
        String text = trimToNull(dom4jElement.getText());

        if (text != null) {
            element.setText(text);
        }
    }

    return element;
}

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** schema?includes */
public static Transformer getTransformerWhoAddsIndirectIncludes(final Map<String, Schema> includes) {
    return new Transformer() {
        public void transform(Document document, String systemId) {
            Element root = document.getRootElement();

            root.addNamespace("xsd", W3C_XML_SCHEMA_NS_URI);

            // <xsd:schema>
            if (W3C_XML_SCHEMA_NS_URI.equals(root.getNamespaceURI()) && "schema".equals(root.getName())) {
                Namespace xsd = DocumentHelper.createNamespace("xsd", W3C_XML_SCHEMA_NS_URI);
                QName includeName = DocumentHelper.createQName("include", xsd);

                // for each <xsd:include>
                for (Iterator<?> i = root.elementIterator(includeName); i.hasNext();) {
                    i.next();//from   ww  w  .j  a  v a2  s.  c om
                    i.remove();
                }

                // includes
                @SuppressWarnings("unchecked")
                List<Node> nodes = root.elements();
                int i = 0;

                for (Schema includedSchema : includes.values()) {
                    Element includeElement = DocumentHelper.createElement(includeName);
                    nodes.add(i++, includeElement);

                    includeElement.addAttribute("schemaLocation", includedSchema.getName());
                }
            }
        }
    };
}

From source file:com.app.buzz.weixin.util.XmlUtils.java

License:Open Source License

/**
 * ??xml ?map//  w w  w.  j a  v a 2 s.c om
 * */
public static Map<String, String> xml2Map(InputStream in) {
    Map<String, String> map = new HashMap<String, String>();
    SAXReader reader = new SAXReader();
    try {
        Document document = reader.read(in);
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        for (Element e : elements) {
            map.put(e.getName(), e.getText());
        }
        return map;

    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.appleframework.pay.app.reconciliation.parser.ALIPAYParser.java

License:Apache License

/**
 * ????/*  ww w  .  j  a v  a 2s . c om*/
 * 
 * @param file
 *            ??
 * @param billDate
 *            ?
 * @param batch
 *            
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<ReconciliationEntityVo> parser(File file, Date billDate, RpAccountCheckBatch batch)
        throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_STYLE);

    // xml?file
    SAXReader reader = new SAXReader();
    Document document;
    try {
        document = reader.read(file);
        // dom4jXpathAccountQueryAccountLogVO
        List projects = document.selectNodes(
                "alipay/response/account_page_query_result/account_log_list/AccountQueryAccountLogVO");

        Iterator it = projects.iterator();
        // ?
        List<AlipayAccountLogVO> tradeList = new ArrayList<AlipayAccountLogVO>();
        // ?
        List<AlipayAccountLogVO> otherAll = new ArrayList<AlipayAccountLogVO>();
        while (it.hasNext()) {
            AlipayAccountLogVO vo = new AlipayAccountLogVO();
            Element elm = (Element) it.next();
            List<Element> childElements = elm.elements();
            for (Element child : childElements) {
                String name = child.getName();
                // 
                switch (name) {
                case "balance":
                    vo.setBalance(new BigDecimal(child.getText()));
                    break;
                case "rate":
                    vo.setBankRate(new BigDecimal(("").equals(child.getText()) ? "0" : child.getText()));
                    break;
                case "buyer_account":
                    vo.setBuyerAccount(child.getText());
                    break;
                case "goods_title":
                    vo.setGoodsTitle(child.getText());
                    break;
                case "income":
                    vo.setIncome(new BigDecimal(("").equals(child.getText()) ? "0" : child.getText()));
                    break;
                case "outcome":
                    vo.setOutcome(new BigDecimal(("").equals(child.getText()) ? "0" : child.getText()));
                    break;
                case "merchant_out_order_no":
                    vo.setMerchantOrderNo(child.getText());
                    break;
                case "total_fee":
                    vo.setTotalFee(new BigDecimal(("").equals(child.getText()) ? "0" : child.getText()));
                    break;
                case "trade_no":// ?
                    vo.setTradeNo(child.getText());
                    break;
                case "trans_code_msg":// 
                    vo.setTransType(child.getText());
                    break;
                case "trans_date":
                    String dateStr = child.getText();
                    Date date;
                    try {
                        date = sdf.parse(dateStr);
                    } catch (ParseException e) {
                        date = billDate;
                    }
                    vo.setTransDate(date);
                    break;

                default:
                    break;
                }
            }

            // ??
            if ("".equals(vo.getTransType())) {
                tradeList.add(vo);
            } else {
                otherAll.add(vo);
            }
        }
        // ?????????
        // ?????????
        for (AlipayAccountLogVO trade : tradeList) {
            String tradeNo = trade.getTradeNo();
            for (AlipayAccountLogVO other : otherAll) {
                String otherTradeNo = other.getTradeNo();
                if (tradeNo.equals(otherTradeNo)) {
                    trade.setBankFee(other.getOutcome());
                }
            }
        }
        // AlipayAccountLogVOvoReconciliationEntityVo?list
        List<ReconciliationEntityVo> list = new ArrayList<ReconciliationEntityVo>();

        // ???
        int totalCount = 0;
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalFee = BigDecimal.ZERO;

        for (AlipayAccountLogVO trade : tradeList) {
            // 
            totalCount++;
            totalAmount = totalAmount.add(trade.getTotalFee());
            totalFee = totalFee.add(trade.getBankFee());

            // AlipayAccountLogVOReconciliationEntityVo
            ReconciliationEntityVo vo = new ReconciliationEntityVo();
            vo.setAccountCheckBatchNo(batch.getBatchNo());
            vo.setBankAmount(trade.getTotalFee());
            vo.setBankFee(trade.getBankFee());
            vo.setBankOrderNo(trade.getMerchantOrderNo());
            vo.setBankRefundAmount(BigDecimal.ZERO);
            vo.setBankTradeStatus("SUCCESS");
            vo.setBankTradeTime(trade.getTransDate());
            vo.setBankTrxNo(trade.getTradeNo());
            vo.setBankType(PayWayEnum.ALIPAY.name());
            vo.setOrderTime(trade.getTransDate());
            list.add(vo);
        }
        batch.setBankTradeCount(totalCount);
        batch.setBankTradeAmount(totalAmount);
        batch.setBankRefundAmount(BigDecimal.ZERO);
        batch.setBankFee(totalFee);

        return list;

    } catch (DocumentException e) {
        LOG.warn("?", e);
        batch.setStatus(BatchStatusEnum.FAIL.name());
        batch.setCheckFailMsg("?, payway[" + PayWayEnum.ALIPAY.name() + "], billdata["
                + sdf.format(billDate) + "]");
        return null;
    }

}

From source file:com.appleframework.pay.trade.utils.WeiXinPayUtils.java

License:Apache License

/**
 * ??xml?,?//from   ww  w.j av  a2  s  .com
 * @param requestUrl
 * @param requestMethod
 * @param xmlStr
 * @return
 */
public static Map<String, Object> httpXmlRequest(String requestUrl, String requestMethod, String xmlStr) {
    // ?HashMap
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        HttpsURLConnection urlCon = (HttpsURLConnection) (new URL(requestUrl)).openConnection();
        urlCon.setDoInput(true);
        urlCon.setDoOutput(true);
        // ?GET/POST
        urlCon.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod)) {
            urlCon.connect();
        }

        urlCon.setRequestProperty("Content-Length", String.valueOf(xmlStr.getBytes().length));
        urlCon.setUseCaches(false);
        // gbk?????
        if (null != xmlStr) {
            OutputStream outputStream = urlCon.getOutputStream();
            outputStream.write(xmlStr.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }
        InputStream inputStream = urlCon.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        // ??
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStreamReader);
        // xml
        Element root = document.getRootElement();
        // ?
        @SuppressWarnings("unchecked")
        List<Element> elementList = root.elements();
        // ???
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        inputStreamReader.close();
        inputStream.close();
        inputStream = null;
        urlCon.disconnect();
    } catch (MalformedURLException e) {
        LOG.error(e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage());
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }
    return map;
}

From source file:com.appleframework.pay.trade.utils.WeiXinPayUtils.java

License:Apache License

/**
 * ???XML/*from   www.  j a v a 2s. c o m*/
 *
 * @param inputStream
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(InputStream inputStream) throws Exception {

    if (inputStream == null) {
        return null;
    }

    Map<String, String> map = new HashMap<String, String>();// ?HashMap
    SAXReader reader = new SAXReader();// ??
    Document document = reader.read(inputStream);
    Element root = document.getRootElement();// xml
    List<Element> elementList = root.elements();// ?
    for (Element e : elementList) { // ???
        map.put(e.getName(), e.getText());
    }

    inputStream.close(); // ?
    inputStream = null;

    return map;
}

From source file:com.arc.cdt.debug.seecode.options.Condition.java

License:Open Source License

static Condition parse(Element e) {
    String name = e.getName().toLowerCase();
    if (name.equals("equals") || name.equals("notequals")) {
        String propName = e.attributeValue("property");
        String option = e.attributeValue("option");
        String value = e.attributeValue("value");
        if (value == null)
            throw new IllegalStateException("Value in SetIf condition is missing");
        if (propName != null) {
            if (option != null)
                throw new IllegalStateException("Can't specify properyt and option in same SetIf condition");
            return PropertyEquals(propName, value, name.charAt(0) == 'n');
        }/*from   www.ja  va2s.c  om*/
        if (option == null)
            throw new IllegalStateException("Missing property or option in setIf \"equals\" condition");
        return OptionEquals(option, value, name.charAt(0) == 'n');
    }
    if (name.equals("and") || name.equals("or")) {
        @SuppressWarnings("unchecked")
        List<Element> kids = e.elements();
        if (kids.size() < 2)
            throw new IllegalStateException("And/Or node in SetIf condition must have 2 or more kids");
        Condition cond = parse(kids.get(0));
        for (int i = 1; i < kids.size(); i++) {
            Condition cond2 = parse(kids.get(i));
            if (name.charAt(0) == 'a')
                cond = And(cond, cond2);
            else
                cond = Or(cond, cond2);
        }
        return cond;
    }
    if (name.equals("not")) {
        @SuppressWarnings("unchecked")
        List<Element> kids = e.elements();
        if (kids.size() != 1)
            throw new IllegalStateException("Not node in SetIf condition must have 2 or more kids");
        Condition cond = parse(kids.get(0));
        return Not(cond);
    }
    throw new IllegalStateException("Unknown SetIf condition node: " + name);
}