Search in sources :

Example 21 with NavException

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

the class XLFHandler method resetTuNodes.

/**
	 * 重置 TU 子节点的 XML 内容。
	 * @param subNodesOfTU
	 *            TU 子节点的 XML 内容
	 */
public void resetTuNodes(Map<String, String> subNodesOfTU) {
    if (subNodesOfTU == null || subNodesOfTU.size() == 0) {
        return;
    }
    List<String> rowIdList = new ArrayList<String>(subNodesOfTU.keySet());
    Map<String, List<String>> map = RowIdUtil.groupRowIdByFileName(rowIdList);
    AutoPilot ap = new AutoPilot();
    ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
    ap.declareXPathNameSpace(hsNSPrefix, hsR7NSUrl);
    XMLModifier xm = new XMLModifier();
    VTDUtils vu = new VTDUtils();
    for (Entry<String, List<String>> entry : map.entrySet()) {
        String fileName = entry.getKey();
        List<String> rowIds = entry.getValue();
        VTDNav vn = vnMap.get(fileName);
        try {
            ap.bind(vn);
            xm.bind(vn);
            vu.bind(vn);
            for (String rowId : rowIds) {
                String tgtNode = subNodesOfTU.get(rowId);
                String xpath = RowIdUtil.parseRowIdToXPath(rowId);
                xm = vu.update(ap, xm, xpath, tgtNode);
            }
            // 保存并更新 VTDNav
            saveAndReparse(xm, fileName);
        } catch (ModifyException e) {
            LOGGER.error("", e);
            e.printStackTrace();
        } catch (NavException e) {
            LOGGER.error("", e);
            e.printStackTrace();
        }
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) ArrayList(java.util.ArrayList) NavException(com.ximpleware.NavException) ModifyException(com.ximpleware.ModifyException) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) VTDNav(com.ximpleware.VTDNav)

Example 22 with NavException

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

the class XLFHandler method generateTMXToUpdateTM.

/**
	 * 更新记忆库
	 * @param file
	 *            xliff 文件
	 * @param srcLang
	 *            源语言,当添加所有语言时,值为 null
	 * @param tgtLang
	 *            目标语言,当添加所有语言时,值为 null
	 * @param isAddApprove
	 *            是否添加已批准文本段到记忆库
	 * @param isAddSignedOff
	 *            是否添加已签发文本段到记忆库
	 * @param isAddTranslate
	 *            是否添加已翻译文本段到记忆库
	 * @param isAddDraft
	 *            是否添加草稿状态文本段到记忆库
	 * @param isTagAddTM
	 *            是否将标记为不添加到记忆库的文本段添加到记忆库
	 * @param isAddNoState
	 *            是否添加无状态文本段到记忆库(未实现)
	 * @return 每个数组中第一个元素表示源语言,第二个元素为生成的 TMX 字符串
	 */
public String[] generateTMXToUpdateTM(IFile file, boolean isAddApprove, boolean isAddSignedOff, boolean isAddTranslate, boolean isAddDraft, boolean isAddLocked, int contextSize, String systemUser) {
    if (file == null) {
        return null;
    }
    String filePath = ResourceUtils.iFileToOSPath(file);
    VTDNav vn = vnMap.get(filePath);
    // 当文件未打开时,要先解析 xliff 文件
    if (vn == null) {
        VTDGen vg = new VTDGen();
        String path = ResourceUtils.iFileToOSPath(file);
        if (vg.parseFile(path, true)) {
            vn = vg.getNav();
        }
    }
    StringBuffer sbTMX = new StringBuffer();
    String srcLang = null;
    // if (srcLang == null || tgtLang == null) {
    AutoPilot ap = new AutoPilot(vn);
    ap.declareXPathNameSpace(hsNSPrefix, hsR7NSUrl);
    String srcLanguage;
    String tgtLanguage;
    String original;
    String strTMX;
    try {
        VTDUtils vu = new VTDUtils(vn);
        vn.push();
        ap.selectXPath("/xliff//file");
        AutoPilot ap2 = new AutoPilot(vn);
        ap2.declareXPathNameSpace(hsNSPrefix, hsR7NSUrl);
        // sbTMX 是否添加了头部信息
        boolean isContainHeader = false;
        while (ap.evalXPath() != -1) {
            vn.push();
            srcLanguage = vu.getCurrentElementAttribut("source-language", null);
            srcLang = srcLanguage;
            tgtLanguage = vu.getCurrentElementAttribut("target-language", null);
            original = vu.getCurrentElementAttribut("original", null);
            if (srcLanguage == null) {
                continue;
            }
            if (tgtLanguage == null) {
                continue;
            }
            vn.pop();
            strTMX = generateTMXString(systemUser, filePath, srcLanguage, tgtLanguage, original, vn, isAddApprove, isAddSignedOff, isAddTranslate, isAddDraft, isAddLocked, contextSize, file.getProject());
            if (strTMX != null) {
                if (!isContainHeader) {
                    isContainHeader = true;
                    sbTMX.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                    sbTMX.append("<tmx version=\"1.4b\">");
                    sbTMX.append("<header creationtool=\"" + Constants.TMX_CREATIONTOOL + "\" creationtoolversion=\"" + Constants.TMX_CREATIONTOOLVERSION + "\" srclang=\"" + srcLanguage + "\" adminlang=\"en\" datatype=\"xml\" o-tmf=\"XLIFF\" segtype=\"paragraph\">");
                    sbTMX.append("</header>");
                    sbTMX.append("<body>");
                }
                sbTMX.append(strTMX);
            }
        }
        if (sbTMX.length() > 0) {
            sbTMX.append("</body>");
            sbTMX.append("</tmx>");
        } else {
            return null;
        }
    } catch (XPathParseException e) {
        LOGGER.error(MessageFormat.format(Messages.getString("file.XLFHandler.logger17"), filePath), e);
    } catch (XPathEvalException e) {
        LOGGER.error(MessageFormat.format(Messages.getString("file.XLFHandler.logger17"), filePath), e);
    } catch (NavException e) {
        LOGGER.error(MessageFormat.format(Messages.getString("file.XLFHandler.logger17"), filePath), e);
    } finally {
        vn.pop();
    }
    return new String[] { srcLang, sbTMX.toString() };
}
Also used : XPathParseException(com.ximpleware.XPathParseException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) VTDGen(com.ximpleware.VTDGen) VTDNav(com.ximpleware.VTDNav)

Example 23 with NavException

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

the class XLFHandler method refreshRowIdsByFilterXPath.

/**
	 * 更新可编辑文本段唯一标识的集合(rowIds)
	 * @param filterXPath
	 *            ;
	 */
private void refreshRowIdsByFilterXPath(String filterXPath) {
    // 清楚缓存的翻译单元
    resetCache();
    // 清除之前的可编辑文本段
    rowIds.clear();
    AutoPilot ap = new AutoPilot();
    for (Entry<String, VTDNav> entry : vnMap.entrySet()) {
        String fileName = entry.getKey();
        VTDNav vn = entry.getValue().duplicateNav();
        ap.bind(vn);
        ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
        ap.declareXPathNameSpace(hsNSPrefix, hsR7NSUrl);
        try {
            ap.selectXPath(filterXPath);
            while (ap.evalXPath() != -1) {
                String rowId = RowIdUtil.getRowId(vn, fileName);
                if (rowId != null) {
                    rowIds.add(rowId);
                }
            }
        } catch (XPathParseException e) {
            LOGGER.error("", e);
            e.printStackTrace();
        } catch (XPathEvalException e) {
            LOGGER.error("", e);
            e.printStackTrace();
        } catch (NavException e) {
            LOGGER.error("", e);
            e.printStackTrace();
        }
    }
}
Also used : XPathParseException(com.ximpleware.XPathParseException) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) VTDNav(com.ximpleware.VTDNav)

Example 24 with NavException

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

the class XLFHandler method getTMXFileContent.

/**
	 * 根据同一个 XLIFF 文件中的 rowId 生成 TMX 文件
	 * @param list
	 *            rowId
	 * @param creationTool
	 *            创建工具
	 * @param creationToolVersion
	 *            创建工具版本
	 * @param srcName
	 *            源语言
	 * @param monitor
	 *            进度条
	 * @return TMX 文件
	 */
public StringBuffer getTMXFileContent(List<String> list, String creationTool, String creationToolVersion, String srcName, IProgressMonitor monitor) {
    if (list == null || list.size() == 0) {
        return new StringBuffer();
    }
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }
    monitor.beginTask(Messages.getString("file.XLFHandler.task3"), list.size());
    if (monitor.isCanceled())
        return new StringBuffer();
    StringBuffer re = new StringBuffer();
    re.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    re.append("<tmx version=\"1.4b\">");
    re.append("<header creationtool=\"" + creationTool + "\" creationtoolversion=\"" + creationToolVersion + "\" srclang=\"" + srcName + "\" adminlang=\"en\" datatype=\"xml\" o-tmf=\"XLIFF\" segtype=\"paragraph\">");
    re.append("</header>");
    re.append("<body>");
    VTDNav vn = getVTDNavByRowId(list.get(0));
    AutoPilot ap = new AutoPilot(vn);
    VTDUtils vu = null;
    try {
        vu = new VTDUtils(vn);
    } catch (NavException e) {
        LOGGER.error("", e);
        e.printStackTrace();
        monitor.done();
    }
    String defaultSrcLang = "";
    String defaultTgtLang = "";
    String fileXPath = RowIdUtil.getFileXpathByRowId(list.get(0));
    if (vu.pilot(ap, fileXPath) != -1) {
        defaultSrcLang = vu.getValue(ap, "./@source-language");
        defaultTgtLang = vu.getValue(ap, "./@target-language");
    }
    if (defaultTgtLang == null) {
        defaultTgtLang = "";
    }
    for (String rowId : list) {
        if (monitor.isCanceled())
            return new StringBuffer();
        String tuXPath = RowIdUtil.parseRowIdToXPath(rowId);
        try {
            ap.selectXPath(tuXPath);
            ap.evalXPath();
        } catch (XPathParseException e) {
            LOGGER.error("", e);
            e.printStackTrace();
            monitor.done();
        } catch (XPathEvalException e) {
            LOGGER.error("", e);
            e.printStackTrace();
            monitor.done();
        } catch (NavException e) {
            LOGGER.error("", e);
            e.printStackTrace();
            monitor.done();
        }
        re.append("<tu ");
        // 添加tu的属性
        boolean hasTuId = false;
        String id = null;
        String attrNameXp = "./@*[name]";
        String attrValueXp = "./@";
        List<String> tuPropNames = vu.getValues(ap, attrNameXp);
        for (String name : tuPropNames) {
            String value = vu.getValue(ap, attrValueXp + name);
            re.append(name + "=\"" + value + "\" ");
            if (name.equals("id")) {
                id = value;
            }
            if (!hasTuId) {
                if (name.equals("tuid")) {
                    hasTuId = true;
                }
            }
        }
        if (!hasTuId) {
            re.append("tuid=\"" + genTuId(rowId, id) + "\"");
        }
        re.append(">");
        String typeXp = "./prop-group/prop/@prop-type";
        List<String> typeValues = vu.getValues(ap, typeXp);
        if (typeValues != null) {
            for (String typeValue : typeValues) {
                re.append("<prop type=\"" + typeValue + "\">");
                re.append(vu.getValue(ap, "./prop-group/prop[@prop-type='" + typeValue + "']/text()"));
                re.append("</prop>");
            }
        }
        // HS的自定义属性组
        ap.declareXPathNameSpace(hsNSPrefix, hsR7NSUrl);
        String hsPropXp = "./hs:prop-group/prop/@prop-type";
        typeValues = vu.getValues(ap, hsPropXp);
        if (typeValues != null) {
            for (String typeValue : typeValues) {
                re.append("<prop type=\"" + typeValue + "\">");
                re.append(vu.getValue(ap, "./hs:prop-group/prop[@prop-type='" + typeValue + "']/text()"));
                re.append("</prop>");
            }
        }
        // 添加tuv(source)
        re.append("<tuv ");
        // 添加tuv(source)属性
        attrNameXp = "./source/@*[name]";
        attrValueXp = "./source/@";
        List<String> sourcePropNames = vu.getValues(ap, attrNameXp);
        if (sourcePropNames != null) {
            for (String name : sourcePropNames) {
                String value = vu.getValue(ap, attrValueXp + name);
                re.append(name + "=\"" + value + "\" ");
            }
        }
        /*
			 * source节点可能没有xml:lang属性,如果没有,则要去file节点去取source-language(Required)属性的值
			 */
        if (sourcePropNames == null || !sourcePropNames.contains("xml:lang")) {
            re.append("xml:lang=\"" + defaultSrcLang + "\"");
        }
        re.append(">");
        // 添加上下文prop
        re.append("<prop type=\"x-preContext\">");
        re.append(getContext(vu, ap, contextNum, true));
        re.append("</prop>");
        re.append("<prop type=\"x-nextContext\">");
        re.append(getContext(vu, ap, contextNum, false));
        re.append("</prop>");
        String sourceTextXp = "./source/text()";
        re.append("<seg>").append(vu.getValue(ap, sourceTextXp)).append("</seg>");
        re.append("</tuv>");
        // 添加tuv(target)
        re.append("<tuv ");
        // 添加tuv(target)属性
        attrNameXp = "./target/@*[name]";
        attrValueXp = "./target/@";
        List<String> targetPropNames = vu.getValues(ap, attrNameXp);
        if (targetPropNames != null) {
            for (String name : targetPropNames) {
                String value = vu.getValue(ap, attrValueXp + name);
                re.append(name + "=\"" + value + "\" ");
            }
        }
        /*
			 * target节点可能没有xml:lang属性,如果没有,则要去file节点去取target-language(Optional)属性的值
			 */
        if (targetPropNames == null || !targetPropNames.contains("xml:lang")) {
            re.append("xml:lang=\"" + defaultTgtLang + "\"");
        }
        re.append(">");
        String targetTextXp = "./target/text()";
        re.append("<seg>").append(vu.getValue(ap, targetTextXp)).append("</seg>");
        re.append("</tuv>");
        re.append("</tu>");
        monitor.worked(1);
    }
    re.append("</body>");
    re.append("</tmx>");
    monitor.done();
    return re;
}
Also used : XPathParseException(com.ximpleware.XPathParseException) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) NavException(com.ximpleware.NavException) XPathEvalException(com.ximpleware.XPathEvalException) VTDNav(com.ximpleware.VTDNav)

Example 25 with NavException

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

the class XLFHandler method getMatchOfSegments.

/**
	 * 获取翻译匹配率达到 <code>minMatchQuality</code> 的匹配
	 * @param minMatchQuality
	 *            最低匹配率
	 */
public Map<String, String> getMatchOfSegments(final int minMatchQuality) {
    final HashMap<String, String> map = new HashMap<String, String>();
    handleAllSegment(new PerFileHandler() {

        public void handle(String fileName, VTDUtils vu, AutoPilot ap, XMLModifier xm) throws ModifyException, XPathParseException, XPathEvalException, NavException, UnsupportedEncodingException {
            ap.selectXPath("/xliff/file/body//trans-unit[translate(alt-trans/@match-quality, '%', '')>=" + minMatchQuality + "]");
            AutoPilot tempAp = new AutoPilot(vu.getVTDNav());
            while (ap.evalXPath() != -1) {
                String rowId = RowIdUtil.getRowId(vu.getVTDNav(), fileName);
                if (isApproved(rowId) || isLocked(rowId)) {
                    // 已经批准或者锁定的,跳过。
                    continue;
                }
                String tuXPath = RowIdUtil.parseRowIdToXPath(rowId);
                if (vu.pilot(tempAp, tuXPath) != -1) {
                    String tgt = vu.getValue(tempAp, "./alt-trans[translate(@match-quality, '%', '')>=" + minMatchQuality + "]/target/text()");
                    if (tgt != null) {
                        // 当前 Target 的值
                        String currentTgt = vu.getValue(tempAp, "./target/text()");
                        if (!tgt.equals(currentTgt)) {
                            map.put(rowId, tgt);
                        }
                    }
                }
            }
            saveAndReparse(xm, fileName);
        }
    });
    return map;
}
Also used : XPathParseException(com.ximpleware.XPathParseException) XMLModifier(com.ximpleware.XMLModifier) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException) ModifyException(com.ximpleware.ModifyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

NavException (com.ximpleware.NavException)93 AutoPilot (com.ximpleware.AutoPilot)70 XPathParseException (com.ximpleware.XPathParseException)70 XPathEvalException (com.ximpleware.XPathEvalException)67 VTDNav (com.ximpleware.VTDNav)63 VTDUtils (net.heartsome.xml.vtdimpl.VTDUtils)58 XMLModifier (com.ximpleware.XMLModifier)31 ModifyException (com.ximpleware.ModifyException)29 ArrayList (java.util.ArrayList)22 IOException (java.io.IOException)21 VTDGen (com.ximpleware.VTDGen)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 HashMap (java.util.HashMap)13 TranscodeException (com.ximpleware.TranscodeException)12 ParseException (com.ximpleware.ParseException)11 FileOutputStream (java.io.FileOutputStream)11 List (java.util.List)10 LinkedList (java.util.LinkedList)9 FileNotFoundException (java.io.FileNotFoundException)8 LinkedHashMap (java.util.LinkedHashMap)8