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:com.eurelis.tools.xml.transformation.local.LocalDocumentSource.java

License:Open Source License

/**
 * Read a dom4j document from a File object.
 *
 * @param file the File object indicating the document position
 * @return the read document/*from  www.j a  v  a  2  s. c  om*/
 * @throws Exception any exception that might occurs while trying to convert the file to a dom4j document
 */
public static Document readDocument(File file) throws Exception {
    Document document = null;
    SAXReader saxReader = new SAXReader();

    InputStream ist = new FileInputStream(file);
    Charset charset = Charset.forName("UTF-8");
    Reader reader = new BufferedReader(new InputStreamReader(ist, charset));
    InputSource source = new InputSource(reader);

    document = saxReader.read(source);

    return document;
}

From source file:com.eurelis.tools.xml.transformation.opencms.OpenCmsDocumentSource.java

License:Open Source License

public OpenCmsDocumentSource(String documentPath, CmsObject cmsObject, boolean ignoreInitialValidation)
        throws CmsException, DocumentException, IOException {
    this.cmsObject = cmsObject;
    cmsFile = this.cmsObject.readFile(documentPath);
    cmsObject.lockResource(cmsFile);//from   ww  w  .  ja  v  a  2 s  .  c  om

    this.documentPath = documentPath;

    byte[] documentBytes = cmsFile.getContents();

    SAXReader saxReader = new SAXReader();
    InputStream is = new ByteArrayInputStream(documentBytes);
    this.initialDocument = saxReader.read(is);
    this.ignoreInitialValidation = ignoreInitialValidation;

    is.close();

    cmsObject.unlockResource(cmsFile);

}

From source file:com.ewcms.content.particular.util.XmlConvert.java

License:Open Source License

@SuppressWarnings("unchecked")
public static List<Map<String, Object>> importXML(File xmlFile, String fileType) {
    if (xmlFile != null) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {//from   ww  w .ja v  a  2 s  . co  m
            List<InputStream> inputStreams = new ArrayList<InputStream>();
            //FileType fileType = FileTypeJudge.getType(xmlFile);
            if (fileType.toLowerCase().equals("application/zip")) {
                inputStreams = parseXmlZIPFile(xmlFile);
            } else if (fileType.toLowerCase().equals("text/xml")) {
                InputStream in = new FileInputStream(xmlFile);
                inputStreams.add(in);
            } else {
                return null;
            }
            if (!inputStreams.isEmpty()) {
                SAXReader reader = new SAXReader();
                Document doc = null;
                for (InputStream inputStream : inputStreams) {
                    try {
                        doc = reader.read(inputStream);
                        if (doc != null) {
                            Element root = doc.getRootElement();
                            Element metaViewData;
                            Element projecties;
                            for (Iterator<?> metaViewDataIterator = root
                                    .elementIterator("MetaViewData"); metaViewDataIterator.hasNext();) {
                                metaViewData = (Element) metaViewDataIterator.next();
                                for (Iterator<?> projectiesIterator = metaViewData
                                        .elementIterator("PROPERTIES"); projectiesIterator.hasNext();) {
                                    projecties = (Element) projectiesIterator.next();
                                    List<Element> elements = projecties.elements();
                                    if (!elements.isEmpty()) {
                                        Map<String, Object> map = new HashMap<String, Object>();
                                        for (Element element : elements) {
                                            map.put(element.getName(), element.getData());
                                        }
                                        list.add(map);
                                    }
                                }
                            }
                        }
                    } catch (DocumentException e) {
                    } finally {
                        if (doc != null) {
                            doc.clearContent();
                            doc = null;
                        }
                    }
                }
            }
        } catch (IOException e) {
            return null;
        }
        return list;
    }
    return null;
}

From source file:com.faithbj.shop.action.admin.InstallAction.java

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("CAIJINGLING?????");
    }/*w w  w.j  a va 2  s .c  om*/
    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 {
        // ?
        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("[CAIJINGLING?]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 (SQLException 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("CAIJINGLING?????");
}

From source file:com.feilong.framework.netpay.advance.adaptor.alipay.AlipayAdvanceAdaptor.java

License:Apache License

/**
 * ??xml?.//w w w . ja  v  a2s  .  c o m
 *
 * @author xialong
 * @param alipayResult
 *            the alipay result
 * @return the map
 * @throws DocumentException
 *             the document exception
 */
private static Map<String, String> convertResultToMap(String alipayResult) throws DocumentException {
    log.info("alipayResult :\n {}", alipayResult);

    Map<String, String> map = new HashMap<String, String>();
    SAXReader reader = new SAXReader();
    Document document = reader.read(new InputSource(new StringReader(alipayResult)));
    Element root = document.getRootElement();

    String is_success = root.elementText("is_success");
    String error = root.elementText("error");
    log.info("is_success : {}", is_success);
    log.info("error : {}", error);

    map.put("is_success", is_success);
    map.put("error", error);

    return map;
}

From source file:com.feilong.framework.netpay.payment.adaptor.alipay.pconline.AlipayOnlineAdaptor.java

License:Apache License

/**
 * ?query_timestamp??? <br>//from w ww .ja v  a  2s  . c o m
 * ??XML???SSL?.
 * 
 * @return 
 */
private final String getAnti_phishing_key() {

    // query_timestamp?URL
    StringBuilder sb = new StringBuilder();
    sb.append(gateway);
    sb.append("?");
    sb.append("service=" + service_query_timestamp);
    sb.append("&");
    sb.append("partner=" + partner);

    InputStream inputStream = null;
    try {
        URL url = new URL(sb.toString());
        inputStream = url.openStream();

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);

        if (log.isDebugEnabled()) {
            log.debug("document:{}", document.toString());

            // <alipay>
            // <is_success>T</is_success>
            // <request>
            // <param name="service">query_timestamp</param>
            // <param name="partner">2088201564862550</param>
            // </request>
            // <response>
            // <timestamp>
            // <encrypt_key>KPr8DuZp5xc031OVxw==</encrypt_key>
            // </timestamp>
            // </response>
            // <sign>1fc434a9045f5681736cd47ee2faa41a</sign>
            // <sign_type>MD5</sign_type>
            // </alipay>
        }

        StringBuilder result = new StringBuilder();
        @SuppressWarnings("unchecked")
        List<Node> nodeList = document.selectNodes("//alipay/*");
        for (Node node : nodeList) {
            // ?????
            String name = node.getName();
            String text = node.getText();
            if (name.equals("is_success") && text.equals("T")) {
                // ??
                @SuppressWarnings("unchecked")
                List<Node> nodeList1 = document.selectNodes("//response/timestamp/*");
                for (Node node1 : nodeList1) {
                    result.append(node1.getText());
                }
            }
        }

        String anti_phishing_key = result.toString();

        if (log.isDebugEnabled()) {
            log.debug("anti_phishing_key value:[{}]", anti_phishing_key);
        }

        return anti_phishing_key;
    } catch (MalformedURLException e) {
        log.error(e.getClass().getName(), e);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (DocumentException e) {
        log.error(e.getClass().getName(), e);
    } finally {
        try {
            if (null != inputStream) {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    //  ?,???
    return "";
}

From source file:com.feilong.framework.netpay.payment.adaptor.alipay.wap.AlipayWapAdaptor.java

License:Apache License

/**
 * ?keyxml./*from   w  ww . jav  a 2  s.  co  m*/
 * 
 * @param xmlData
 *            the xml data
 * @param name
 *            the name
 * @return String
 * @throws DocumentException
 *             the document exception
 * @author 
 * @time 2013-9-16?10:16:39
 */
private String getValueByKeyForXML(String xmlData, String name) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(new InputSource(new StringReader(xmlData)));
    Element root = document.getRootElement();
    String value = root.elementText(name);
    return value;
}

From source file:com.feilong.tools.dom4j.Dom4jUtil.java

License:Apache License

/**
 * Gets the document.// w  w w. j  a  va  2s  .  c  o  m
 *
 * @param inputStream
 *            the input stream
 * @return the document
 * @throws Dom4jException
 *             the dom4j exception
 */
public static Document getDocument(InputStream inputStream) throws Dom4jException {
    if (null == inputStream) {
        throw new IllegalArgumentException("inputStream can't be null");
    }
    SAXReader reader = new SAXReader();
    try {
        Document document = reader.read(inputStream);
        return document;
    } catch (DocumentException e) {
        throw new Dom4jException(e);
    }
}

From source file:com.fivepebbles.Backup.java

License:MIT License

public void processBackup() {

    //Retrieve Bucket Names and related files/folders from XML saved locally

    Document myDocument = null;// w  w  w  . j a  va  2s  .c o  m

    try {
        URL myURL = new File("target", "s3files.xml").toURI().toURL();
        SAXReader myReader = new SAXReader();
        myDocument = myReader.read(myURL);
    } catch (MalformedURLException | DocumentException e) {
        //***TODO*** log Msg
        e.printStackTrace();
    }

    Element root = myDocument.getRootElement();

    for (Iterator<Element> i1 = root.elementIterator(); i1.hasNext();) {
        Element bucketelem = i1.next();

        if (bucketelem.getName() == "bucket") {
            bucketnm = bucketelem.attributeValue("name");

            for (Iterator<Element> i2 = bucketelem.elementIterator(); i2.hasNext();) {
                Element fileelem = i2.next();

                if (fileelem.getName() == "file") {
                    bfile = fileelem.getText();

                    //Get list of files (bfile could be a folder name)
                    ProcessFiles p1 = new ProcessFiles();
                    filelist = p1.getFiles(bfile);

                    //Append files to arraylist
                    if (filelist != null) {
                        totalfilelist.addAll(filelist);
                    }
                }
            }

            //Make the data good for S3
            //Replace "\" with "/" for Windows

            for (int j = 0; j < totalfilelist.size(); j++) {

                if (totalfilelist.get(j).contains("\\")) {
                    newfilelist.add(totalfilelist.get(j).replace("\\", "/"));
                } else {
                    newfilelist.add(totalfilelist.get(j));
                }
            }

            //Remove Driveletter from files/object list if present (Windows)
            for (int k = 0; k < newfilelist.size(); k++) {
                if (newfilelist.get(k).contains("C:")) {
                    newfilelist2.add(newfilelist.get(k).replace("C:", ""));
                } else {
                    newfilelist2.add(newfilelist.get(k));
                }
            }

            //Get S3 key list corresponding to the files 
            //This is obtained by removing the "/" in index 0 from the file list since AWS key should not have a / at position 0

            for (int m = 0; m < newfilelist2.size(); m++) {
                keylist.add(newfilelist2.get(m).substring(1));
            }

            //Backup files in S3 (for this bucket)

            //Get AWS Credentials
            String[] awskeys = new S3Credentials().getCredentials();

            //Set AWS credentials
            ProcessAWS pr1 = new ProcessAWS(awskeys[0], awskeys[1]);

            //Check if Bucket exists in S3
            if (pr1.checkBucket(bucketnm)) {

                //Put Objects in S3
                //keylist contains S3 keys and newfilelist2 contains the files
                for (int l = 0; l < newfilelist2.size(); l++) {
                    boolean r1 = pr1.putAWSObject(keylist.get(l), new File(newfilelist2.get(l)), bucketnm);

                    if (!r1) {
                        //***TODO*** Log message
                    }
                }
            } else {
                //Create Bucket in S3
                boolean r2 = pr1.createBucket(bucketnm);

                if (r2) {
                    //Put Objects in S3
                    //keylist contains S3 keys and newfilelist2 contains the files
                    for (int m = 0; m < newfilelist2.size(); m++) {
                        boolean r3 = pr1.putAWSObject(keylist.get(m), new File(newfilelist2.get(m)), bucketnm);

                        if (!r3) {
                            //***TODO*** Log message
                        }
                    }

                } else {
                    //***TODO*** Log message
                }
            }

        }

        //Clear arrays for the next bucket
        totalfilelist.clear();
        newfilelist.clear();
        newfilelist2.clear();
        keylist.clear();

    }

}

From source file:com.flaptor.util.DocumentParser.java

License:Apache License

public DocumentParser() {
    int processors = Runtime.getRuntime().availableProcessors();
    logger.info("constructor: found " + processors + " processors. Creating the same number of readers.");
    readers = new ArrayBlockingQueue<SAXReader>(processors);
    for (int i = 0; i < processors; i++) {
        readers.add(new SAXReader());
    }/*from w w w. j a  va  2  s.  c  om*/
}