Example usage for org.dom4j.io SAXReader read

List of usage examples for org.dom4j.io SAXReader read

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader read.

Prototype

public Document read(InputSource in) throws DocumentException 

Source Link

Document

Reads a Document from the given InputSource using SAX

Usage

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

License:LGPL

@Override
public String importCityInfo(String filename) {
    SAXReader reader = new SAXReader();

    File file = new File(filename);
    if (!file.exists())
        return "not exist.";
    Document document;// ?XML
    try {//from w w w.ja v a2  s.c o m
        document = reader.read(file);
    } catch (DocumentException e) {
        e.printStackTrace();
        return "error";
    }

    List flightDataList = document.selectNodes("//CityDetails/*");
    List<City> cities = new ArrayList<City>();
    String temp;
    for (Iterator it = flightDataList.iterator(); it.hasNext();) {
        Element fltElement = (Element) it.next();

        City city = new City();
        cities.add(city);

        city.setCityCode(fltElement.element("CityCode").getText());
        city.setOpenApiId(Integer.parseInt(fltElement.element("City").getText()));
        city.setCityName(fltElement.element("CityName").getText());
        city.setCityEnglishName(fltElement.elementText("CityEName").trim());
        temp = fltElement.elementText("Country").trim();
        if (temp.equalsIgnoreCase("1"))
            city.setCountryCode("CN");
        else
            city.setCountryCode(temp);
        city.setProvinceId(Integer.parseInt(fltElement.elementText("Province")));
        city.setAirport(fltElement.element("Airport").getText());
    }

    int count = 0;
    for (City city : cities) {
        if (city.getCityCode() == null || city.getCityCode().trim().length() == 0)
            continue;
        if (cityDao.create(city) == 1)
            count++;
    }

    return "create " + count + " record(s).";
}

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

License:LGPL

@Override
public String importDistrictInfo(String filename) {
    SAXReader reader = new SAXReader();

    File file = new File(filename);
    if (!file.exists())
        return "not exist.";
    Document document;// ?XML
    try {/*from   w ww  .  jav  a2 s. co  m*/
        document = reader.read(file);
    } catch (DocumentException e) {
        e.printStackTrace();
        return "error";
    }

    List list = document.selectNodes("//LocationDetails/*");
    List<District> districts = new ArrayList<District>();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Element element = (Element) it.next();

        District district = new District();
        districts.add(district);

        district.setName(element.element("LocationName").getText());
        district.setEnglishName(element.element("LocationEName").getText());
        district.setDistrictId(Integer.parseInt(element.element("Location").getText()));
        district.setCityId(Integer.parseInt(element.element("LocationCity").getText()));
    }

    int count = 0;
    for (District district : districts) {
        if (hotelDao.createDistrict(district) == 1)
            count++;
    }

    return "create " + count + " record(s).";
}

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

License:LGPL

@Override
public String importZoneInfo(String filename) {
    SAXReader reader = new SAXReader();

    File file = new File(filename);
    if (!file.exists())
        return "not exist.";
    Document document;// ?XML
    try {/*from www  .j av a  2  s. c  o m*/
        document = reader.read(file);
    } catch (DocumentException e) {
        e.printStackTrace();
        return "error";
    }

    List list = document.selectNodes("//ZoneDetails/*");
    List<Zone> zones = new ArrayList<Zone>();
    int maxLength = 0;
    for (Iterator it = list.iterator(); it.hasNext();) {
        Element element = (Element) it.next();

        Zone zone = new Zone();
        zones.add(zone);

        zone.setZoneId(Integer.parseInt(element.element("Zone").getText()));
        zone.setCityId(Integer.parseInt(element.element("City").getText()));
        zone.setName(element.element("ZoneName").getText());
        zone.setEnglishName(element.element("ZoneEName").getText());
        zone.setDescription(element.element("ZoneDesc").getText());
        if (zone.getDescription().length() > maxLength)
            maxLength = zone.getDescription().length();
        zone.setMapUse(element.element("ZoneMapuse").getText());
        zone.setMapRange(element.element("ZoneRange").getText());
        zone.setMapPic(element.element("ZoneMapPic").getText());
    }

    int count = 0;
    for (Zone zone : zones) {
        if (hotelDao.createZone(zone) == 1)
            count++;
    }
    System.out.println(maxLength);

    return "create " + count + " record(s).";
}

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

License:LGPL

/**
 * ??/* ww  w  . j  a  v  a  2 s  .  c  om*/
 * @param cityId ?
 * @return ??
 */
@Override
public String searchHotel(int cityId) {
    if (cityId <= 0)
        return "ER#CITYID IS " + cityId;

    //headerAPI?
    Cache cache = getCache();
    String cacheKey = ConfigData.OTA_HotelSearch_Request;
    net.sf.ehcache.Element cacheElement = cache.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("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#Thread.sleep is interrupted.";
            }
        }
    }

    HotelRequestBody request = new HotelRequestBody();
    request.createHotelRequestRQ();
    request.getHotelRequestRQ().getCriteria().getCriterion().getHotelRef().setHotelCityCode(cityId);
    String xml;

    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_HotelSearchRQ");
        ele.addNamespace("", "http://www.opentravel.org/OTA/2003/05");

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

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

        xml = doc1.asXML();
    } catch (JAXBException ex) {
        logger.error(ex.getMessage());
        return "ER";
    }

    if (serviceStopped)
        return "ER#Service stopped.";
    String response = execApiRequest(xml, ConfigData.OTA_HotelSearch_Url, "requestXML");
    //?
    SAXReader reader = new SAXReader();

    Document document;// ?XML
    try {
        document = reader.read(new StringReader(response));

        if (serviceStopped)
            return "ER#Service stopped.";
        response = processHotelSearchResponse(document);
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        return "ER";
    }

    return response;
}

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

License:LGPL

@Override
public String importHotelSearchRS(String filename) {
    String rs;//from ww w  .  j ava 2 s . co m
    SAXReader reader = new SAXReader();

    logger.info("filename: " + filename);

    File file = new File(filename);
    if (!file.exists())
        return null;

    Document document;// ?XML
    try {
        document = reader.read(file);
    } catch (DocumentException e) {
        e.printStackTrace();
        return "error";
    }

    rs = processHotelSearchResponse(document);

    return rs;
}

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?// ww  w .  j a  v  a 2s  .c o  m
    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 List<String> hotelCodes, final int periodId, final boolean returnXml) {
    if (hotelCodes == null || hotelCodes.size() == 0)
        return "ER#hotelcodes is null or empty.";

    int minDay = (periodId - 1) * 28;
    int maxDay = periodId * 28;
    if (maxDay > 90)
        maxDay = 90;// ww w.  j av  a  2 s  . c  om

    if (minDay >= this.maxDaysOfHotelRate)
        return "ER#Exceed the max day of rate!";
    if (maxDay > this.maxDaysOfHotelRate)
        maxDay = this.maxDaysOfHotelRate;

    Date startDate = DateUtil.add(DateUtil.getCurDate(), minDay);
    Date endDate = DateUtil.add(DateUtil.getCurDate(), maxDay);

    String response = execSearchHotelRatePlan(hotelCodes, startDate, endDate);
    if (this.serviceStopped)
        return "ER#EXIT";

    //?
    String 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";
    }

    try {
        rs = processHotelRatePlanResponse(document, periodId, hotelCodes);
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        logger.debug(response);
        return "ER#processHotelRatePlanResponse";
    }

    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 .java2 s .co  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?//from  www.  ja v a  2  s .com
    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:cn.buk.api.service.CtripHotelServiceImpl.java

License:LGPL

@Override
public String importHotelRatePlanResponse(String filename) {
    String rs;//from   w  ww . j  a v a2  s .co m
    SAXReader reader = new SAXReader();

    logger.info("filename: " + filename);

    File file = new File(filename);
    if (!file.exists())
        return null;

    Document document;// ?XML
    try {
        document = reader.read(file);
    } catch (DocumentException e) {
        e.printStackTrace();
        return "error";
    }

    rs = processHotelRatePlanResponse(document, 1, new ArrayList<String>());

    return rs;
}