Example usage for org.dom4j.io SAXReader SAXReader

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

Introduction

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

Prototype

public SAXReader() 

Source Link

Usage

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

License:LGPL

private String processHotelCacheChange(String xml) {
    String retval;//www  .  j  av  a  2s. c  om
    //?
    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.
 * /*from   w w  w .ja  va 2s.  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 a2s .  co  m*/
    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   ww  w .ja v a 2s.  com*/
        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 w ww.  j ava2 s.  c o 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 {/*  w  ww  .j av a  2  s  . com*/

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

From source file:cn.itcreator.android.reader.util.XMLUtil.java

License:Open Source License

/**
 * //w w  w. j av a2 s  .c om
 * @param filePath
 *             xml file path
 */
public XMLUtil(String filePath) {
    this.mFilePath = filePath;
    mFile = new File(mFilePath);
    if (!mFile.exists()) {
        try {
            mFile.createNewFile();
            mDocument = DocumentHelper.createDocument();
            // create new xml document
        } catch (IOException e) {
            mDocument = DocumentHelper.createDocument();
        }
    } else {
        try {
            mDocument = new SAXReader().read(mFile);
        } catch (DocumentException e) {
            mDocument = DocumentHelper.createDocument();
        }
    }
    System.gc();
}

From source file:cn.kee.engine.common.SystemInitServlet.java

private Document readerDom(File flie) {
    Document doc = null;//w ww.  j  a  va 2 s  .  com
    SAXReader reader = new SAXReader();
    reader.setValidation(false);
    reader.setEntityResolver(new NoOpEntityResolver());
    try {
        doc = reader.read(flie);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return doc;
}

From source file:cn.mario256.blog.service.impl.ThemeServiceImpl.java

License:Open Source License

/**
 * ?//ww  w . ja v a2  s.  c o  m
 * 
 * @param themeXmlFile
 *            ?
 * @return 
 */
private Theme get(File themeXmlFile) {
    try {
        Document document = new SAXReader().read(themeXmlFile);
        Node idNode = document.selectSingleNode("/theme/id");
        Node nameNode = document.selectSingleNode("/theme/name");
        Node versionNode = document.selectSingleNode("/theme/version");
        Node authorNode = document.selectSingleNode("/theme/author");
        Node siteUrlNode = document.selectSingleNode("/theme/siteUrl");
        Node previewNode = document.selectSingleNode("/theme/preview");

        Theme theme = new Theme();
        theme.setId(idNode != null ? idNode.getText().trim() : null);
        theme.setName(nameNode != null ? nameNode.getText().trim() : null);
        theme.setVersion(versionNode != null ? versionNode.getText().trim() : null);
        theme.setAuthor(authorNode != null ? authorNode.getText().trim() : null);
        theme.setSiteUrl(siteUrlNode != null ? siteUrlNode.getText().trim() : null);
        theme.setPreview(previewNode != null ? previewNode.getText().trim() : null);
        return theme;
    } catch (DocumentException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:cn.mario256.blog.util.SystemUtils.java

License:Open Source License

/**
 * ?/* w ww . j a v  a2 s .co  m*/
 * 
 * @return 
 */
@SuppressWarnings("unchecked")
public static Setting getSetting() {
    Ehcache cache = CACHE_MANAGER.getEhcache(Setting.CACHE_NAME);
    String cacheKey = "setting";
    Element cacheElement = cache.get(cacheKey);
    if (cacheElement == null) {
        Setting setting = new Setting();
        try {
            File turingXmlFile = new ClassPathResource(CommonAttributes.TURING_XML_PATH).getFile();
            Document document = new SAXReader().read(turingXmlFile);
            List<org.dom4j.Element> elements = document.selectNodes("/turing/setting");
            for (org.dom4j.Element element : elements) {
                try {
                    String name = element.attributeValue("name");
                    String value = element.attributeValue("value");
                    BEAN_UTILS.setProperty(setting, name, value);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e.getMessage(), e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (DocumentException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        cache.put(new Element(cacheKey, setting));
        cacheElement = cache.get(cacheKey);
    }
    return (Setting) cacheElement.getObjectValue();
}