Search in sources :

Example 6 with XMLModifier

use of com.ximpleware.XMLModifier in project translationstudio8 by heartsome.

the class ImportTbx method saveTermEntryWithMerge.

private void saveTermEntryWithMerge(Map<String, String> dbTermEntry, AutoPilot langSetAp, AutoPilot termAp) throws XPathParseException, XPathEvalException, NavException, SQLException, EncodingException, EOFException, EntityException, ParseException, TranscodeException, ModifyException, IOException {
    String content = dbTermEntry.get("CONTENT");
    String termEntryPk = dbTermEntry.get("BTEPKID");
    // content修改标记
    boolean changFlag = false;
    VTDGen vg = new VTDGen();
    VTDUtils vtdUtiles = new VTDUtils();
    vg.setDoc(content.getBytes());
    vg.parse(true);
    vtdUtiles.bind(vg.getNav());
    AutoPilot _ap = new AutoPilot(vtdUtiles.getVTDNav());
    if (!content.equals(vu.getElementFragment())) {
        vu.getVTDNav().push();
        while (langSetAp.evalXPath() != -1) {
            String curlang = getElementAttribute("xml:lang");
            String tigValue = vu.getChildContent("tig");
            String ntigValue = vu.getChildContent("ntig");
            vtdUtiles.getVTDNav().push();
            _ap.selectXPath("/termEntry/langSet[@xml:lang='" + curlang + "']");
            if (_ap.evalXPath() != -1) {
                // 当语言的langSet在库中是否存在
                vu.getVTDNav().push();
                while (termAp.evalXPath() != -1) {
                    String fullText = vu.getElementContent();
                    String pureText = DocUtils.getTmxTbxPureText(vu);
                    vtdUtiles.getVTDNav().push();
                    _ap.selectXPath("./tig[term='" + fullText + "']|./ntig/termGrp[term='" + fullText + "']");
                    if (_ap.evalXPath() == -1) {
                        XMLModifier xm = null;
                        if (tigValue != null) {
                            xm = vtdUtiles.insert("/termEntry/langSet[@xml:lang='" + curlang + "']/tig", "<tig>" + tigValue + "</tig>");
                        } else if (ntigValue != null) {
                            xm = vtdUtiles.insert("/termEntry/langSet[@xml:lang='" + curlang + "']/tig", "<ntig>" + ntigValue + "</ntig>");
                        }
                        vtdUtiles.bind(xm.outputAndReparse());
                        // 当pureText为空字符串时,HASH字段留空
                        String hash = null;
                        if (pureText != null) {
                            hash = "" + pureText.hashCode();
                        }
                        dbOperator.insertTextData("B", Integer.parseInt(termEntryPk), hash, pureText, fullText, Utils.convertLangCode(curlang), null, null);
                        changFlag = true;
                    }
                    _ap.resetXPath();
                    vtdUtiles.getVTDNav().pop();
                }
                termAp.resetXPath();
                //
                vu.getVTDNav().pop();
            } else {
                // 库中不存在该种语言的langSet,则新增
                XMLModifier xm = vtdUtiles.insert("/termEntry/langSet", vu.getElementFragment());
                vtdUtiles.bind(xm.outputAndReparse());
                changFlag = true;
                vu.getVTDNav().push();
                if (termAp.evalXPath() != -1) {
                    String fullText = vu.getElementContent();
                    String pureText = DocUtils.getTmxTbxPureText(vu);
                    // 当pureText为空字符串时,HASH字段留空
                    String hash = null;
                    if (pureText != null) {
                        hash = "" + pureText.hashCode();
                    }
                    dbOperator.insertTextData("B", Integer.parseInt(termEntryPk), hash, pureText, fullText, Utils.convertLangCode(curlang), null, null);
                }
                termAp.resetXPath();
                vu.getVTDNav().pop();
            }
            vtdUtiles.getVTDNav().pop();
        }
        langSetAp.resetXPath();
        vu.getVTDNav().pop();
        // 处理note
        List<String> existDbNoteId = new ArrayList<String>();
        List<String> existDbNotePk = new ArrayList<String>();
        // 用于记录已经处理的noteId,过滤掉文件重复的内容
        List<String> noteIdRm = new ArrayList<String>();
        StringBuffer noteContentBf = new StringBuffer();
        AutoPilot noteAp = new AutoPilot(vu.getVTDNav());
        vu.getVTDNav().push();
        noteAp.selectXPath("./note");
        while (noteAp.evalXPath() != -1) {
            String noteId = vu.getCurrentElementAttribut("id", "");
            String noteContent = vu.getElementContent();
            if (noteId.equals("") || noteContent == null || noteContent.equals("")) {
                continue;
            }
            String[] ids = noteId.split(",");
            if (ids.length != 2) {
                continue;
            }
            String reNoteId = ids[1] + "," + ids[0];
            if (noteIdRm.contains(noteId) || noteIdRm.contains(reNoteId)) {
                // 重复不重复写入
                continue;
            }
            // 记录已经处理的note
            noteIdRm.add(noteId);
            AutoPilot dbNoteAp = new AutoPilot(vtdUtiles.getVTDNav());
            dbNoteAp.selectXPath("/termEntry/note[@id='" + noteId + "' or @id='" + reNoteId + "']");
            while (dbNoteAp.evalXPath() != -1) {
                String dbNoteId = vtdUtiles.getCurrentElementAttribut("id", "");
                if (!existDbNoteId.contains(dbNoteId)) {
                    existDbNoteId.add(dbNoteId);
                }
                List<Map<String, String>> result = dbOperator.getBNodeByParent(termEntryPk, "termEntry", "E", "note", dbNoteId);
                for (Map<String, String> map : result) {
                    existDbNotePk.add(map.get("NPKID"));
                }
            }
            dbOperator.insertBNode(Integer.parseInt(termEntryPk), "termEntry", "E", "note", noteId, noteContent);
            noteContentBf.append(vu.getElementFragment());
        }
        vu.getVTDNav().pop();
        if (existDbNotePk.size() > 0) {
            dbOperator.deleteBNode(existDbNotePk);
        }
        StringBuffer xpathWhere = new StringBuffer();
        for (String dbNodeId : existDbNoteId) {
            xpathWhere.append("@id='" + dbNodeId + "' or ");
        }
        if (xpathWhere.length() > 0) {
            String xpath = xpathWhere.substring(0, xpathWhere.lastIndexOf("or"));
            // 清除文件中的note
            XMLModifier xm = vtdUtiles.delete("/termEntry/note[" + xpath + "]", VTDUtils.PILOT_TO_END);
            vtdUtiles.bind(xm.outputAndReparse());
            changFlag = true;
        }
        if (noteContentBf.length() != 0) {
            XMLModifier xm = vtdUtiles.insert("/termEntry/text()", noteContentBf.toString());
            vtdUtiles.bind(xm.outputAndReparse());
            changFlag = true;
        }
        if (changFlag) {
            dbOperator.updateTermEntry(vtdUtiles.getElementFragment(), termEntryPk);
        }
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) ArrayList(java.util.ArrayList) VTDGen(com.ximpleware.VTDGen) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with XMLModifier

use of com.ximpleware.XMLModifier in project translationstudio8 by heartsome.

the class ExportTbxImpl method filterLangSet.

/**
	 * 过滤从库中导出的langSet节点<br>
	 * 在库中TremEntry是以整个节点进行存储的,因此,在导出后也是整个节点导出,所以会将无关的语言也导出来。<br>
	 * 在导出后,生成的TBX文件中进语言进行过滤
	 * @param filePath
	 *            导出后生成的TBX文件路径
	 * @param srcLang
	 *            源语言
	 * @param needLang
	 *            当前需要导出的语言;
	 */
private void filterLangSet(String filePath, String srcLang, List<String> needLang) {
    try {
        VTDGen vg = new VTDGen();
        if (vg.parseFile(filePath, true)) {
            VTDUtils vu = new VTDUtils(vg.getNav());
            StringBuffer xpath = new StringBuffer("/martif/text/body/termEntry/langSet[");
            String noteXpathtemp = "starts-with(@id,'__LANG__,') or ends-with(@id,',__LANG__')";
            StringBuffer noteTgtXpath = new StringBuffer();
            for (String lang : needLang) {
                xpath.append("not(@xml:lang='" + lang + "') and ");
                if (!lang.equals(srcLang)) {
                    noteTgtXpath.append(noteXpathtemp.replace("__LANG__", lang)).append(" or ");
                }
            }
            String tgtLangXpath = noteTgtXpath.substring(0, noteTgtXpath.lastIndexOf("or"));
            StringBuffer noteXpath = new StringBuffer();
            noteXpath.append("/martif/text/body/termEntry/note[");
            noteXpath.append("not(");
            noteXpath.append("(").append(noteXpathtemp.replace("__LANG__", srcLang)).append(")");
            noteXpath.append(" and ");
            noteXpath.append("(").append(tgtLangXpath).append(")");
            noteXpath.append(")");
            noteXpath.append("]");
            String xpathStr = xpath.substring(0, xpath.lastIndexOf("and")) + "]";
            XMLModifier xm = new XMLModifier(vu.getVTDNav());
            AutoPilot ap = new AutoPilot(vu.getVTDNav());
            ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
            xm = vu.delete(ap, xm, xpathStr, VTDUtils.PILOT_TO_END);
            xm = vu.delete(ap, xm, noteXpath.toString(), VTDUtils.PILOT_TO_END);
            FileOutputStream fos = new FileOutputStream(filePath);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            // 写入文件
            xm.output(bos);
            bos.close();
            fos.close();
        }
    } catch (NavException e) {
        logger.error("", e);
        e.printStackTrace();
    } catch (ModifyException e) {
        logger.error("", e);
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        logger.error("", e);
        e.printStackTrace();
    } catch (TranscodeException e) {
        logger.error("", e);
        e.printStackTrace();
    } catch (IOException e) {
        logger.error("", e);
        e.printStackTrace();
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) NavException(com.ximpleware.NavException) FileNotFoundException(java.io.FileNotFoundException) VTDGen(com.ximpleware.VTDGen) IOException(java.io.IOException) TranscodeException(com.ximpleware.TranscodeException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) FileOutputStream(java.io.FileOutputStream) ModifyException(com.ximpleware.ModifyException) BufferedOutputStream(java.io.BufferedOutputStream)

Example 8 with XMLModifier

use of com.ximpleware.XMLModifier in project translationstudio8 by heartsome.

the class PartOperate method loadFile.

/**
	 * 解析文件
	 * @param nameSpaceMap	要申明的命名空间
	 * @throws Exception
	 */
protected void loadFile(Map<String, String> nameSpaceMap) throws Exception {
    VTDGen vg = new VTDGen();
    if (vg.parseFile(partPath, true)) {
        vn = vg.getNav();
        ap = new AutoPilot(vn);
        otherAP = new AutoPilot(vn);
        childAP = new AutoPilot(vn);
        extendAP = new AutoPilot(vn);
        vu = new VTDUtils(vn);
        xm = new XMLModifier(vn);
        // 给 ap 申明命名空间
        for (Entry<String, String> entry : nameSpaceMap.entrySet()) {
            ap.declareXPathNameSpace(entry.getKey(), entry.getValue());
            childAP.declareXPathNameSpace(entry.getKey(), entry.getValue());
            otherAP.declareXPathNameSpace(entry.getKey(), entry.getValue());
            extendAP.declareXPathNameSpace(entry.getKey(), entry.getValue());
        }
    } else {
        throw new DocxConverterException(MessageFormat.format(Messages.getString("docxConvert.msg2"), partPath));
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) DocxConverterException(net.heartsome.cat.converter.word2007.common.DocxConverterException) AutoPilot(com.ximpleware.AutoPilot) VTDGen(com.ximpleware.VTDGen)

Example 9 with XMLModifier

use of com.ximpleware.XMLModifier in project translationstudio8 by heartsome.

the class XliffInputer method restoreGTag.

private void restoreGTag(String interTagPath) throws Exception {
    if (!new File(interTagPath).exists()) {
        return;
    }
    // 先解析 interTag.xml
    VTDGen vg = new VTDGen();
    if (!vg.parseFile(interTagPath, true)) {
        throw new Exception();
    }
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    VTDUtils vu = new VTDUtils(vn);
    String xpath = "/docxTags/tag";
    ap.selectXPath(xpath);
    Map<String, String> tagMap = new HashMap<String, String>();
    String tuId = null;
    int index = -1;
    while (ap.evalXPath() != -1) {
        tuId = null;
        if ((index = vn.getAttrVal("tuId")) != -1) {
            tuId = vn.toString(index);
        }
        if (tuId == null) {
            continue;
        }
        String content = vu.getElementContent().replace("</g>", "");
        if (content.indexOf("<g") != 0) {
            continue;
        }
        tagMap.put(tuId, content);
    }
    // 再将结果传至 xliff 文件
    vg = new VTDGen();
    if (!vg.parseFile(xliffFile, true)) {
        throw new Exception();
    }
    vn = vg.getNav();
    vu.bind(vn);
    ap.bind(vn);
    XMLModifier xm = new XMLModifier(vn);
    for (Entry<String, String> entry : tagMap.entrySet()) {
        String thisTuId = entry.getKey();
        String tagContent = entry.getValue();
        // docx 转换器里面是没有 多个file节点 的情况
        // 先处理源文
        xpath = "/xliff/file/body//trans-unit[@id='" + thisTuId + "']/source";
        ap.selectXPath(xpath);
        if (ap.evalXPath() != -1) {
            String srcHeader = vu.getElementHead();
            String oldContent = vu.getElementContent();
            xm.remove();
            StringBuffer newFragSB = new StringBuffer();
            newFragSB.append(srcHeader);
            newFragSB.append(tagContent);
            newFragSB.append(oldContent);
            newFragSB.append("</g></source>");
            xm.insertAfterElement(newFragSB.toString());
        }
        // 处理译文
        xpath = "/xliff/file/body//trans-unit[@id='" + thisTuId + "']/target";
        ap.selectXPath(xpath);
        if (ap.evalXPath() != -1) {
            String srcHeader = vu.getElementHead();
            String oldContent = vu.getElementContent();
            xm.remove();
            StringBuffer newFragSB = new StringBuffer();
            newFragSB.append(srcHeader);
            newFragSB.append(tagContent);
            newFragSB.append(oldContent);
            newFragSB.append("</g></target>");
            xm.insertAfterElement(newFragSB.toString());
        }
    }
    xm.output(xliffFile);
    // 删除 interTag.xml
    File interTagFile = new File(interTagPath);
    interTagFile.delete();
}
Also used : XMLModifier(com.ximpleware.XMLModifier) HashMap(java.util.HashMap) VTDGen(com.ximpleware.VTDGen) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) File(java.io.File) VTDNav(com.ximpleware.VTDNav)

Example 10 with XMLModifier

use of com.ximpleware.XMLModifier in project translationstudio8 by heartsome.

the class Application method deleteErrorMemoryInfo.

/**
	 * 删除错误记录文件,以修改产品第一次运行后,存储错误信息导致第二次打不开的情况	robert	2013-05-15
	 */
private static void deleteErrorMemoryInfo() {
    // 只针对 mac 下的用户
    if (System.getProperty("os.name").indexOf("Mac") == -1) {
        return;
    }
    String workbenchXmlPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(".metadata/.plugins/org.eclipse.ui.workbench/workbench.xml").toOSString();
    VTDGen vg = new VTDGen();
    boolean result = vg.parseFile(workbenchXmlPath, true);
    if (!result) {
        new File(workbenchXmlPath).delete();
        return;
    }
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    FileOutputStream stream = null;
    try {
        XMLModifier xm = new XMLModifier(vn);
        // 删除节点 editor
        ap.selectXPath("/workbench/window/page/editors/editor");
        while (ap.evalXPath() != -1) {
            xm.remove();
        }
        // 删除其他记录
        ap.selectXPath("/workbench/window/page/navigationHistory");
        if (ap.evalXPath() != -1) {
            xm.remove();
        }
        xm.output(workbenchXmlPath);
    } catch (Exception e) {
    // do nothing
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e2) {
            }
        }
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) AutoPilot(com.ximpleware.AutoPilot) FileOutputStream(java.io.FileOutputStream) VTDGen(com.ximpleware.VTDGen) File(java.io.File) VTDNav(com.ximpleware.VTDNav)

Aggregations

XMLModifier (com.ximpleware.XMLModifier)80 NavException (com.ximpleware.NavException)54 VTDNav (com.ximpleware.VTDNav)53 AutoPilot (com.ximpleware.AutoPilot)50 ModifyException (com.ximpleware.ModifyException)50 XPathParseException (com.ximpleware.XPathParseException)42 VTDUtils (net.heartsome.xml.vtdimpl.VTDUtils)41 XPathEvalException (com.ximpleware.XPathEvalException)40 IOException (java.io.IOException)38 TranscodeException (com.ximpleware.TranscodeException)34 VTDGen (com.ximpleware.VTDGen)23 UnsupportedEncodingException (java.io.UnsupportedEncodingException)22 CoreException (org.eclipse.core.runtime.CoreException)17 FileNotFoundException (java.io.FileNotFoundException)15 FileOutputStream (java.io.FileOutputStream)15 ParseException (com.ximpleware.ParseException)13 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)13 ArrayList (java.util.ArrayList)12 File (java.io.File)11 XQException (javax.xml.xquery.XQException)11