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 importHotelCacheChangeResponse(String filename) {
    String rs;// w w  w  .  j av  a 2 s  .  c om
    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 = processHotelCacheChangeResponse(document);

    return rs;
}

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

License:LGPL

/**
 * ??//  w w  w.jav a  2s. com
 * @param hotelCode
 * @param checkInDate
 * @param checkOutDate
 * @param ratePlanCode
 * @param roomQuantity
 * @param guestCount
 * @param lateArrivalTime
 * @return
 */
@Override
public String checkHotelAvail(String hotelCode, Date checkInDate, Date checkOutDate, String ratePlanCode,
        int roomQuantity, int guestCount, Date lateArrivalTime, boolean returnXml) {
    HotelRequestBody request = new HotelRequestBody();

    //
    if (checkInDate.getTime() < DateUtil.getCurDate().getTime())
        checkInDate = DateUtil.getCurDate();
    if (checkInDate.getTime() >= checkOutDate.getTime())
        checkOutDate = DateUtil.add(checkInDate, 1);
    if (lateArrivalTime.getTime() <= DateUtil.getCurDateTime().getTime())
        lateArrivalTime = DateUtil.addMinutes(DateUtil.getCurDateTime(), 5);

    request.createHotelAvailRequest();
    HotelAvailRequestSegment hotelAvailRequestSegment = new HotelAvailRequestSegment();
    request.getHotelAvailRequest().getHotelAvailRequestSegments().add(hotelAvailRequestSegment);

    HotelSearchCriterion criterion = hotelAvailRequestSegment.getHotelSearchCriteria().getCriterion();
    criterion.getHotelRef().setHotelCode(hotelCode);
    criterion.getHotelStayDateRange().setStartDate(DateUtil.formatDate(checkInDate, "yyyy-MM-dd"));
    criterion.getHotelStayDateRange().setEndDate(DateUtil.formatDate(checkOutDate, "yyyy-MM-dd"));

    HotelRatePlanCandidate ratePlanCandidate = new HotelRatePlanCandidate();
    criterion.getRatePlanCandidates().add(ratePlanCandidate);
    ratePlanCandidate.setRatePlanCode(ratePlanCode);

    RoomStayCandidate roomStayCandidate = new RoomStayCandidate();
    criterion.getRoomStayCandidates().add(roomStayCandidate);
    roomStayCandidate.setQuantity(roomQuantity);

    roomStayCandidate.getRoomGuestCount().getGuestCount().setCount(guestCount);
    roomStayCandidate.getRoomGuestCount().setPerRoom(false);

    criterion.getHotelLateArrivalTime()
            .setLateArrivalTime(DateUtil.formatDate(lateArrivalTime, "yyyy-MM-dd'T'HH:mm:ss"));

    String xml;

    try {
        xml = createXml4HotelRequestBody(request, ConfigData.OTA_HotelAvail_Request);
    } catch (JAXBException ex) {
        ex.printStackTrace();
        logger.error(ex.getMessage());
        return "ER";
    }

    logger.debug(xml);

    //        return xml;

    if (serviceStopped)
        return "ER#Service stopped.";
    String response = execApiRequest(xml, ConfigData.OTA_HotelAvail_Url, "requestXML");

    logger.debug(response);

    if (returnXml)
        return response;

    //?
    SAXReader reader = new SAXReader();

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

        if (serviceStopped)
            return "ER#Service stopped.";
        response = processHotelAvailResponse(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 importHotelAvailResponse(String xml_file) {
    String rs;/*from   www .ja v  a2 s. c om*/
    SAXReader reader = new SAXReader();

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

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

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

    rs = processHotelAvailResponse(document);

    return rs;
}

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

License:LGPL

private List<HotelAvailResponseRoomStay> processHotelAvailResponse(String responseXml) {
    List<HotelAvailResponseRoomStay> roomStays = new ArrayList<HotelAvailResponseRoomStay>();

    //?//  ww  w  . jav  a  2 s.com
    SAXReader reader = new SAXReader();
    Document document;// ?XML
    try {
        document = reader.read(new StringReader(responseXml));

        //?????
        Map uris = new HashMap();
        uris.put("ns", "http://www.opentravel.org/OTA/2003/05");
        XPath xpath = document.createXPath("//ns:RoomStays/*");
        xpath.setNamespaceURIs(uris);
        List myNodes = xpath.selectNodes(document);

        if (myNodes.size() == 0) {
            logger.warn("ER#There is nothing.");
            return roomStays;
        }

        XStream xs = createXStream();
        xs.alias("RoomStay", HotelAvailResponseRoomStay.class);
        xs.processAnnotations(HotelAvailResponseRoomStay.class);

        String xml;

        for (Iterator it = myNodes.iterator(); it.hasNext();) {
            //if (serviceStopped) break;

            Element element = (Element) it.next();

            xml = element.asXML();
            HotelAvailResponseRoomStay roomStay = (HotelAvailResponseRoomStay) xs.fromXML(xml);
            roomStays.add(roomStay);
        }

    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }

    return roomStays;
}

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

License:LGPL

private String processHotelCacheChange(String xml) {
    String retval;/*from   www .  j a v a 2s  . c o m*/
    //?
    SAXReader reader = new SAXReader();

    Document document;// ?XML
    try {
        document = reader.read(new StringReader(xml));
        retval = processHotelCacheChangeResponse(document);
    } catch (Exception ex) {
        ex.printStackTrace();
        return "ER";
    }

    return retval;
}

From source file:cn.com.iscs.base.util.XMLProperties.java

License:Open Source License

/**
 * Builds the document XML model up based the given reader of XML data.
 * // w ww. ja  va 2  s . co m
 * @param in
 *          the input stream used to build the xml document
 * @throws java.io.IOException
 *           thrown when an error occurs reading the input stream.
 */
private void buildDoc(Reader in) throws IOException {
    try {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        document = xmlReader.read(in);
    } catch (Exception e) {
        System.err.print("Error reading XML properties");
        throw new IOException(e.getMessage());
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:cn.com.xdays.xshop.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }/*w w w .j a v  a 2  s .  com*/
    if (StringUtils.isEmpty(databaseHost)) {
        return ajaxJsonErrorMessage("?!");
    }
    if (StringUtils.isEmpty(databasePort)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(databasePassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(databaseName)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminUsername)) {
        return ajaxJsonErrorMessage("???!");
    }
    if (StringUtils.isEmpty(adminPassword)) {
        return ajaxJsonErrorMessage("??!");
    }
    if (StringUtils.isEmpty(installStatus)) {
        Map<String, String> jsonMap = new HashMap<String, String>();
        jsonMap.put(STATUS, "requiredCheckFinish");
        return ajaxJson(jsonMap);
    }

    String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName
            + "?useUnicode=true&characterEncoding=UTF-8";

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        // ?
        connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword);
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        String[] types = { "TABLE" };
        resultSet = databaseMetaData.getTables(null, databaseName, "%", types);
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) {
            Map<String, String> jsonMap = new HashMap<String, String>();
            jsonMap.put(STATUS, "databaseCheckFinish");
            return ajaxJson(jsonMap);
        }

        // ?
        if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) {
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader bufferedReader = null;
            String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
                    .getPath() + SQL_INSTALL_FILE_NAME;
            bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8"));
            String line = "";
            while (null != line) {
                line = bufferedReader.readLine();
                stringBuffer.append(line);
                if (null != line && line.endsWith(";")) {
                    System.out.println("[SHOP++?]SQL: " + line);
                    preparedStatement = connection.prepareStatement(stringBuffer.toString());
                    preparedStatement.executeUpdate();
                    stringBuffer = new StringBuffer();
                }
            }
            String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','"
                    + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');";
            String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');";
            preparedStatement = connection.prepareStatement(insertAdminSql);
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(insertAdminRoleSql);
            preparedStatement.executeUpdate();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return ajaxJsonErrorMessage("???!");
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
                resultSet = null;
            }
            if (preparedStatement != null) {
                preparedStatement.close();
                preparedStatement = null;
            }
            if (connection != null) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // ???
    String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()
            + JDBC_CONFIG_FILE_NAME;
    Properties properties = new Properties();
    properties.put("jdbc.driver", "com.mysql.jdbc.Driver");
    properties.put("jdbc.url", jdbcUrl);
    properties.put("jdbc.username", databaseUsername);
    properties.put("jdbc.password", databasePassword);
    properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    properties.put("hibernate.show_sql", "false");
    properties.put("hibernate.format_sql", "false");
    OutputStream outputStream = new FileOutputStream(configFilePath);
    properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION);
    outputStream.close();

    // ??
    String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + BACKUP_WEB_CONFIG_FILE_NAME;
    String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    String webConfigFilePath = new File(
            Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/"
            + WEB_CONFIG_FILE_NAME;
    String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("")
            .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME;
    String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader()
            .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME;

    FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath));
    FileUtils.copyFile(new File(backupApplicationContextConfigFilePath),
            new File(applicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath),
            new File(compassApplicationContextConfigFilePath));
    FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath),
            new File(securityApplicationContextConfigFilePath));

    // ??
    String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
            .getPath() + SystemConfigUtil.CONFIG_FILE_NAME;
    File systemConfigFile = new File(systemConfigFilePath);
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(systemConfigFile);
    Element rootElement = document.getRootElement();
    Element systemConfigElement = rootElement.element("systemConfig");
    Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled");
    if (isInstalledNode == null) {
        isInstalledNode = systemConfigElement.addElement("isInstalled");
    }
    isInstalledNode.setText("true");
    try {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML?
        outputFormat.setEncoding("UTF-8");// XML?
        outputFormat.setIndent(true);// ?
        outputFormat.setIndent("   ");// TAB?
        outputFormat.setNewlines(true);// ??
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat);
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ajaxJsonSuccessMessage("SHOP++?????");
}

From source file:cn.com.xdays.xshop.action.admin.InstallAction.java

private boolean isInstalled() {
    try {//from   w w w  .j av  a 2  s.  c  o  m
        String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI()
                .getPath() + SystemConfigUtil.CONFIG_FILE_NAME;
        File systemConfigFile = new File(systemConfigFilePath);
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(systemConfigFile);
        Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled");
        if (isInstalledNode != null && StringUtils.equalsIgnoreCase(isInstalledNode.getText(), "false")) {
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return true;
    }
}

From source file:cn.ict.zyq.bestConf.util.ParseXMLToYaml.java

License:Open Source License

public static HashMap parseXMLToHashmap(String filePath) {
    HashMap result = new HashMap();
    try {/*from   ww w.ja v  a2  s .  co  m*/
        File f = new File(filePath);
        SAXReader reader = new SAXReader();
        Document doc = reader.read(f);
        Element root = doc.getRootElement();
        Element foo;
        for (Iterator i = root.elementIterator("property"); i.hasNext();) {
            foo = (Element) i.next();
            String value;
            if (foo.elementText("value") != null) {
                value = foo.elementText("value");
                Pattern pattern = Pattern.compile("^-?[0-9]\\d*$");
                Matcher matcher = pattern.matcher(value);
                if (matcher.find()) {
                    result.put(foo.elementText("name"), value);
                } else if (Pattern.compile("^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$").matcher(value)
                        .find()) {
                    result.put(foo.elementText("name"), value);
                } else {
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:cn.ict.zyq.bestConf.util.ParseXMLToYaml.java

License:Open Source License

public static void appendXMLByDOM4J(HashMap target, String source, String destination) throws IOException {

    SAXReader reader = new SAXReader();
    try {//from w ww . j a  va  2 s .  c  o m

        Document document = reader.read(new File(source));
        Element configStore = document.getRootElement();
        Iterator iter = target.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = entry.getKey().toString();
            String val = entry.getValue().toString();
            Element property = configStore.addElement("property");
            Element name = property.addElement("name");
            name.setText(key);
            Element value = property.addElement("value");
            value.setText(val);
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileOutputStream(destination), format);
        writer.write(document);
        writer.close();

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