Example usage for org.dom4j Element attribute

List of usage examples for org.dom4j Element attribute

Introduction

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

Prototype

Attribute attribute(QName qName);

Source Link

Document

DOCUMENT ME!

Usage

From source file:cn.buk.api.service.CtripHotelServiceImpl.java

License:LGPL

private String processHotelSearchResponse(Document document) {
    if (document == null)
        return "ER#Document is null.";

    Element rootElement = document.getRootElement();
    Element headerElement = rootElement.element("Header");
    if (!headerElement.attribute("ResultCode").getValue().equalsIgnoreCase("Success")) {
        logger.error(document.asXML());/* w  ww  .  j  a  v  a  2s  .com*/
        return "ER#ResultCode is not Success.";
    }

    //header?
    getCache().put(new net.sf.ehcache.Element(ConfigData.OTA_HotelSearch_Request, headerElement));

    List myNodes = document.selectNodes("/Response/HotelResponse/*");
    Element eleOtaHotelSearchRS = (Element) myNodes.get(0);

    XStream xs = createXStream();
    xs.alias("Response", HotelSearchResponse.class);
    xs.processAnnotations(HotelSearchResponse.class);

    Date date0 = DateUtil.getCurDateTime();
    String xml = eleOtaHotelSearchRS.asXML();
    HotelSearchResponse response = (HotelSearchResponse) xs.fromXML(xml);
    int spanMilliSeconds = DateUtil.getPastTime(date0);
    logger.info("xml -> object: " + spanMilliSeconds + "ms.");
    int total = response.getHotelInfos().size();
    if (total == 0) {
        //logger.info(xml);
        if (response.getSuccess() != null) {
            logger.info("There is no hotel.");
            return "OK#0 hotel";
        }
    }

    // return response;
    String rs;
    int saveCount = 0;
    int count = 0;
    for (HotelInfo hotelInfo : response.getHotelInfos()) {
        if (this.serviceStopped)
            break;

        cn.buk.hotel.entity.HotelInfo hotelInfo1 = ConvertUtil.convertHotelInfo(hotelInfo);

        int retCode = hotelDao.createHotelInfo(hotelInfo1);

        if (retCode == 1 || retCode == 2) {
            saveCount++;
        }

        count++;
        if (count % 100 == 0) {
            logger.info("Progress: " + count + " / " + total);
        }
    }

    if (saveCount > 0)
        rs = "OK#" + saveCount + " be saved";
    else
        rs = "ER";

    return rs;
}

From source file:cn.buk.api.service.CtripHotelServiceImpl.java

License:LGPL

/**
 * ?HotelRatePlanResponse//  w ww  .  j av a 2 s  .  c  o  m
 * @param document ??
 * @return ??
 */
private String processHotelRatePlanResponse(final Document document, final int periodId,
        final List<String> hotelCodes) {
    if (document == null)
        return "ER#Document is null.";

    Element rootElement = document.getRootElement();
    Element headerElement = rootElement.element("Header");
    if (!headerElement.attribute("ResultCode").getValue().equalsIgnoreCase("Success")) {
        //logger.error("ER#ResultCode is not Success.");
        logger.error(document.asXML());
        return "ER#ResultCode is not Success.";
    }

    DocumentDto documentDto = new DocumentDto();
    documentDto.setDocument(document);
    documentDto.setPeriodId(periodId);

    for (String hotelCode : hotelCodes)
        documentDto.getHotelCodes().add(hotelCode);

    try {
        logger.debug("Current ratePlanQueue\'s size: " + ratePlanQueue.size());
        logger.debug("put hotelCodes\'s size is " + hotelCodes.size());

        ratePlanQueue.put(documentDto);
        hotelRatePlanDaoExecutor.execute(new HotelRatePlanDaoThread());
    } catch (InterruptedException e) {
        logger.warn(Thread.currentThread().getName() + " is interrupted.");
        return "ER#RatePlanQueue.put is interrupted.";
    }

    return "OK#Document has been added to Queue.";
}

From source file:cn.buk.api.service.CtripHotelServiceImpl.java

License:LGPL

private String processHotelCacheChangeResponse(final Document document) {
    if (document == null)
        return "ER#Document is null.";

    Element rootElement = document.getRootElement();
    Element headerElement = rootElement.element("Header");
    if (!headerElement.attribute("ResultCode").getValue().equalsIgnoreCase("Success")) {
        logger.error(document.asXML());/*from  w  w w. j  av  a  2  s . c  o m*/
        return "ER#ResultCode is not Success.";
    }

    //header?
    getCache().put(new net.sf.ehcache.Element(ConfigData.OTA_HotelCacheChange_Request, headerElement));

    DocumentDto documentDto = new DocumentDto();
    documentDto.setDocument(document);
    try {
        hotelCacheChangeDaoExecutor.execute(new HotelCacheChangeDaoThread());

        logger.debug("Current hotelCacheChangeQueue\'s size is " + hotelCacheChangeQueue.size());
        hotelCacheChangeQueue.put(documentDto);
    } catch (InterruptedException e) {
        logger.warn(Thread.currentThread().getName() + " is interrupted.");
        return "ER#HotelCacheChangeQueue.put is interrupted.";
    }

    return "OK#HotelCacheChange document has been added into queue.";
}

From source file:cn.buk.api.service.CtripHotelServiceImpl.java

License:LGPL

@Override
public synchronized String searchHotelDetail(List<String> hotelCodes, boolean returnXml) {
    if (hotelCodes == null || hotelCodes.size() == 0)
        return "ER#hotelcodes is null";

    //headerAPI?//www.j a  v  a2 s .c  om
    net.sf.ehcache.Element cacheElement = getCache().get(ConfigData.OTA_HotelDetail_Request);
    if (cacheElement != null) {
        Element headerElement = (Element) cacheElement.getValue();
        int accessCount = Integer.parseInt(headerElement.attributeValue("AccessCount"));
        int currentCount = Integer.parseInt(headerElement.attributeValue("CurrentCount")) + 1;
        logger.info(ConfigData.OTA_HotelDetail_Request + " AccessCount="
                + headerElement.attributeValue("AccessCount") + ", CurrentCount="
                + headerElement.attributeValue("CurrentCount") + ", ResetTime="
                + headerElement.attributeValue("ResetTime"));
        if (currentCount >= accessCount) {
            try {
                logger.info("Sleep for one minute.");
                Thread.sleep(60000);
            } catch (InterruptedException ex) {
                logger.warn(Thread.currentThread().getName() + " is interrupted.");
                return "ER#SearchHotelDetail thread.sleep is interrupted.";
            }
        }
    }

    if (this.serviceStopped)
        return "ER#Service stopped.";

    HotelRequestBody request = new HotelRequestBody();
    request.createHotelDetailRequest();
    for (String hotelCode : hotelCodes) {
        if (this.serviceStopped)
            return "ER#Service stopped.";

        HotelDescriptiveInfo hotelDescriptiveInfo = new HotelDescriptiveInfo();
        hotelDescriptiveInfo.setHotelCode(hotelCode);

        cn.buk.hotel.entity.HotelInfo hotelInfo = hotelDao.getHotelDetailInfoByHotelCode(hotelCode);
        if (hotelInfo != null) {
            //if (hotelInfo.getGuestRooms().size() == 0) {
            hotelDescriptiveInfo.setHotelInfoFacilityInfo(new HotelInfoFacilityInfo());
            hotelDescriptiveInfo.getHotelInfoFacilityInfo().setSendGuestRooms(true);
            //}

            if (hotelInfo.getRefPoints().size() == 0) {
                hotelDescriptiveInfo.setHotelInfoAreaInfo(new HotelInfoAreaInfo());
                hotelDescriptiveInfo.getHotelInfoAreaInfo().setSendAttractions(true);
                hotelDescriptiveInfo.getHotelInfoAreaInfo().setSendRecreations(true);
            }

            if (hotelInfo.getMedias().size() == 0) {
                hotelDescriptiveInfo.setHotelInfoMultimedia(new HotelInfoMultimedia());
                hotelDescriptiveInfo.getHotelInfoMultimedia().setSendData(true);
            }
        }

        request.getHotelDetailRequest().getHotelDescriptiveInfos().add(hotelDescriptiveInfo);
    }

    String requestXml;

    try {
        JAXBContext jc = JAXBContext.newInstance(HotelRequestBody.class);

        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        DocumentResult documentResult = new DocumentResult();
        m.marshal(request, documentResult);

        org.dom4j.Document document = documentResult.getDocument();
        org.dom4j.Element requestElement = document.getRootElement();

        Element ele = requestElement.element("OTA_HotelDescriptiveInfoRQ");
        ele.addNamespace("", "http://www.opentravel.org/OTA/2003/05");

        org.dom4j.Document doc1 = DocumentHelper.createDocument();

        if (this.serviceStopped)
            return "ER#Service stopped.";

        org.dom4j.Element rootElement = createRequestHeaderElement(doc1, ConfigData.OTA_HotelDetail_Request);
        rootElement.add(requestElement);

        requestXml = doc1.asXML();
    } catch (JAXBException e) {
        e.printStackTrace();
        return "ER#OTA_exception";
    }

    Date date0 = DateUtil.getCurDateTime();

    logger.debug(ConfigData.OTA_HotelDetail_Request + ": begin");
    logger.debug(requestXml);

    if (this.serviceStopped)
        return "ER#Service stopped.";
    String response = execApiRequest(requestXml, ConfigData.OTA_HotelDetail_Url, "requestXML");

    logger.debug(response);
    int apiElapsedTime = DateUtil.getPastTime(date0);
    logger.debug(ConfigData.OTA_HotelDetail_Request + ": end, " + apiElapsedTime + "ms");

    if (returnXml)
        return response;

    //?
    String rs;
    SAXReader reader = new SAXReader();
    Document document;// ?XML
    try {
        document = reader.read(new StringReader(response));
        Element headerElement = document.getRootElement().element("Header");

        //header?
        getCache().put(new net.sf.ehcache.Element(ConfigData.OTA_HotelDetail_Request, headerElement));

        if (!headerElement.attribute("ResultCode").getValue().equalsIgnoreCase("Success")) {
            logger.error(requestXml);
            logger.error(document.asXML());
            return "ER#ResultCode is not Success.";
        }

        DocumentDto documentDto = new DocumentDto();
        documentDto.setDocument(document);

        if (hotelDetailQueue.size() == MAX_HOTEL_DETAIL_QUEUE) {
            logger.warn("hotelDetailQueue is full, thread will be blocked here.");
        }
        hotelDetailQueue.put(documentDto);
        hotelDetailDaoExecutor.execute(new HotelDetailDaoThread());

        rs = "OK#save to the queue.";
    } catch (InterruptedException ex) {
        return "ER#Interrupt occured.";
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        return "ER#searchHotelDetail";
    }

    return rs;
}

From source file:cn.buk.api.service.CtripHotelServiceImpl.java

License:LGPL

@Override
public String searchHotelRatePlan(final String hotelCode, Date startDate, Date endDate,
        final boolean returnXml) {
    List<String> hotelCodes = new ArrayList<String>();
    hotelCodes.add(hotelCode);/*w  w w .j  a v  a 2 s. c  o  m*/
    String response = execSearchHotelRatePlan(hotelCodes, startDate, endDate);
    if (returnXml)
        return response;

    //?
    String rs = "rs";
    SAXReader reader = new SAXReader();
    Document document;// ?XML
    try {
        document = reader.read(new StringReader(response));
    } catch (DocumentException e) {
        logger.error(e.getMessage());
        return "ER#xml->document";
    }

    if (document == null)
        return "ER#Document is null.";

    Element rootElement = document.getRootElement();
    Element headerElement = rootElement.element("Header");
    if (!headerElement.attribute("ResultCode").getValue().equalsIgnoreCase("Success")) {
        //logger.error("ER#ResultCode is not Success.");
        logger.error(document.asXML());
        return "ER#ResultCode is not Success.";
    }

    rs = processHotelRatePlanResponse(document, 0, hotelCodes);

    return rs;
}

From source file:cn.buk.api.service.CtripHotelServiceImpl.java

License:LGPL

private synchronized String doSearchHotelRatePlan(String requestXml) {

    logger.debug("doSearchHotelRatePlan begin..." + Thread.currentThread().getName());

    //headerAPI?/* w ww  .  jav a 2 s  .c om*/
    String cacheKey = ConfigData.OTA_HotelRatePlan_Request;
    net.sf.ehcache.Element cacheElement = getCache().get(cacheKey);
    if (cacheElement != null) {
        Element headerElement = (Element) cacheElement.getValue();
        int accessCount = Integer.parseInt(headerElement.attributeValue("AccessCount"));
        int currentCount = Integer.parseInt(headerElement.attributeValue("CurrentCount")) + 1;
        logger.info(ConfigData.OTA_HotelRatePlan_Request + " AccessCount="
                + headerElement.attributeValue("AccessCount") + ", CurrentCount="
                + headerElement.attributeValue("CurrentCount") + ", ResetTime="
                + headerElement.attributeValue("ResetTime"));
        if (currentCount >= accessCount) {
            try {
                logger.info("Sleep for one minute.");
                Thread.sleep(60000);
            } catch (InterruptedException ex) {
                logger.warn(Thread.currentThread().getName() + " is interrupted.");
                return "ER#DoSearchHotelRatePlan thread.sleep is interrupted.";
            }
        }
    }
    if (this.serviceStopped)
        return "ER#Service is stopped.";

    Date date0 = DateUtil.getCurDateTime();

    String response = execApiRequest(requestXml, ConfigData.OTA_HotelRatePlan_Url, "requestXML");

    int apiElapsedTime = DateUtil.getPastTime(date0);
    if (apiElapsedTime > 1000)
        logger.debug(ConfigData.OTA_HotelRatePlan_Request + " API: " + apiElapsedTime + "ms");

    //?
    try {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(response));
        Element rootElement = document.getRootElement();
        Element headerElement = rootElement.element("Header");
        if (headerElement.attribute("ResultCode").getValue().equalsIgnoreCase("Success")) {
            //header?
            logger.debug("put headerElement to cache by key " + ConfigData.OTA_HotelRatePlan_Request);
            getCache().put(new net.sf.ehcache.Element(ConfigData.OTA_HotelRatePlan_Request, headerElement));
        } else {
            logger.error(response);
            logger.error("ResultCode is not Success.");
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
    }

    logger.debug("doSearchHotelRatePlan end..." + Thread.currentThread().getName());

    return response;
}

From source file:com.ah.be.ls.stat.StatManager.java

private static List<StatConfig> readStatConfig() {
    if (stats != null && !stats.isEmpty()) {
        return stats;
    }/*from   www  . jav a  2s .  co m*/
    stats = new ArrayList<StatConfig>();
    // read from stat-config.xml
    SAXReader reader = new SAXReader();
    File ff = new File(System.getenv("HM_ROOT") + "/resources/stat-config.xml");
    if (!ff.exists()) {
        // for test
        ff = new File("stat-config.xml");
    }
    try {
        Document doc = reader.read(ff);

        Element roota = doc.getRootElement();
        log.info("StatManager", "roota..nodcount=" + roota.nodeCount());

        Iterator<?> iters = roota.elementIterator("feature");
        while (iters.hasNext()) {
            StatConfig stat = new StatConfig();
            Element foo = (Element) iters.next();
            if (foo.attribute("ignore") != null) {
                continue;
            }
            stat.setFeatureId(Integer.valueOf(foo.attributeValue("id")));
            stat.setFeatureName(foo.attributeValue("name"));

            Element e2 = foo.element("bo-class");
            Element e4 = foo.element("search-rule");
            stat.setBoClassName(e2.attributeValue("name"));
            stat.setSearchRule(e4.attributeValue("value"));
            stat.setSearchType(e4.attributeValue("type"));

            stats.add(stat);
        }

        return stats;
    } catch (ClassNotFoundException e) {
        log.error("StatManager", "readStatConfig: ClassNotFoundException", e);
    } catch (Exception e) {
        log.error("StatManager", "readStatConfig: Exception", e);
    }

    return null;
}

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 av  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.alibaba.citrus.springext.impl.SchemaImpl.java

License:Open Source License

/**
 * ?schema??/*  w  ww. j av  a  2  s .c o m*/
 * <ol>
 * <li>targetNamespace</li>
 * <li>include name</li>
 * </ol>
 */
@Override
protected void doAnalyze() {
    Document doc = getDocument(); // ??null
    org.dom4j.Element root = doc.getRootElement();

    // return if not a schema file
    if (!W3C_XML_SCHEMA_NS_URI.equals(root.getNamespaceURI()) || !"schema".equals(root.getName())) {
        return;
    }

    // parse targetNamespace
    if (parsingTargetNamespace) {
        Attribute attr = root.attribute("targetNamespace");

        if (attr != null) {
            targetNamespace = trimToNull(attr.getStringValue());
        }
    }

    // parse include
    Namespace xsd = DocumentHelper.createNamespace("xsd", W3C_XML_SCHEMA_NS_URI);
    QName includeName = DocumentHelper.createQName("include", xsd);
    List<String> includeNames = createLinkedList();

    // for each <xsd:include>
    for (Iterator<?> i = root.elementIterator(includeName); i.hasNext();) {
        org.dom4j.Element includeElement = (org.dom4j.Element) i.next();
        String schemaLocation = trimToNull(includeElement.attributeValue("schemaLocation"));

        if (schemaLocation != null) {
            includeNames.add(schemaLocation);
        }
    }

    includes = includeNames.toArray(new String[includeNames.size()]);

    // parse xsd:element
    QName elementName = DocumentHelper.createQName("element", xsd);

    // for each <xsd:element>
    for (Iterator<?> i = root.elementIterator(elementName); i.hasNext();) {
        Element element = new ElementImpl((org.dom4j.Element) i.next());

        if (element.getName() != null) {
            this.elements.put(element.getName(), element);
        }
    }
}

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

License:Open Source License

/** element/attribute??namespace */
public static Transformer getUnqualifiedStyleTransformer(ResourceResolver resourceResolver) {
    if (isUnqualifiedStyle(resourceResolver)) {
        return new Transformer() {
            public void transform(Document document, String systemId) {
                Element root = document.getRootElement();

                if (root.attribute("elementFormDefault") != null) {
                    root.remove(root.attribute("elementFormDefault"));
                }//  w w w  . j  a  va2  s . com

                if (root.attribute("attributeFormDefault") != null) {
                    root.remove(root.attribute("attributeFormDefault"));
                }
            }
        };
    } else {
        return getNoopTransformer();
    }
}