Search in sources :

Example 21 with XMLModifier

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

the class TSFileHandler method openFile.

@Override
public Map<String, Object> openFile(File file, int tuCount) {
    long start = System.currentTimeMillis();
    // 验证文件是否存在
    if (file == null || !file.exists()) {
        String errorMsg = Messages.getString("file.TSFileHandler.logger5");
        logger.error(errorMsg);
        return getErrorResult(errorMsg, null);
    }
    // 判断是否还有缓存空间。
    boolean canCache = tuCount < TU_CACHE_SIZE;
    // 当前文件中解析并缓存翻译单元计数器。
    int parsedTuCount = 0;
    // 当前文件未解析缓存的翻译单元计数器。
    int noParseTuCount = 0;
    String filename = file.getAbsolutePath();
    int fileIndex = 1;
    // 解析文件并获取索引
    VTDGen vgRead = new VTDGen();
    if (vgRead.parseFile(filename, true)) {
        VTDNav vnRead = vgRead.getNav();
        VTDUtils vu = null;
        try {
            vu = new VTDUtils(vnRead);
            // 创建临时文件
            File tmpFile = createTmpFile();
            XMLModifier xm = new XMLModifier(vnRead);
            FileOutputStream fos = new FileOutputStream(tmpFile);
            xm.output(fos);
            fos.close();
            tmpFileMap.put(filename, tmpFile.getAbsolutePath());
            filesChangeStatus.put(filename, false);
        } catch (ModifyException e) {
            String errorMsg = MessageFormat.format(Messages.getString("file.TSFileHandler.logger6"), filename);
            logger.error(errorMsg, e);
            return getErrorResult(errorMsg, e);
        } catch (TranscodeException e) {
            String errorMsg = MessageFormat.format(Messages.getString("file.TSFileHandler.logger7"), filename);
            logger.error(errorMsg, e);
            return getErrorResult(errorMsg, e);
        } catch (IOException e) {
            String errorMsg = MessageFormat.format(Messages.getString("file.TSFileHandler.logger8"), filename);
            logger.error(errorMsg, e);
            return getErrorResult(errorMsg, e);
        } catch (NavException e) {
            String errorMsg = Messages.getString("file.TSFileHandler.logger9");
            logger.error(errorMsg, e);
            return getErrorResult(errorMsg, e);
        }
        // 创建翻译单元集合缓存。
        Vector<TransUnitBean> tusCache = new Vector<TransUnitBean>();
        // 创建翻译单元索引集合缓存。
        Vector<String> tuIndexCache = new Vector<String>();
        // 初始化文件节点属性集合。
        fileAttrs = new Hashtable<Integer, Hashtable<String, String>>();
        AutoPilot apFile = new AutoPilot(vnRead);
        String fileNode = "/xliff/file";
        try {
            apFile.selectXPath(fileNode);
            while (apFile.evalXPath() != -1) {
                fileAttrs.put(fileIndex, vu.getCurrentElementAttributs());
                AutoPilot apTU = new AutoPilot(vnRead);
                apTU.selectXPath("body//trans-unit");
                vnRead.push();
                while (apTU.evalXPath() != -1) {
                    // 如果缓冲区未满,则解析文件内容并缓存,否则只计数,不解析内容。
                    if (canCache) {
                        String tuid = "";
                        String srcText = "";
                        String srcContent = "";
                        String tgtText = "";
                        String tgtContent = "";
                        Hashtable<String, String> srcProps = null;
                        Hashtable<String, String> tgtProps = null;
                        // 取翻译单元所有属性
                        String tmpNode = "";
                        vnRead.push();
                        Hashtable<String, String> tuProps = vu.getCurrentElementAttributs();
                        vnRead.pop();
                        tuid = tuProps.get("id");
                        // 取翻译单元源节点完整文本,含内部标记。
                        vnRead.push();
                        tmpNode = "./source";
                        srcContent = vu.getElementContent(tmpNode);
                        // vnRead.pop();
                        // 取翻译单元源文本。
                        // vnRead.push();
                        srcText = vu.getElementPureText();
                        // 取翻译单元源节点属性。
                        srcProps = vu.getCurrentElementAttributs();
                        vnRead.pop();
                        // 取翻译单元目标节点完整文本,含内部标记。
                        vnRead.push();
                        tmpNode = "./target";
                        tgtContent = vu.getElementContent(tmpNode);
                        // vnRead.pop();
                        // 取翻译单元目标文本。
                        // vnRead.push();
                        tgtText = vu.getElementPureText();
                        // 取翻译单元目标节点属性。
                        tgtProps = vu.getCurrentElementAttributs();
                        vnRead.pop();
                        // 获取所有的 alttrans 匹配节点。
                        vnRead.push();
                        Vector<AltTransBean> matches = getAltTrans(vu);
                        vnRead.pop();
                        // 构建翻译单元对象,存储节点信息
                        TransUnitBean tub = new TransUnitBean(tuid, srcContent, srcText);
                        tub.setTuProps(tuProps);
                        tub.setSrcProps(srcProps);
                        tub.setTgtContent(tgtContent);
                        tub.setTgtText(tgtText);
                        tub.setTgtProps(tgtProps);
                        tub.setMatches(matches);
                        vnRead.push();
                        tub.setNotes(getNotes(vu));
                        vnRead.pop();
                        vnRead.push();
                        tub.setPropgroups(getPrpoGroups(vu));
                        vnRead.pop();
                        tusCache.add(tub);
                        tuIndexCache.add(filename + ";" + fileIndex + ";" + tuid);
                        // 解析的翻译单元节点计数
                        parsedTuCount++;
                        if (tuCount + parsedTuCount == TU_CACHE_SIZE) {
                            canCache = false;
                        }
                    } else {
                        // 未解析的翻译单元节点计数
                        noParseTuCount++;
                    }
                }
                vnRead.pop();
                // 文件节点索引计数
                fileIndex++;
            }
            transunits.put(filename, tusCache);
            tuIndexs.put(filename, tuIndexCache);
            actualTuCount.put(filename, parsedTuCount + noParseTuCount);
            accessHistory.put(filename, "");
        } catch (XPathEvalException e) {
            String errorMsg = Messages.getString("file.TSFileHandler.logger10");
            logger.error(errorMsg, e);
            return getErrorResult(errorMsg, e);
        } catch (NavException e) {
            String errorMsg = Messages.getString("file.TSFileHandler.logger11");
            logger.error(errorMsg, e);
            return getErrorResult(errorMsg, e);
        } catch (XPathParseException e) {
            String errorMsg = Messages.getString("file.TSFileHandler.logger12");
            logger.error(errorMsg, e);
            return getErrorResult(errorMsg, e);
        }
    } else {
        String errorMsg = MessageFormat.format(Messages.getString("file.TSFileHandler.logger13"), filename);
        logger.error(errorMsg);
        return getErrorResult(errorMsg, null);
    }
    long end = System.currentTimeMillis();
    // 输出结果
    long resultMS = end - start;
    long resultS = resultMS / 1000;
    long resultM = resultMS / (1000 * 60);
    System.gc();
    logger.info(Messages.getString("file.TSFileHandler.logger14"), new Object[] { resultM, resultS, resultMS });
    Map<String, Object> result = getSuccessResult();
    result.put("CurCachedTuCount", Integer.valueOf(parsedTuCount));
    result.put("TotalCachedTuCount", Integer.valueOf(parsedTuCount + tuCount));
    return result;
}
Also used : XMLModifier(com.ximpleware.XMLModifier) XPathParseException(com.ximpleware.XPathParseException) TransUnitBean(net.heartsome.cat.ts.core.bean.TransUnitBean) AltTransBean(net.heartsome.cat.ts.core.bean.AltTransBean) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) ModifyException(com.ximpleware.ModifyException) Vector(java.util.Vector) Hashtable(java.util.Hashtable) NavException(com.ximpleware.NavException) XPathEvalException(com.ximpleware.XPathEvalException) VTDGen(com.ximpleware.VTDGen) IOException(java.io.IOException) TranscodeException(com.ximpleware.TranscodeException) AutoPilot(com.ximpleware.AutoPilot) FileOutputStream(java.io.FileOutputStream) VTDNav(com.ximpleware.VTDNav) File(java.io.File)

Example 22 with XMLModifier

use of com.ximpleware.XMLModifier 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 23 with XMLModifier

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

the class XLFHandler method deleteNodeByXpath.

/**
	 * 从当前xlfPath的文件中删除xpath指定的内容 Add By Jason
	 * @param xlfPath
	 *            文件
	 * @param xpath
	 *            如当前VN定位在trans-unit节点,则./target|./alt-trans 为删除所有的target节点和alt-trans节点 ;
	 */
public void deleteNodeByXpath(String xlfPath, String xpath) {
    VTDNav vn = vnMap.get(xlfPath);
    Assert.isNotNull(vn, Messages.getString("file.XLFHandler.msg4") + xlfPath);
    try {
        VTDUtils vu = new VTDUtils(vn);
        XMLModifier xm = vu.delete(xpath, VTDUtils.PILOT_TO_END);
        saveAndReparse(xm, xlfPath);
    } catch (Exception e) {
        LOGGER.error("", e);
        e.printStackTrace();
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) VTDNav(com.ximpleware.VTDNav) NavException(com.ximpleware.NavException) CoreException(org.eclipse.core.runtime.CoreException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) XPathParseException(com.ximpleware.XPathParseException) FileNotFoundException(java.io.FileNotFoundException) XQException(javax.xml.xquery.XQException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TranscodeException(com.ximpleware.TranscodeException) XPathEvalException(com.ximpleware.XPathEvalException) IOException(java.io.IOException) ModifyException(com.ximpleware.ModifyException)

Example 24 with XMLModifier

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

the class XLFHandler method unlockSegment.

/**
	 * 给当前界面所显示的文本段解锁 robert 2012-09-24
	 */
public void unlockSegment() {
    Map<String, List<String>> groupRowIdMap = RowIdUtil.groupRowIdByFileName(rowIds);
    for (Entry<String, List<String>> entry : groupRowIdMap.entrySet()) {
        String filePath = entry.getKey();
        List<String> rowIdList = entry.getValue();
        VTDNav vn = vnMap.get(filePath);
        Assert.isNotNull(vn, Messages.getString("file.XLFHandler.msg4") + filePath);
        AutoPilot ap = new AutoPilot(vn);
        boolean isUpdate = false;
        try {
            XMLModifier xm = new XMLModifier(vn);
            for (String rowId : rowIdList) {
                ap.selectXPath(RowIdUtil.parseRowIdToXPath(rowId));
                if (ap.evalXPath() != -1) {
                    int index = vn.getAttrVal("translate");
                    if (index != -1 && "no".equalsIgnoreCase(vn.toString(index))) {
                        xm.removeAttribute(index - 1);
                        isUpdate = true;
                    }
                }
            }
            if (isUpdate) {
                saveAndReparse(xm, filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) AutoPilot(com.ximpleware.AutoPilot) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) VTDNav(com.ximpleware.VTDNav) NavException(com.ximpleware.NavException) CoreException(org.eclipse.core.runtime.CoreException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) XPathParseException(com.ximpleware.XPathParseException) FileNotFoundException(java.io.FileNotFoundException) XQException(javax.xml.xquery.XQException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TranscodeException(com.ximpleware.TranscodeException) XPathEvalException(com.ximpleware.XPathEvalException) IOException(java.io.IOException) ModifyException(com.ximpleware.ModifyException)

Example 25 with XMLModifier

use of com.ximpleware.XMLModifier 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

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