Example usage for org.dom4j Element getText

List of usage examples for org.dom4j Element getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text value of this element without recursing through child elements.

Usage

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

License:Open Source License

/**
 * ??xml ?map/*from   w  w w  . j  a  v  a 2  s . c  o  m*/
 * */
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.appdynamics.monitors.hadoop.parser.Parser.java

License:Apache License

/**
 * Parses XML file at <code>xml</code> and collect filtering rules.
 *
 * @param xml//  w w  w .ja  va 2 s .co m
 * @throws DocumentException
 */
public void parseXML(String xml) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document doc = reader.read(xml);
    Element root = doc.getRootElement();
    String text;

    Iterator<Element> hrmIter = root.element("hadoop-resource-manager").elementIterator();
    Iterator<Element> ambariIter = root.element("ambari").elementIterator();

    while (hrmIter.hasNext()) {
        Element element = hrmIter.next();
        if (element.getName().equals("aggregate-app-period")) {
            if (!(text = element.getText()).equals("")) {
                try {
                    aggrAppPeriod = Integer.parseInt(text);
                } catch (NumberFormatException e) {
                    logger.error("Error parsing aggregate-app-period: " + e + "\n"
                            + "Using default value instead: " + DEFAULT_THREAD_LIMIT);
                    aggrAppPeriod = DEFAULT_AGGR_APP_PERIOD;
                }
            }
        } else if (element.getName().equals("exclude-nodeid")) {
            if (!(text = element.getText()).equals("")) {
                String[] nodeId = text.split(",");
                excludeNodeid.addAll(Arrays.asList(nodeId));
            }
        } else {
            logger.error("Unknown element '" + element.getName() + "' in properties file");
        }
    }

    while (ambariIter.hasNext()) {
        Element element = ambariIter.next();

        if (element.getName().equals("thread-limit")) {
            if (!(text = element.getText()).equals("")) {
                try {
                    threadLimit = Integer.parseInt(text);
                } catch (NumberFormatException e) {
                    logger.error("Error parsing thread-limit " + e + "\n" + "Using default value instead: "
                            + DEFAULT_THREAD_LIMIT);
                    threadLimit = DEFAULT_THREAD_LIMIT;
                }
            }
        } else if (element.getName().equals("include-cluster")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.split(",");
                includeAmbariCluster.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("include-host")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.split(",");
                includeAmbariHost.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("exclude-host")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.split(",");
                excludeAmbariHost.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("exclude-service")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.toLowerCase().split(",");
                excludeAmbariService.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("exclude-service-component")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.toLowerCase().split(",");
                excludeAmbariServiceComponent.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("include-host-metrics")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.toLowerCase().split(",");
                includeAmbariHostMetrics.addAll(Arrays.asList(appId));
            }
        } else if (element.getName().equals("include-component-metrics")) {
            if (!(text = element.getText()).equals("")) {
                String[] appId = text.toLowerCase().split(",");
                includeAmbariComponentMetrics.addAll(Arrays.asList(appId));
            }
        }
    }
}

From source file:com.appdynamics.snmp.SNMPTrapSender.java

License:Apache License

/**
 * Parses the config xml/*from w w w  . j  a v a  2s  .  c om*/
 * @param    xml         Configuration file locations
 * @return            Map<String, String> - Map of config objects
 * @throws             DocumentException
 */
private static Map<String, String> parseXML(String xml) throws DocumentException {
    Map<String, String> map = new HashMap<String, String>();
    SAXReader reader = new SAXReader();
    Document document = reader.read(xml);
    Element root = document.getRootElement();

    for (Iterator<Element> i = root.elementIterator(); i.hasNext();) {
        Element element = (Element) i.next();
        if (element.getName().equals("snmp-v3")) {
            Iterator<Element> elementIterator = element.elementIterator();
            for (Iterator<Element> j = elementIterator; j.hasNext();) {
                element = (Element) j.next();
                map.put(element.getName(), element.getText());
            }
        } else {
            map.put(element.getName(), element.getText());
        }
    }

    return map;
}

From source file:com.appeligo.channelfeed.work.FileReaderThread.java

License:Apache License

public void run() {

    try {//  ww w . j  a v a2  s .c o m
        SAXReader reader = new SAXReader();
        Document document;
        try {
            document = reader.read(new File(ccDocumentRoot + captionFilename));
        } catch (DocumentException e) {
            log.error("Could not open document " + ccDocumentRoot + captionFilename + "; ", e);
            return;
        }

        do {
            //Node startTimeNode = document.selectSingleNode("//meta[@name='StartTime']");
            Node startTimeNode = document.selectSingleNode("//*[name()='meta'][@name='StartTime']");
            long startTime;
            try {
                startTime = Long.parseLong(startTimeNode.valueOf("@content"));
            } catch (NumberFormatException e) {
                throw new Error(e);
            }

            //Node endTimeNode = document.selectSingleNode("//meta[@name='EndTime']");
            Node endTimeNode = document.selectSingleNode("//*[name()='meta'][@name='EndTime']");
            long endTime;
            try {
                endTime = Long.parseLong(endTimeNode.valueOf("@content"));
            } catch (NumberFormatException e) {
                throw new Error(e);
            }

            long durationMillis = endTime - startTime;

            if (autoAdvance) {
                long durationSeconds = durationMillis / 1000;
                Calendar midnight = Calendar.getInstance();
                midnight.setTime(new Date());
                midnight.setTimeZone(TimeZone.getTimeZone("GMT"));
                int year = midnight.get(Calendar.YEAR);
                int month = midnight.get(Calendar.MONTH);
                int dayOfMonth = midnight.get(Calendar.DAY_OF_MONTH);
                midnight.clear();
                midnight.set(year, month, dayOfMonth);
                long midnightMillis = midnight.getTimeInMillis();
                long secondsSinceMidnight = (System.currentTimeMillis() - midnightMillis) / 1000;
                //int loopsSinceMidnight = (int)(secondsSinceMidnight / durationSeconds);
                advanceSeconds = (int) (secondsSinceMidnight % durationSeconds);
            }

            long newStartTime = System.currentTimeMillis() - (advanceSeconds * 1000);
            long newEndTime = newStartTime + durationMillis;

            setProgram(newStartTime).setStartTime(new Date(newStartTime));

            //            List divs = document.selectNodes("/html/body/div");
            List divs = document.selectNodes("/*[name()='html']/*[name()='body']/*[name()='div']");

            while ((divs.size() > 0) && (!aborted)) {
                Element div = (Element) divs.remove(0);
                List children = div.selectNodes("child::node()");
                while ((children.size() > 0) && (!aborted)) {
                    Node a = (Node) children.remove(0);
                    while (!("a".equals(a.getName()))) {
                        if (children.size() == 0) {
                            break;
                        }
                        a = (Node) children.remove(0);
                    }
                    if (!("a".equals(a.getName()))) {
                        break;
                    }
                    long timestamp;
                    try {
                        timestamp = Long.parseLong(a.valueOf("@name"));
                    } catch (NumberFormatException e) {
                        throw new Error(e);
                    }
                    long offset = timestamp - startTime;
                    long delayUntil = newStartTime + offset;
                    log.debug("Next sentence in " + ((delayUntil - System.currentTimeMillis()) / 1000)
                            + " seconds");
                    while (System.currentTimeMillis() < delayUntil) {
                        try {
                            Thread.sleep(delayUntil - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                        }
                    }

                    String speakerChange = null;
                    Node afterA = (Node) children.remove(0);
                    if (afterA instanceof Element) {
                        if (!("span".equals(afterA.getName()))) {
                            throw new Error("span expected");
                        }
                        Element span = (Element) afterA;
                        speakerChange = span.getText().replace("&gt;&gt;", "").trim();
                        afterA = (Node) children.remove(0);
                    }

                    String sentence;
                    if (afterA instanceof Text) {
                        Text sentenceNode = (Text) afterA;
                        sentence = sentenceNode.getText();
                    } else {
                        Entity entity = (Entity) afterA;
                        sentence = entity.asXML();
                    }
                    while (children.get(0) instanceof Text || children.get(0) instanceof Entity) {
                        if (children.get(0) instanceof Text) {
                            Text moreText = (Text) children.remove(0);
                            sentence += moreText.getText();
                        } else {
                            Entity entity = (Entity) children.remove(0);
                            sentence += entity.asXML();
                        }
                    }
                    sentence = sentence.trim();

                    /*
                    if (!docOpened) {
                       openDoc(newStartTime - SCHEDULE_VARIANCE);
                    }
                    */
                    //if (program != null) {
                    getDestinations().writeSentence(getProgram(), delayUntil, speakerChange, sentence);
                    //}
                }
            }

            if (loop) {
                autoAdvance = false;
                advanceSeconds = 0;
                log.debug("Waiting for end of program in " + ((newEndTime - System.currentTimeMillis()) / 1000)
                        + " seconds");
                while (System.currentTimeMillis() < newEndTime) {
                    try {
                        Thread.sleep(newEndTime - System.currentTimeMillis());
                    } catch (InterruptedException e) {
                    }
                }
            }
        } while (loop);
    } catch (Exception e) {
        log.error("Uncaught exception!", e);
    }
}

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

License:Apache License

/**
 * ????//from  ww  w . j a  va 2  s.c  o  m
 * 
 * @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  a v  a  2s  .  c o m*/
 * @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 av  a2s .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.aricojf.util.ConfigParser.java

/**
 * ??//from  w  w  w. j  a v a  2s . c  om
 * ?String "/?/?"
 * ep: "config/conn/user"
 * @return
 */
public static String parseConfigParmByPath(String configFilePath, String nodes) {
    value = "";
    FileInputStream fs = null;
    File file = new File(configFilePath);
    if (file.exists()) {
        file = null;
        try {
            fs = new FileInputStream(configFilePath);
            SAXReader reader = new SAXReader();
            org.dom4j.Document document = reader.read(fs);
            org.dom4j.Element element = document.getRootElement();
            String[] nod = nodes.trim().split(FILE_SEPARATOR);
            for (int i = 1; i < nod.length; i++) {
                List<Element> elements = element.elements(nod[i]);
                /**
                 * ???????
                 * ??xml?????
                 */
                for (Element ele : elements) {
                    element = ele;
                    value = ele.getText();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConn(fs);
        }
    }
    return null == value ? "" : value;
}

From source file:com.atguigu.p2p.util.XmlUtils.java

License:Apache License

@SuppressWarnings("unchecked")
public static Map<String, String> xml2Map(String xml) {
    Map<String, String> map = new HashMap<String, String>();
    try {/*  ww w  .ja v  a2 s .c om*/
        Document document = DocumentHelper.parseText(xml);
        Element rootElement = document.getRootElement();
        for (Iterator<Element> it = rootElement.elementIterator(); it.hasNext();) {
            Element element = (Element) it.next();
            map.put(element.getName(), element.getText());
        }
    } catch (Exception e) {
        logger.error("xml2Map error:", e);
    }
    return map;
}

From source file:com.atguigu.p2p.util.XmlUtils.java

License:Apache License

@SuppressWarnings("unchecked")
public static List<Map<String, String>> xml2MapList(String xml, String xPath) {
    List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
    try {/*  ww  w. j  a v  a 2  s. c o  m*/
        Document document = DocumentHelper.parseText(xml);
        List<Element> selectNodes = document.selectNodes(xPath);
        for (Element e : selectNodes) {
            Map<String, String> map = new HashMap<String, String>();
            for (Iterator<Element> it = e.elementIterator(); it.hasNext();) {
                Element element = (Element) it.next();
                map.put(element.getName(), element.getText());
            }
            mapList.add(map);
        }
    } catch (Exception e) {
        logger.error("xml2MapList error:", e);
    }
    return mapList;
}