Search in sources :

Example 16 with XMLModifier

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

the class ExportDocx method addTagRIdToRels.

/**
	 * 给标记的 r:id 属性添加关系申明
	 */
private void addTagRIdToRels() throws Exception {
    VTDGen vg = new VTDGen();
    String docRelsPath = docxFolderPath + File.separator + "word" + File.separator + "_rels" + File.separator + "document.xml.rels";
    boolean parseResult = vg.parseFile(docRelsPath, true);
    if (!parseResult) {
        throw new Exception(MessageFormat.format("文件{0}解析失败!", new Object[] { docRelsPath }));
    }
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    XMLModifier xm = new XMLModifier(vn);
    ap.selectXPath("/Relationships");
    if (ap.evalXPath() != -1) {
        String tagRelationShip = "<Relationship Id=\"" + tagRId + "\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\" Target=\"http://null\" TargetMode=\"External\"/>";
        xm.insertBeforeTail(tagRelationShip);
        xm.output(docRelsPath);
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) AutoPilot(com.ximpleware.AutoPilot) VTDGen(com.ximpleware.VTDGen) VTDNav(com.ximpleware.VTDNav)

Example 17 with XMLModifier

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

the class ImportDocxDialog method beginImport.

/**
	 * 开始导入功能
	 */
public boolean beginImport(final String docxPath) throws Exception {
    if (xliffEditor == null || xliffEditor.getXLFHandler() == null) {
        xlfHandler = new XLFHandler();
    } else {
        xlfHandler = xliffEditor.getXLFHandler();
        Display.getDefault().syncExec(new Runnable() {

            @Override
            public void run() {
                HsMultiActiveCellEditor.commit(true);
            }
        });
        xm = new XMLModifier(xlfHandler.getVnMap().get(xliffFullPath));
        xlfHandler.saveAndReparse(xm, xliffFullPath);
    }
    // 开始解析 xliff 文件
    tempXlfHandler = new XLFHandler();
    parseXliff(tempXlfHandler);
    // UNDO 这里还应判断导入时两个文件是否对应,
    try {
        ImportDocx importWord = new ImportDocx(docxPath, xliffFullPath);
        List<RowBean> rowList = importWord.getDataFromWord();
        hasComment = importWord.isHasComment();
        // 现在开始判断每个tu 节点的标记是否异常。若有异常进行提示
        rowListFor: for (RowBean rowBean : rowList) {
            String rowId = rowBean.getRowId();
            if (rowId == null || rowId.length() <= 0) {
                continue rowListFor;
            }
            if (curRowIsLocked(rowId)) {
                rowBean.setLocked(true);
                continue rowListFor;
            }
            String srcText = getSrcTextFromXliffByRowId(rowId);
            List<String> xliffSrcTagList = getTagFromSrcText(srcText);
            List<String> xliffTgtTagList = new ArrayList<String>();
            xliffTgtTagList.addAll(xliffSrcTagList);
            // 获取 rowBean 中源文的标记
            List<TagBean> rowSrcTagList = new ArrayList<TagBean>();
            for (Object object : rowBean.getSrcElement()) {
                if (object instanceof TagBean) {
                    rowSrcTagList.add((TagBean) object);
                }
            }
            // 0、首先验证 word 文档中的当前行能否找到与之对应的 xliff 文件
            if (srcText == null) {
                errorList.add(new ErrorBean(rowBean.getIndex(), true, DocxConstant.ERROR_notFindTU));
                errorRowSet.add(rowBean.getRowId());
                continue rowListFor;
            }
            // 1、首先验证源文标记是否缺失
            if (rowSrcTagList.size() < xliffSrcTagList.size()) {
                errorList.add(new ErrorBean(rowBean.getIndex(), true, DocxConstant.ERROR_tagLose));
                errorRowSet.add(rowBean.getRowId());
                continue rowListFor;
            }
            // 2、验证word源文标记是否多出
            if (rowSrcTagList.size() > xliffSrcTagList.size()) {
                errorList.add(new ErrorBean(rowBean.getIndex(), true, DocxConstant.ERROR_tagMore));
                errorRowSet.add(rowBean.getRowId());
                continue rowListFor;
            }
            // UNDO 这里还应确定导出的标记是否发生改变
            for (TagBean bean : rowSrcTagList) {
                String rowTagText = bean.getText();
                for (int i = 0; i < xliffSrcTagList.size(); i++) {
                    String xlfTagText = xliffSrcTagList.get(i);
                    if (xlfTagText.indexOf(rowTagText) == 0) {
                        if (!xlfTagText.equals(rowTagText)) {
                            bean.setText(xlfTagText);
                        }
                        xliffSrcTagList.remove(i);
                        bean.setTagType(DocxCommonFuction.getTagType(xlfTagText));
                        break;
                    }
                }
            }
            if (xliffSrcTagList.size() > 0) {
                // docx 文档中的标记被更换了
                errorList.add(new ErrorBean(rowBean.getIndex(), true, DocxConstant.ERROR_tagNotSame));
                errorRowSet.add(rowBean.getRowId());
                continue rowListFor;
            }
            int startTag = 0;
            for (TagBean bean : rowSrcTagList) {
                if (bean.getTagType() == DocxConstant.PAIRSTAR) {
                    startTag++;
                } else if (bean.getTagType() == DocxConstant.PAIREND) {
                    startTag--;
                }
                if (startTag < 0) {
                    errorList.add(new ErrorBean(rowBean.getIndex(), true, DocxConstant.ERROR_tagPostionError));
                    errorRowSet.add(rowBean.getRowId());
                    continue rowListFor;
                }
            }
            // 4、验证 目标文本段中标记错误,或者位置不对应的情况
            // 先获得word 中目标文本中的标记
            // 获取 rowBean 中源文的标记
            List<TagBean> rowTgtTagList = new ArrayList<TagBean>();
            for (Object object : rowBean.getTgtElement()) {
                if (object instanceof TagBean) {
                    rowTgtTagList.add((TagBean) object);
                }
            }
            int modifiedTagSum = 0;
            for (TagBean bean : rowTgtTagList) {
                String rowTagText = bean.getText();
                // 因为标记不允许修改,因此在 xliff 中,目标文本中的标记就是源文中的标记
                for (int i = 0; i < xliffTgtTagList.size(); i++) {
                    String xlfTagText = xliffTgtTagList.get(i);
                    if (xlfTagText.indexOf(rowTagText) == 0) {
                        if (!xlfTagText.equals(rowTagText)) {
                            bean.setText(xlfTagText);
                        }
                        xliffTgtTagList.remove(i);
                        modifiedTagSum++;
                        bean.setTagType(DocxCommonFuction.getTagType(xlfTagText));
                        break;
                    }
                }
            }
            if (modifiedTagSum != rowTgtTagList.size()) {
                // docx 文档中的标记被更换了
                errorList.add(new ErrorBean(rowBean.getIndex(), false, DocxConstant.ERROR_tagNotSame));
                errorRowSet.add(rowBean.getRowId());
                continue rowListFor;
            }
            startTag = 0;
            for (TagBean bean : rowTgtTagList) {
                if (bean.getTagType() == DocxConstant.PAIRSTAR) {
                    startTag++;
                } else if (bean.getTagType() == DocxConstant.PAIREND) {
                    startTag--;
                }
                if (startTag < 0) {
                    errorList.add(new ErrorBean(rowBean.getIndex(), false, DocxConstant.ERROR_tagPostionError));
                    errorRowSet.add(rowBean.getRowId());
                    continue rowListFor;
                }
            }
            if (startTag != 0) {
                errorList.add(new ErrorBean(rowBean.getIndex(), false, DocxConstant.ERROR_pairTagError));
                errorRowSet.add(rowBean.getRowId());
            }
        }
        // 验证完后,开始导入功能,如果有错误提示信息,开始提示
        if (errorList.size() > 0) {
            StringBuffer errorSB = new StringBuffer();
            errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip1"));
            for (ErrorBean bean : errorList) {
                errorSB.append(MessageFormat.format(Messages.getString("ImportDocxDialog.import.errorTip2"), bean.getIndex()));
                if (bean.getErrorType() == DocxConstant.ERROR_notFindTU) {
                    errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip3"));
                    continue;
                }
                if (bean.isSrc()) {
                    errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip4"));
                } else {
                    errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip5"));
                }
                switch(bean.getErrorType()) {
                    case DocxConstant.ERROR_tagLose:
                        errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip6"));
                        break;
                    case DocxConstant.ERROR_tagMore:
                        errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip7"));
                        break;
                    case DocxConstant.ERROR_tagPostionError:
                        errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip8"));
                        break;
                    case DocxConstant.ERROR_tagNotSame:
                        errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip9"));
                        break;
                    case DocxConstant.ERROR_pairTagError:
                        errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip11"));
                        break;
                    default:
                        break;
                }
            }
            errorSB.append(Messages.getString("ImportDocxDialog.import.errorTip10"));
            final String errorTip = errorSB.toString();
            Display.getDefault().syncExec(new Runnable() {

                @Override
                public void run() {
                    ErrorTipDialog errorDialog = new ErrorTipDialog(getShell(), errorTip);
                    int result = errorDialog.open();
                    if (result == IDialogConstants.CANCEL_ID) {
                        continuImport = false;
                    }
                }
            });
            if (!continuImport) {
                return false;
            }
            String rowId = "";
            // 先将 有错误的文本段进行清除
            for (int i = 0; i < rowList.size(); i++) {
                rowId = rowList.get(i).getRowId();
                if (errorRowSet.contains(rowId)) {
                    rowList.remove(i);
                    i--;
                }
            }
        }
        importDocxToXliffList(rowList);
        if (xliffEditor != null) {
            parseXliff(xlfHandler);
            Display.getDefault().syncExec(new Runnable() {

                @Override
                public void run() {
                    xliffEditor.reloadData();
                    HsMultiCellEditorControl.activeSourceAndTargetCell(xliffEditor);
                }
            });
        }
    } catch (final FlagErrorException e) {
        Display.getDefault().syncExec(new Runnable() {

            @Override
            public void run() {
                MessageDialog.openWarning(Display.getDefault().getActiveShell(), Messages.getString("all.dialog.warning"), e.getMessage());
            }
        });
        LOGGER.error(e.getMessage(), e);
        return false;
    } catch (Exception e) {
        LOGGER.error(Messages.getString("ImportDocxDialog.LOGGER.logger2"), e);
    }
    return true;
}
Also used : XMLModifier(com.ximpleware.XMLModifier) FlagErrorException(net.heartsome.cat.ts.ui.docx.common.FlagErrorException) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) FlagErrorException(net.heartsome.cat.ts.ui.docx.common.FlagErrorException) ImportDocx(net.heartsome.cat.ts.ui.docx.ImportDocx) TagBean(net.heartsome.cat.ts.ui.docx.common.TagBean) ErrorBean(net.heartsome.cat.ts.ui.docx.common.ErrorBean) List(java.util.List) ArrayList(java.util.ArrayList) XLFHandler(net.heartsome.cat.ts.core.file.XLFHandler) RowBean(net.heartsome.cat.ts.ui.docx.common.RowBean)

Example 18 with XMLModifier

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

the class ReverseConversionValidateWithLibrary3 method reBuildXlf.

/**
	 * <div style='color:red;'>代替上面的 reBuildXlf 方法</div>
	 * 将要逆转换的 hsxliff 文件生成临时文件,再将这个临时文件进行处理,比如将分割的文本段拆分开来	robert	2012-11-28
	 * @param tmpXLFFile
	 */
private void reBuildXlf(String xliffPath, File tmpXLFFile) {
    //先将所有合并的文本段进行恢复成原来的样子
    try {
        ResourceUtils.copyFile(new File(xliffPath), tmpXLFFile);
        VTDGen vg = new VTDGen();
        if (!vg.parseFile(xliffPath, true)) {
            LOGGER.error(MessageFormat.format("{0} parse error!", xliffPath));
            return;
        }
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        AutoPilot childAP = new AutoPilot(vn);
        ap.declareXPathNameSpace("hs", "http://www.heartsome.net.cn/2008/XLFExtension");
        childAP.declareXPathNameSpace("hs", "http://www.heartsome.net.cn/2008/XLFExtension");
        VTDUtils vu = new VTDUtils(vn);
        XMLModifier xm = new XMLModifier(vn);
        // 先找出所有的分割与合并信息,再依序列号从高到低依次分解,合并信息是<ph id="hs-merge0~1" splitMergeIndex="0"> 这种标记
        NavigableMap<Long, SegMergeInfoBean> infoMap = new TreeMap<Long, SegMergeInfoBean>();
        ap.selectXPath("/xliff/file/body/descendant::node()" + "[(name()='group' and @ts='hs-split') or (name()='ph' and contains(@id, 'hs-merge'))]");
        int idx = -1;
        while (ap.evalXPath() != -1) {
            String nodeName = vn.toString(vn.getCurrentIndex());
            long index = -1;
            if ((idx = vn.getAttrVal("splitMergeIndex")) != -1) {
                index = Long.parseLong(vn.toString(idx));
            }
            boolean isMerge = false;
            // 如果是 ph 节点,那么这个就是合并信息
            if ("ph".equals(nodeName)) {
                isMerge = true;
                String phFrag = vu.getElementFragment();
                String phID = vn.toString(vn.getAttrVal("id"));
                String[] tuIds = vn.toString(vn.getAttrVal("id")).replace("hs-merge", "").split("~");
                String mergeFirstId = tuIds[0].trim();
                String mergeSecondId = tuIds[1].trim();
                System.out.println("mergeFirstId = " + mergeFirstId);
                System.out.println("mergeSecondId = " + mergeSecondId);
                infoMap.put(index, new SegMergeInfoBean(isMerge, phFrag, phID, mergeFirstId, mergeSecondId));
            } else {
                infoMap.put(index, new SegMergeInfoBean(isMerge));
            }
        }
        for (Entry<Long, SegMergeInfoBean> entry : infoMap.descendingMap().entrySet()) {
            Long index = entry.getKey();
            SegMergeInfoBean bean = entry.getValue();
            if (bean.isMerge()) {
                resetMerge(ap, vn, vu, xm, index, bean);
            } else {
                resetSplit(ap, childAP, vn, vu, xm, index);
            }
            vn = xm.outputAndReparse();
            xm.bind(vn);
            ap.bind(vn);
            childAP.bind(vn);
            vu.bind(vn);
        }
        xm.output(tmpXLFFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) VTDGen(com.ximpleware.VTDGen) TreeMap(java.util.TreeMap) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) IFile(org.eclipse.core.resources.IFile) File(java.io.File) VTDNav(com.ximpleware.VTDNav)

Example 19 with XMLModifier

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

the class ProjectConfiger method saveProjectConfigInfo.

/**
	 * 保存项目的配置信息
	 * @param bean
	 *            {@link ProjectInfoBean} 项目配置信息bean
	 * @throws NavException
	 * @throws ParseException
	 * @throws TranscodeException
	 * @throws ModifyException
	 * @throws IOException
	 *             ;
	 */
public boolean saveProjectConfigInfo(ProjectInfoBean bean) {
    try {
        StringBuffer content = new StringBuffer();
        content.append("\n\t<hs>");
        content.append(createProjectNameNode(bean.getProjectName()));
        content.append(createFieldListNode(bean.getMapField()));
        content.append(createAttrListNode(bean.getMapAttr()));
        content.append(createLanguageNode(bean.getSourceLang(), bean.getTargetLang()));
        content.append(createTmNode(bean.getTmDb()));
        content.append(createTbNode(bean.getTbDb()));
        content.append("\n\t</hs>");
        XMLModifier xm = vu.update("/projectDescription/text()", content.toString());
        save(xm, this.projCfgFile);
        return true;
    } catch (Exception e) {
        logger.error(Messages.getString("file.ProjectConfiger.logger1"), e);
        e.printStackTrace();
        return false;
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) NavException(com.ximpleware.NavException) TranscodeException(com.ximpleware.TranscodeException) XPathEvalException(com.ximpleware.XPathEvalException) XPathParseException(com.ximpleware.XPathParseException) IOException(java.io.IOException) ModifyException(com.ximpleware.ModifyException) ParseException(com.ximpleware.ParseException)

Example 20 with XMLModifier

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

the class TSFileHandler method xliffAnalysis.

protected Map<String, Object> xliffAnalysis(File file, int analysisMode, float eqvFactor) throws ModifyException, NavException, TranscodeException, IOException, XPathParseException, XPathEvalException {
    String filepath = file.getAbsolutePath();
    // TODO 确定报告生成的地址及文件名。
    String reportFile = "";
    if (file == null || !file.exists()) {
        String msg = Messages.getString("file.TSFileHandler.logger21");
        logger.error(msg);
        return getErrorResult(msg, null);
    }
    // 判断文件是否已打开并已修改,是则提示是否保存。
    if (filesChangeStatus.get(file.getAbsolutePath())) {
        String msg = MessageFormat.format(Messages.getString("file.TSFileHandler.logger29"), filepath);
        logger.warn(msg);
        Map<String, Object> result = getErrorResult(msg, null);
        result.put("FileChanged", true);
        return result;
    }
    VTDGen vg = new VTDGen();
    if (vg.parseFile(filepath, true)) {
        VTDNav vn = vg.getNav();
        // 创建分析报告结构
        vg.setDoc("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<hsts-analysisreport>\n</hsts-analysisreport>".getBytes());
        VTDNav vnReport = vg.getNav();
        XMLModifier xm = new XMLModifier(vnReport);
        // 分析状态信息
        if (TSFileHandler.ANALYSIS_MODE_STATUS == (analysisMode & TSFileHandler.ANALYSIS_MODE_STATUS)) {
            String xml = analysisStatus(vn.duplicateNav(), filepath, eqvFactor);
            vnReport.toElement(VTDNav.ROOT);
            xm.insertAfterElement(xml);
        }
        // 分析翻译进度
        if (TSFileHandler.ANALYSIS_MODE_TRANSLATOR_PROGRESS == (analysisMode & TSFileHandler.ANALYSIS_MODE_TRANSLATOR_PROGRESS)) {
            String xml = analysisTranslatorProgress(vn.duplicateNav(), filepath, eqvFactor);
            vnReport.toElement(VTDNav.ROOT);
            xm.insertAfterElement(xml);
        }
        // 分析编辑进度
        if (TSFileHandler.ANALYSIS_MODE_EDITOR_PROGRESS == (analysisMode & TSFileHandler.ANALYSIS_MODE_EDITOR_PROGRESS)) {
            String xml = analysisEditorProgress(vn.duplicateNav(), filepath, eqvFactor);
            vnReport.toElement(VTDNav.ROOT);
            xm.insertAfterElement(xml);
        }
        xm.output(reportFile);
    } else {
        String msg = MessageFormat.format(Messages.getString("file.TSFileHandler.logger28"), filepath);
        logger.error(msg);
        return getErrorResult(msg, null);
    }
    Map<String, Object> result = getSuccessResult();
    return result;
}
Also used : XMLModifier(com.ximpleware.XMLModifier) VTDGen(com.ximpleware.VTDGen) 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