Search in sources :

Example 36 with Document

use of org.dom4j.Document in project TeachingInSimulation by ScOrPiOzzy.

the class CompMannualBuilder method readXml.

private static List<String[]> readXml(File file) throws FileNotFoundException {
    List<String[]> listData = new ArrayList<String[]>();
    SAXReader saxReader = createNonvalidatXmlReader();
    Document document = null;
    System.out.println("CompMannualBuilder.readXml()" + file);
    try {
        document = saxReader.read(new FileInputStream(file));
    } catch (Exception e) {
        System.err.println("ParserFactory.Parser.initItem() " + e.getMessage() + "\r\n " + file);
        return listData;
    }
    Element root = document.getRootElement();
    Iterator compIter = root.elementIterator("ElecCompDef");
    while (compIter.hasNext()) {
        String[] data = new String[2];
        Element element = (Element) compIter.next();
        data[0] = element.attributeValue("model");
        data[1] = element.attributeValue("name");
        // data[2] = element.attributeValue("mdlRef");
        listData.add(data);
    }
    return listData;
}
Also used : SAXReader(org.dom4j.io.SAXReader) Element(org.dom4j.Element) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) Document(org.dom4j.Document) FileInputStream(java.io.FileInputStream) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException)

Example 37 with Document

use of org.dom4j.Document in project cubrid-manager by CUBRID.

the class FormatXMLAction method writeTo.

/**
	 * Format XML strings to a output stream.
	 *
	 * @param out OutputStream
	 * @param content the content to be formated.
	 * @param encoding String
	 * @throws DocumentException when document error raised.
	 * @throws IOException when IO errors.
	 */
public static void writeTo(OutputStream out, String content, String encoding) throws DocumentException, IOException {
    StringReader reader = new StringReader(content);
    SAXReader xmlReader = new SAXReader();
    Document doc = xmlReader.read(reader);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);
    format.setIndent(true);
    format.setIndent(" ");
    format.setIndentSize(4);
    XMLWriter writer = new XMLWriter(out, format);
    writer.write(doc);
    writer.flush();
    writer.close();
    reader.close();
}
Also used : SAXReader(org.dom4j.io.SAXReader) StringReader(java.io.StringReader) OutputFormat(org.dom4j.io.OutputFormat) Document(org.dom4j.Document) XMLWriter(org.dom4j.io.XMLWriter)

Example 38 with Document

use of org.dom4j.Document in project sic by belluccifranco.

the class AfipServiceImpl method getAfipWSAACredencial.

@Override
public AfipWSAACredencial getAfipWSAACredencial(String afipNombreServicio, Empresa empresa) {
    AfipWSAACredencial afipCredencial = new AfipWSAACredencial();
    String loginTicketResponse = "";
    byte[] p12file = configuracionDelSistemaService.getConfiguracionDelSistemaPorEmpresa(empresa).getCertificadoAfip();
    if (p12file.length == 0) {
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_cds_certificado_vacio"));
    }
    String p12signer = configuracionDelSistemaService.getConfiguracionDelSistemaPorEmpresa(empresa).getFirmanteCertificadoAfip();
    String p12pass = configuracionDelSistemaService.getConfiguracionDelSistemaPorEmpresa(empresa).getPasswordCertificadoAfip();
    //siempre devuelve por 12hs
    long ticketTime = 3600000L;
    byte[] loginTicketRequest_xml_cms = afipWebServiceSOAPClient.crearCMS(p12file, p12pass, p12signer, afipNombreServicio, ticketTime);
    LoginCms loginCms = new LoginCms();
    loginCms.setIn0(Base64.getEncoder().encodeToString(loginTicketRequest_xml_cms));
    try {
        loginTicketResponse = afipWebServiceSOAPClient.loginCMS(loginCms);
    } catch (WebServiceClientException ex) {
        LOGGER.error(ex.getMessage());
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_token_wsaa_error"));
    }
    try {
        Reader tokenReader = new StringReader(loginTicketResponse);
        Document tokenDoc = new SAXReader(false).read(tokenReader);
        afipCredencial.setToken(tokenDoc.valueOf("/loginTicketResponse/credentials/token"));
        afipCredencial.setSign(tokenDoc.valueOf("/loginTicketResponse/credentials/sign"));
        afipCredencial.setCuit(empresa.getCuip());
    } catch (DocumentException ex) {
        LOGGER.error(ex.getMessage());
        throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_error_procesando_xml"));
    }
    return afipCredencial;
}
Also used : AfipWSAACredencial(sic.modelo.AfipWSAACredencial) BusinessServiceException(sic.service.BusinessServiceException) WebServiceClientException(org.springframework.ws.client.WebServiceClientException) SAXReader(org.dom4j.io.SAXReader) DocumentException(org.dom4j.DocumentException) StringReader(java.io.StringReader) SAXReader(org.dom4j.io.SAXReader) Reader(java.io.Reader) StringReader(java.io.StringReader) LoginCms(afip.wsaa.wsdl.LoginCms) Document(org.dom4j.Document)

Example 39 with Document

use of org.dom4j.Document in project CodeUtils by boredream.

the class TempUtils method extractAllString.

public static void extractAllString() {
    List<File> files = FileUtils.getAllFiles("D:\\work\\BusinessCMT2.0");
    // List<File> files =
    // FileUtils.getAllFiles("D:\\work\\BusinessCMT2.0\\src\\com\\imohoo\\BusinessCMT\\view\\activity\\pay");
    Map<String, String> stringIdValueMap = new TreeMap<String, String>();
    for (File file : files) {
        if (file.getName().endsWith(".java") || file.getName().endsWith(".xml")) {
            FileReader fr;
            StringBuilder newFileContent = new StringBuilder();
            /**
				 * 是否是页面类
				 */
            boolean isActivity = false;
            /**
				 * 是否有替换string操作
				 */
            boolean isReplace = false;
            /**
				 * 代码行数
				 */
            int totoalLine = 0;
            /**
				 * string抽取的id后缀
				 */
            int stringIdEnd = 0;
            try {
                fr = new FileReader(file);
                BufferedReader bufferedreader = new BufferedReader(fr);
                String line;
                // 是否属于多行注释
                boolean multiLineAnno = false;
                while ((line = bufferedreader.readLine()) != null) {
                    totoalLine++;
                    // 空行
                    if (line.trim().equals("")) {
                        newFileContent.append(line + "\n");
                        continue;
                    }
                    // 单行注释,//开头
                    if (line.trim().startsWith("//")) {
                        newFileContent.append(line + "\n");
                        continue;
                    }
                    // 如果还是在多行注释中
                    if (multiLineAnno) {
                        // 如果本行包含多行注释结束符,结束
                        if (line.contains("*/")) {
                            multiLineAnno = false;
                        }
                        newFileContent.append(line + "\n");
                        continue;
                    }
                    // 多行注释开始(包括/*和/**)
                    if (line.contains("/*")) {
                        multiLineAnno = true;
                        newFileContent.append(line + "\n");
                        continue;
                    }
                    // 判断是否为页面类
                    if (line.contains("extends") && line.contains("Activity")) {
                        isActivity = true;
                    }
                    // 中文字符"blablabla"
                    String regexEmoji = "\"([\\s\\S]+?)\"";
                    Pattern pattern = Pattern.compile(regexEmoji);
                    Matcher matcher = pattern.matcher(line);
                    String regexChinese = "[一-龥]+";
                    Pattern patternChiese = Pattern.compile(regexChinese);
                    // 如果该行包含字符串"blablabla"
                    while (matcher.find()) {
                        String chinese = matcher.group(1);
                        Matcher matcherChinese = patternChiese.matcher(chinese);
                        // TODO 如果包含的内容中没有中文,跳过
                        if (!matcherChinese.find()) {
                            continue;
                        }
                        // TODO 如果是日志内容,跳过
                        if (line.trim().startsWith("Log") || line.trim().startsWith("showLog")) {
                            continue;
                        }
                        if (file.getName().endsWith(".java")) {
                            // id规则,文件名小写_递增数字
                            String stringId = FileUtils.getName(file.getName().toLowerCase(Locale.CHINA)) + "_" + stringIdEnd++;
                            if (isActivity) {
                                // 如果是页面类,直接getResource
                                line = line.replace("\"" + chinese + "\"", "getResources().getString(R.string." + stringId + ")");
                            } else {
                                // 非页面类,用application去getResource
                                line = line.replace("\"" + chinese + "\"", "BusinessCMTApplication.getInstance().getResources().getString(R.string." + stringId + ")");
                            }
                            stringIdValueMap.put(stringId, chinese);
                            isReplace = true;
                        } else if (file.getName().endsWith(".xml")) {
                            // id规则,文件名小写_递增数字
                            String stringId = FileUtils.getName(file.getName().toLowerCase(Locale.CHINA)) + "_" + stringIdEnd++;
                            // xml用@string/blabla替换,注意,不替换""
                            line = line.replace(chinese, "@string/" + stringId);
                            stringIdValueMap.put(stringId, chinese);
                            isReplace = true;
                        }
                    }
                    newFileContent.append(line + "\n");
                }
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (isReplace) {
            // TODO 写入回文件,如果有替换操作
            // FileUtils.writeString2File(newFileContent.toString(),
            // file, "UTF-8");
            }
        }
    }
    System.out.println(stringIdValueMap);
    // save to
    File file = new File("D:\\work\\BusinessCMT2.0\\res\\values\\string.xml");
    Document valuesDoc = XmlUtil.read(file);
    Element rootElement = valuesDoc.getRootElement();
    List<Element> elements = rootElement.elements();
    for (Map.Entry<String, String> entry : stringIdValueMap.entrySet()) {
        // 是否在values/xx.xml对应文件下下已有某个抽取过的值
        boolean hasElement = false;
        for (Element element : elements) {
            Attribute nameAtt = element.attribute("name");
            if (nameAtt.getValue().equals(entry.getKey())) {
                hasElement = true;
                break;
            }
        }
        if (!hasElement) {
            // <string name="app_name">Stone Chat</string>
            Element element = rootElement.addElement("string");
            element.addAttribute("name", entry.getKey());
            element.setText(entry.getValue());
        }
    }
// TODO save string文件
// XmlUtil.write2xml(file, valuesDoc);
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Attribute(org.dom4j.Attribute) Element(org.dom4j.Element) IOException(java.io.IOException) TreeMap(java.util.TreeMap) Document(org.dom4j.Document) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 40 with Document

use of org.dom4j.Document in project CodeUtils by boredream.

the class AndroidUtils method relaceLayoutViewNames.

public static void relaceLayoutViewNames(String proPath, List<String> tarList, String replacement) {
    List<File> allFiles = FileUtils.getAllFiles(proPath);
    for (File file : allFiles) {
        // 如果是xml文件,且在layout..目录下,则视为布局文件
        if (file.getName().endsWith(".xml") && file.getParentFile().getName().startsWith("layout")) {
            Document document = XmlUtil.read(file);
            boolean hasReplace = XmlUtil.replaceElementName(document, tarList, replacement);
            if (hasReplace) {
                XmlUtil.write2xml(file, document);
            }
        }
    }
}
Also used : Document(org.dom4j.Document) File(java.io.File)

Aggregations

Document (org.dom4j.Document)891 Element (org.dom4j.Element)492 SAXReader (org.dom4j.io.SAXReader)252 File (java.io.File)135 IOException (java.io.IOException)135 StringReader (java.io.StringReader)111 ArrayList (java.util.ArrayList)110 List (java.util.List)107 Test (org.junit.Test)101 DocumentException (org.dom4j.DocumentException)93 HashMap (java.util.HashMap)90 InputStream (java.io.InputStream)82 Node (org.dom4j.Node)80 Test (org.junit.jupiter.api.Test)80 XMLWriter (org.dom4j.io.XMLWriter)53 ReturnedDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument)48 FileInputStream (java.io.FileInputStream)45 Map (java.util.Map)41 ReturnedMultipartDocument (org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument)40 XMLParser (org.olat.core.util.xml.XMLParser)40