Example usage for org.dom4j Node setText

List of usage examples for org.dom4j Node setText

Introduction

In this page you can find the example usage for org.dom4j Node setText.

Prototype

void setText(String text);

Source Link

Document

Sets the text data of this node or this method will throw an UnsupportedOperationException if it is read-only.

Usage

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

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("SHOP++?????");
    }//from   w  w w . jav a2s . c o 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.kee.engine.common.SystemInitServlet.java

/**
 *
 *//*from w  w  w . j  a v  a  2s  . c o  m*/
private void changeReportConfig(PropertiesFactory pf) {
    File config_file = new File(getClassPath(), "reportConfig.xml");
    Document doc = readerDom(config_file);
    Element root = doc.getRootElement();
    //home
    Node oCfg = root.selectSingleNode("config[name='reportFileHome']/value");
    if (pf.getParam("reportFileHome") != null) {
        oCfg.setText(pf.getParam("reportFileHome"));
        File file = new File(pf.getParam("reportFileHome"));
        if (!file.exists()) {
            file.mkdirs();
        }
    }
    //license
    Node license = root.selectSingleNode("config[name='license']/value");
    if (pf.getParam("license") != null) {
        license.setText(pf.getParam("license"));
    }
    writeConfig(doc.asXML(), config_file);
}

From source file:com.beetle.framework.util.file.XMLReader.java

License:Apache License

public static void setTagContent(String xmlFileName, String TagPath, String value) {
    synchronized (writeLock) {
        SAXReader reader = new SAXReader();
        XMLWriter writer = null;/*w ww  . j  a v  a2 s.co m*/
        try {
            Document doc = reader.read(new File(xmlFileName));
            Node node = doc.selectSingleNode(convertPath(TagPath));
            if (node != null) {
                node.setText(value);
            }
            writer = new XMLWriter(new FileWriter(xmlFileName));
            writer.write(doc);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reader = null;
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

From source file:com.cladonia.xngreditor.actions.ToolsStripTextAction.java

License:Open Source License

private void treeWalk(XElement element, boolean stripElements, boolean stripAttributes,
        boolean stripMixedContent, boolean traverseChildren) throws Exception {

    for (int i = 0, size = element.nodeCount(); i < size; i++) {
        Node node = element.node(i);
        if ((node instanceof Element) && (traverseChildren)) {
            //remove the attributes first
            XElement e = (XElement) node;
            if (stripAttributes) {
                if (e.attributeCount() > 0) {
                    int attCount = e.attributeCount();
                    for (int cnt = 0; cnt < attCount; ++cnt) {
                        Attribute att = e.attribute(cnt);
                        att.setText("");
                    }//from ww w  . j a  v  a  2s. c  om
                }
            }
            //check if it is mixed
            if ((stripMixedContent) && (isMixed((XElement) node))) {
                e.removeAllChildren();
            } else {
                treeWalk(e, stripElements, stripAttributes, stripMixedContent, traverseChildren);
            }
        } else if ((stripElements) && (node instanceof Text)) {
            //these are all text nodes
            // blank but need to preserve formatting
            String value = node.getText();
            //if it does not contain a new line char then can blank
            // straight away
            if (value.indexOf("\n") == -1) {
                node.setText("");
            } else {
                //id does contain a newline
                if (value.charAt(0) == '\n') {
                    //if the first char is new line
                    //the new value should have all the spaces, \n and \t
                    // but no letters or digits
                    String newValue = "";
                    for (int cnt = 0; cnt < value.length(); ++cnt) {
                        //look for the first occurence of a real character
                        if (Character.isLetterOrDigit(value.charAt(cnt))) {
                            //cnt = value.length();
                        } else if ((value.charAt(cnt) == '\n') || (value.charAt(cnt) == '\t')
                                || (value.charAt(cnt) == ' ')) {
                            newValue += value.charAt(cnt);
                        }
                    }
                    node.setText(newValue);
                } else {
                    String newValue = "";
                    for (int cnt = 0; cnt < value.length(); ++cnt) {
                        //look for the first occurence of a real character
                        if (Character.isLetterOrDigit(value.charAt(cnt))) {
                            //cnt = value.length();
                        } else if ((value.charAt(cnt) == '\n') || (value.charAt(cnt) == '\t')
                                || (value.charAt(cnt) == ' ')) {
                            newValue += value.charAt(cnt);
                        }
                    }
                    node.setText(newValue);
                }
            }
        }
    }
}

From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementTextOnlyParser.java

License:Open Source License

public List<Element> replace(Element element, ParameterPool variables) throws Exception {
    List<Element> result = new LinkedList();
    result.add(element.createCopy());/*from  www. j  a  v a2  s  .c  o m*/
    element = result.get(0);

    Iterator nodesIterator = element.nodeIterator();
    HashMap<Node, Node> nodesToReplace = new HashMap<Node, Node>();

    boolean alreadyNext = false;

    while (nodesIterator.hasNext()) {
        Node node = null;
        if (!alreadyNext) {
            node = (Node) nodesIterator.next();
        }

        Node lastTextNode = null;
        String lastTextNodeText = "";
        alreadyNext = false;

        //
        // We put all successive TEXT Nodes into one node ( there is some fragmentation i don't understand )
        //
        while (null != node && node.getNodeType() == Node.TEXT_NODE) {
            alreadyNext = true;
            lastTextNode = (Text) node;
            lastTextNodeText += lastTextNode.getText();

            // this node will be deleted later ... if not overwritten in this hashmap
            nodesToReplace.put(lastTextNode, null);
            if (nodesIterator.hasNext()) {
                node = (Node) nodesIterator.next();
            } else {
                node = null;
            }
        }

        //
        // We process normally the CDATA Nodes
        // 
        if (null != node && node.getNodeType() == Node.CDATA_SECTION_NODE) {
            lastTextNode = (Node) node;
            lastTextNodeText = lastTextNode.getText();
        }

        //
        // We do nothing for the other type Nodes
        // 
        if (null == lastTextNode) {
            continue;
        }

        lastTextNode.setText(lastTextNodeText);

        //
        // Now that we have only one, complete, TEXT node or one CDATA node to proceed
        //
        Node textNode = (Node) lastTextNode;

        String text = textNode.getText();
        String out = "";

        int endOfLine;
        String line;

        //
        // Transform all \r\n, in \n
        //
        //text = Utils.replaceNoRegex(text, "\r", "");

        while (text.length() > 0) {
            //
            // Read a line
            //
            endOfLine = text.indexOf("\n");

            if (endOfLine == -1) {
                line = text;
                text = "";
            } else {
                line = text.substring(0, endOfLine + 1);
                text = text.substring(endOfLine + 1);
            }

            //
            // Replace line if it contains at least a variable
            //
            if (Parameter.containsParameter(line)) {
                List<String> results = variables.parse(line);

                for (String s : results) {
                    out += s;
                }
            } else {
                out += line;
            }
        }

        //
        // Set new text into new AVP
        //
        Text newTextNode = new DefaultText(out);
        nodesToReplace.put(textNode, newTextNode);
    }

    for (Node key : nodesToReplace.keySet()) {
        DefaultElementInterface.replaceNode((DefaultElement) element, key, nodesToReplace.get(key));
    }

    if (result.size() != 1) {
        throw new ExecutionException("Size of result for XMLElementTextOnlyParser should be 1");
    }

    return result;
}

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

public String save() throws URISyntaxException, IOException, DocumentException {
    if (isInstalled()) {
        return ajaxJsonErrorMessage("CAIJINGLING?????");
    }/*from   w w w  .j  av  a  2  s  . c  o 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 {
        // ?
        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.google.gdt.handler.impl.ExcelxHandler.java

License:Open Source License

/**
 * //from   w  ww. j  a v  a 2s  . c  o m
 * @param inputFile
 * @throws IOException
 * @throws InvalidFormatException
 */
@Override
public void handle(String inputFile, ProgressLevel pLevel) throws IOException, InvalidFormatException {
    String outPutFile = getOuputFileName(inputFile);
    ZipInputStream zis = new ZipInputStream(new FileInputStream(inputFile));
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outPutFile));
    ZipEntry zipEntry;
    int wordCount = 0;
    int pBarUpdate = 0;
    while ((zipEntry = zis.getNextEntry()) != null) {
        if (zipEntry.getName().equals("xl/sharedStrings.xml")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[BUFFER];
            int len;
            while ((len = zis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }
            baos.flush();

            InputStream clone = new ByteArrayInputStream(baos.toByteArray());
            SAXReader saxReader = new SAXReader();
            Document doc = null;
            Map<String, String> nameSpaceMap = new HashMap<String, String>();
            nameSpaceMap.put("xmlns", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
            try {
                XPath xPath = new Dom4jXPath("//xmlns:t");
                xPath.setNamespaceContext(new SimpleNamespaceContext(nameSpaceMap));
                doc = saxReader.read(clone);
                List<Node> nodes = xPath.selectNodes(doc);
                wordCount = nodes.size();
                pLevel.setValue(0);
                pLevel.setMaxValue(wordCount);
                pLevel.setStringPainted(true);
                pLevel.setTrFileName(outPutFile);
                pBarUpdate = 0;
                for (Node node : nodes) {
                    pBarUpdate++;
                    pLevel.setValue(pBarUpdate);
                    if (isInterrupted) {
                        zis.close();
                        zout.close();
                        new File(outPutFile).delete();
                        pLevel.setString("cancelled");
                        return;
                    }
                    String inputText = "";
                    try {
                        inputText = node.getText();
                        String translatedTxt = inputText;
                        translatedTxt = translator.translate(inputText);
                        node.setText(translatedTxt);
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Translation fails for the inputText : " + inputText, e);
                    }
                }
            } catch (DocumentException e) {
                logger.log(Level.SEVERE, "cannot parse slide", e);
            } catch (JaxenException e) {
                e.printStackTrace();
            }

            zout.putNextEntry(new ZipEntry(zipEntry.getName()));
            byte data[] = doc.asXML().getBytes("UTF8");
            zout.write(data, 0, data.length);
        } else {
            zout.putNextEntry(new ZipEntry(zipEntry.getName()));
            int len;
            byte data[] = new byte[BUFFER];
            while ((len = zis.read(data, 0, BUFFER)) != -1) {
                zout.write(data, 0, len);
            }
        }
    }
    zis.close();
    zout.close();
    pLevel.setValue(wordCount);
    pLevel.setString("done");
}

From source file:com.google.gdt.handler.impl.PowerpointxHandler.java

License:Open Source License

/**
 * //from  ww w. j a va 2s.  c om
 * @param inputFile
 * @param pLevel
 * @throws IOException
 * @throws InvalidFormatException
 */
@Override
public void handle(String inputFile, ProgressLevel pLevel) throws IOException, InvalidFormatException {
    String outPutFile = getOuputFileName(inputFile);
    ZipInputStream zis = new ZipInputStream(new FileInputStream(inputFile));
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outPutFile));

    int slideCount = getSlideCount(inputFile);
    pLevel.setValue(0);
    pLevel.setMaxValue(slideCount);
    pLevel.setStringPainted(true);
    pLevel.setTrFileName(outPutFile);
    ZipEntry zipEntry;
    int pBarUpdate = 0;
    while ((zipEntry = zis.getNextEntry()) != null) {
        if (zipEntry.getName().contains("ppt/slides/slide")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[BUFFER];
            int len;
            while ((len = zis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }
            baos.flush();

            InputStream clone = new ByteArrayInputStream(baos.toByteArray());
            SAXReader saxReader = new SAXReader();
            Document doc = null;
            try {
                doc = saxReader.read(clone);
                List<Node> nodes = doc.selectNodes("//a:t");
                for (Node node : nodes) {
                    if (isInterrupted) {
                        zis.close();
                        zout.close();
                        new File(outPutFile).delete();
                        pLevel.setString("cancelled");
                        return;
                    }
                    String inputText = "";
                    try {
                        inputText = node.getText();
                        if ((null == inputText) || (inputText.trim().equals("")))
                            continue;
                        String translatedText = translator.translate(inputText);
                        node.setText(translatedText);
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Translation fails for the inputText : " + inputText, e);
                    }
                }
            } catch (DocumentException e) {
                logger.log(Level.SEVERE, "cannot parse slide", e);
            }

            zout.putNextEntry(new ZipEntry(zipEntry.getName()));
            byte data[] = doc.asXML().getBytes("UTF8");
            zout.write(data, 0, data.length);
            pBarUpdate++;
            pLevel.setValue(pBarUpdate);
        } else {
            zout.putNextEntry(new ZipEntry(zipEntry.getName()));
            int len;
            byte data[] = new byte[BUFFER];
            while ((len = zis.read(data, 0, BUFFER)) != -1) {
                zout.write(data, 0, len);
            }
        }
    }
    zis.close();
    zout.close();
    pLevel.setValue(slideCount);
    pLevel.setString("done");
}

From source file:com.google.gdt.handler.impl.WordxHandler.java

License:Open Source License

/**
 * /*from  ww  w  .j  ava2 s.c  o m*/
 * @param inputFile
 * @param pLevel
 * @throws IOException
 * @throws InvalidFormatException
 */
@Override
public void handle(String inputFile, ProgressLevel pLevel) throws IOException, InvalidFormatException {
    String outPutFile = getOuputFileName(inputFile);
    ZipInputStream zis = new ZipInputStream(new FileInputStream(inputFile));
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outPutFile));
    ZipEntry zipEntry;
    int wordCount = 0;
    int pBarUpdate = 0;
    while ((zipEntry = zis.getNextEntry()) != null) {
        if (zipEntry.getName().equals("word/document.xml")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[BUFFER];
            int len;
            while ((len = zis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }
            baos.flush();

            InputStream clone = new ByteArrayInputStream(baos.toByteArray());
            SAXReader saxReader = new SAXReader();
            Document doc = null;
            try {
                doc = saxReader.read(clone);
                List<Node> nodes = doc.selectNodes("//w:t");
                wordCount = nodes.size();
                pLevel.setValue(0);
                pLevel.setMaxValue(wordCount);
                pLevel.setStringPainted(true);
                pLevel.setTrFileName(outPutFile);
                pBarUpdate = 0;
                for (Node node : nodes) {
                    if (isInterrupted) {
                        zis.close();
                        zout.close();
                        new File(outPutFile).delete();
                        pLevel.setString("cancelled");
                        return;
                    }
                    String inputText = "";
                    try {
                        inputText = node.getText();
                        pBarUpdate++;
                        pLevel.setValue(pBarUpdate);
                        if ((null == inputText) || (inputText.trim().equals("")))
                            continue;
                        String translatedText = translator.translate(inputText);
                        node.setText(translatedText);
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Translation fails for the inputText : " + inputText, e);
                    }
                }
            } catch (DocumentException e) {
                logger.log(Level.SEVERE, "cannot parse slide", e);
            }

            zout.putNextEntry(new ZipEntry(zipEntry.getName()));
            byte data[] = doc.asXML().getBytes("UTF8");
            zout.write(data, 0, data.length);
        } else {
            zout.putNextEntry(new ZipEntry(zipEntry.getName()));
            int len;
            byte data[] = new byte[BUFFER];
            while ((len = zis.read(data, 0, BUFFER)) != -1) {
                zout.write(data, 0, len);
            }
        }
    }
    zis.close();
    zout.close();
    pLevel.setValue(wordCount);
    pLevel.setString("done");
}

From source file:com.lafengmaker.tool.util.XMLDataUtil.java

License:Open Source License

public static boolean setDataByPattern(Node node, String value, String pattern) {
    if (node != null) {
        Node desNode = node.selectSingleNode(pattern);
        if (desNode != null) {
            desNode.setText(value);
            return true;
        } else {/* w ww. java 2 s  .  c  o  m*/
            return false;
        }
    } else {
        return false;
    }
}